const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-Dx0VmMvk.js","assets/radix-vendor-DA0cB_hD.js","assets/charts-vendor-Cji9-Yri.js","assets/utils-vendor-DHm03ykU.js","assets/ui-vendor-BPwaxA-i.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-CRr9x_Jp.js","assets/requestNavigation-DjrXcYns.js"])))=>i.map(i=>d[i]); var Zp=Object.defineProperty;var Xp=(t,s,a)=>s in t?Zp(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var Xn=(t,s,a)=>Xp(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as im,R as om,I as lm,F as cm,a as Jp,T as Qp,P as qp,C as ex,b as tx,O as dm,c as mm,d as sx,e as ax,f as rx,D as nx,g as ix,A as ox,h as lx,i as cx,k as dx,l as mx,m as ux,n as hx,V as px,o as xx,p as gx,q as fx,r as yx,s as bx,t as vx,u as jx,v as Nx,w as wx,x as Cx,y as Sx,z as Ax,B as kx,E as Tx,G as Dx,H as Rx,J as Px,K as Ex,L as Ix,M as Mx,N as Fx,Q as um,U as hm,W as _x,X as pm,Y as xm,Z as Lx,_ as Ox,$ as $x,a0 as Bx,a1 as Ux,a2 as Vx,a3 as zx,a4 as Hx,a5 as Wx,a6 as Gx,a7 as Kx,a8 as Yx,a9 as Zx,aa as Xx,ab as Jx}from"./radix-vendor-DA0cB_hD.js";import{a as Qx,r as p,c as gm,d as go,B as qx,C as fm,X as ym,Y as bm,T as fo,L as vm,e as Jn,P as eg,f as tg,g as sg,h as ag,i as ic,j as Pn,k as En,b as rg}from"./charts-vendor-Cji9-Yri.js";import{a as jm,f as Nm,b as Ne,d as ng,c as ig,e as og,s as Ns,g as yo,h as oc,i as lg,j as Hs,k as Pr,l as bo,m as wm,n as gs,o as bs,p as Qn,q as sa,r as cg,t as Li,u as dg,v as Oi,w as mg,x as ug,y as hg,z as pg,A as qn,B as lc,C as xg,D as Cm,E as Sm,F as vo,G as jo,H as gg,I as fg,J as Am}from"./utils-vendor-DHm03ykU.js";import{L as yg,C as Ie,a as Er,b as Je,X as ut,H as bg,c as km,U as St,F as Ee,d as Ce,S as qa,P as Ws,e as vg,f as jg,B as cs,g as ua,h as ei,i as No,j as Tm,k as er,l as Ng,m as zr,n as qe,R as Zt,I as Hr,T as Dt,o as He,p as Os,q as wg,A as Wt,r as as,M as Ps,s as In,t as Vt,u as Cg,D as ss,Z as wo,v as Pt,w as ws,x as Dm,y as Rm,z as Ir,E as yt,G as Sg,J as Ag,K as kg,N as Tg,O as Dg,Q as Rg,V as Pg,W as Eg,Y as Ig,_ as Mg,$ as Fg,a0 as _g,a1 as aa,a2 as Mn,a3 as ha,a4 as Nn,a5 as cc,a6 as an,a7 as $i,a8 as Pm,a9 as Lg,aa as ne,ab as Zs,ac as Fn,ad as ms,ae as Og,af as rs,ag as $g,ah as Bg,ai as Ug,aj as _n,ak as Rs,al as Em,am as Vg,an as zg,ao as ls,ap as ys,aq as _s,ar as Ln,as as Co,at as Hg,au as Wg,av as Im,aw as Gg,ax as Bi,ay as So,az as On,aA as Mm,aB as Fm,aC as _m,aD as Ao,aE as Kg,aF as ko,aG as Lm,aH as Yg,aI as $n,aJ as Bn,aK as To,aL as Zg,aM as Om,aN as dc,aO as fa,aP as Xg,aQ as Do,aR as Jg,aS as Va,aT as $m,aU as mc,aV as Qg,aW as qg,aX as ef,aY as Bm,aZ as tf,a_ as sf,a$ as af,b0 as rf}from"./ui-vendor-BPwaxA-i.js";import{l as nf}from"./socket-vendor-TjCxX7sJ.js";import{c as tr,a as of}from"./redux-vendor-tbZCm13o.js";import{u as Oa,a as ya,b as Um,B as lf,R as cf,c as Lt}from"./router-vendor-CRr9x_Jp.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 Ui={},uc=Qx;Ui.createRoot=uc.createRoot,Ui.hydrateRoot=uc.hydrateRoot;var Vm={exports:{}},zm={};/** * @license React * use-sync-external-store-with-selector.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Wr=p;function df(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var mf=typeof Object.is=="function"?Object.is:df,uf=Wr.useSyncExternalStore,hf=Wr.useRef,pf=Wr.useEffect,xf=Wr.useMemo,gf=Wr.useDebugValue;zm.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=hf(null);if(i.current===null){var o={hasValue:!1,value:null};i.current=o}else o=i.current;i=xf(function(){function c(x){if(!d){if(d=!0,m=x,x=r(x),n!==void 0&&o.hasValue){var g=o.value;if(n(g,x))return u=g}return u=x}if(g=u,mf(m,x))return g;var f=r(x);return n!==void 0&&n(g,f)?(m=x,g):(m=x,u=f)}var d=!1,m,u,h=a===void 0?null:a;return[function(){return c(s())},h===null?void 0:function(){return c(h())}]},[s,a,r,n]);var l=uf(t,i[0],i[1]);return pf(function(){o.hasValue=!0,o.value=l},[l]),gf(l),l};Vm.exports=zm;var ff=Vm.exports;function yf(t){t()}function bf(){let t=null,s=null;return{clear(){t=null,s=null},notify(){yf(()=>{let a=t;for(;a;)a.callback(),a=a.next})},get(){const a=[];let r=t;for(;r;)a.push(r),r=r.next;return a},subscribe(a){let r=!0;const n=s={callback:a,next:null,prev:s};return n.prev?n.prev.next=n:t=n,function(){!r||t===null||(r=!1,n.next?n.next.prev=n.prev:s=n.prev,n.prev?n.prev.next=n.next:t=n.next)}}}}var hc={notify(){},get:()=>[]};function vf(t,s){let a,r=hc,n=0,i=!1;function o(f){m();const j=r.subscribe(f);let w=!1;return()=>{w||(w=!0,j(),u())}}function l(){r.notify()}function c(){g.onStateChange&&g.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=bf())}function u(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=hc)}function h(){i||(i=!0,m())}function x(){i&&(i=!1,u())}const g={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:d,trySubscribe:h,tryUnsubscribe:x,getListeners:()=>r};return g}var jf=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Nf=jf(),wf=()=>typeof navigator<"u"&&navigator.product==="ReactNative",Cf=wf(),Sf=()=>Nf||Cf?p.useLayoutEffect:p.useEffect,Af=Sf(),ti=Symbol.for("react-redux-context"),si=typeof globalThis<"u"?globalThis:{};function kf(){if(!p.createContext)return{};const t=si[ti]??(si[ti]=new Map);let s=t.get(p.createContext);return s||(s=p.createContext(null),t.set(p.createContext,s)),s}var pa=kf();function Tf(t){const{children:s,context:a,serverState:r,store:n}=t,i=p.useMemo(()=>{const c=vf(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),o=p.useMemo(()=>n.getState(),[n]);Af(()=>{const{subscription:c}=i;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),o!==n.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[i,o]);const l=a||pa;return p.createElement(l.Provider,{value:i},s)}var Df=Tf;function Ro(t=pa){return function(){return p.useContext(t)}}var Hm=Ro();function Wm(t=pa){const s=t===pa?Hm:Ro(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var Rf=Wm();function Pf(t=pa){const s=t===pa?Rf:Wm(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var Ef=Pf(),If=(t,s)=>t===s;function Mf(t=pa){const s=t===pa?Hm:Ro(t),a=(r,n={})=>{const{equalityFn:i=If}=typeof n=="function"?{equalityFn:n}:n,o=s(),{store:l,subscription:c,getServerState:d}=o;p.useRef(!0);const m=p.useCallback({[r.name](h){return r(h)}}[r.name],[r]),u=ff.useSyncExternalStoreWithSelector(c.addNestedSub,l.getState,d||l.getState,m,i);return p.useDebugValue(u),u};return Object.assign(a,{withTypes:()=>a}),a}var Ff=Mf(),Vi=function(t,s){return Vi=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])},Vi(t,s)};function _f(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");Vi(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var wn=function(){return wn=Object.assign||function(s){for(var a,r=1,n=arguments.length;r0&&g[g.length-1])||v[0]!==6&&v[0]!==2)){j=0;continue}if(v[0]===3&&(!g||v[1]>g[0]&&v[1]0?setTimeout(x,C):x(null)}}window.addEventListener("storage",w),m.addToWaiting(w);var b=setTimeout(w,Math.max(0,u-Date.now()))})];case 1:return h.sent(),[2]}})})},m.addToWaiting=function(u){this.removeFromWaiting(u),m.waiters!==void 0&&m.waiters.push(u)},m.removeFromWaiting=function(u){m.waiters!==void 0&&(m.waiters=m.waiters.filter(function(h){return h!==u}))},m.notifyWaiters=function(){m.waiters!==void 0&&m.waiters.slice().forEach(function(u){return u()})},m.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()]}})})},m.prototype.releaseLock__private__=function(u){return a(this,void 0,void 0,function(){var h,x,g,f;return r(this,function(j){switch(j.label){case 0:return h=this.storageHandler===void 0?o:this.storageHandler,x=i+"-"+u,(g=h.getItemSync(x))===null?[2]:(f=JSON.parse(g)).id!==this.id?[3,2]:[4,Sa.default().lock(f.iat)];case 1:j.sent(),this.acquiredIatSet.delete(f.iat),h.removeItemSync(x),Sa.default().unlock(f.iat),m.notifyWaiters(),j.label=2;case 2:return[2]}})})},m.lockCorrector=function(u){for(var h=Date.now()-5e3,x=u,g=[],f=0;;){var j=x.keySync(f);if(j===null)break;g.push(j),f++}for(var w=!1,b=0;b.")},$f=wn(wn({},Of),{buildAuthorizeUrl:ps,buildLogoutUrl:ps,getAccessTokenSilently:ps,getAccessTokenWithPopup:ps,getIdTokenClaims:ps,loginWithRedirect:ps,loginWithPopup:ps,connectAccountWithRedirect:ps,logout:ps,handleRedirectCallback:ps,getDpopNonce:ps,setDpopNonce:ps,generateDpopProof:ps,createFetcher:ps}),Bf=p.createContext($f);(function(t){_f(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 Uf=function(t){return t===void 0&&(t=Bf),p.useContext(t)};const ai="idToken",ri="userData",Vf=()=>!0;class mt{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(ai,s)}static getIdToken(){return sessionStorage.getItem(ai)}static setUserData(s){localStorage.setItem(ri,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(ri);if(!s)return null;try{return JSON.parse(s)}catch{return null}}static clearAll(){try{sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true")}catch(s){console.warn("Could not set logout flags:",s)}try{localStorage.removeItem(ri),sessionStorage.removeItem(ai)}catch(s){console.warn("Error clearing user data:",s)}{try{sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true")}catch{}return}}static hasAccessToken(){return!!this.getUserData()}static hasRefreshToken(){return!!this.getUserData()}static isLocalhost(){return window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"||window.location.hostname===""}static isProduction(){return Vf()}}function ni(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-it,t=>Promise.reject(t));he.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;const n=!0;try{const i=mt.getRefreshToken(),o=await jm.post(`${Gm}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),c=(o.data.data||o.data).accessToken;return he(s)}catch(i){return mt.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function zf(t,s){var a,r;try{const n=await he.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.user&&mt.setUserData(o.user),o.idToken&&mt.setIdToken(o.idToken),o.accessToken&&o.refreshToken&&(mt.setAccessToken(o.accessToken),mt.setRefreshToken(o.refreshToken)),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 Hf(){var r;const t={},a=(await he.post("/auth/refresh",t)).data;if((r=a.data)!=null&&r.accessToken||a.accessToken,a.success!==!1)return"cookie-based-auth";throw new Error("Failed to refresh token")}async function rn(){const s=(await he.get("/auth/me")).data;return s.data||s}async function Wf(){var t,s;try{await he.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 Km=p.createContext(void 0);function Gf({children:t}){const[s,a]=p.useState(!1),[r,n]=p.useState(!0),[i,o]=p.useState(null),[l,c]=p.useState(null),[d,m]=p.useState(!1);p.useEffect(()=>{const b=sessionStorage.getItem("__logout_in_progress__"),C=sessionStorage.getItem("__force_logout__");if(b==="true"||C==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),mt.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(N){console.error("Error clearing storage:",N)}a(!1),o(null),n(!1),c(null);return}const v=new URLSearchParams(window.location.search);if(v.has("logout")||v.has("okta_logged_out")){mt.clearAll(),localStorage.clear(),sessionStorage.clear(),a(!1),o(null),n(!1);const N=new URLSearchParams;v.has("okta_logged_out")&&N.set("okta_logged_out","true");const k=N.toString()?`/?${N.toString()}`:"/";window.history.replaceState({},document.title,k);return}window.location.pathname!=="/login/callback"&&(mt.getUserData(),d?n(!1):h())},[d]),p.useEffect(()=>{if(!s)return;const b=async()=>{try{await j()}catch(N){console.error("Silent refresh failed:",N)}},C=10*60*1e3,v=setInterval(b,C);return()=>clearInterval(v)},[s]);const u=p.useRef(!1);p.useEffect(()=>{if(u.current||window.location.pathname!=="/login/callback")return;(async()=>{u.current=!0;const C=new URLSearchParams(window.location.search),v=C.get("code"),N=C.get("error");if(window.history.replaceState({},document.title,"/login/callback"),N){c(new Error(`Authentication error: ${N}`)),n(!1);return}if(!v){n(!1);return}try{n(!0),a(!1),c(null);const k=`${window.location.origin}/login/callback`,E=await zf(v,k);o(E.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()=>{var C;if(d){n(!1);return}const b=!0;try{if(n(!0),b){const k=mt.getUserData();try{const E=await rn();o(E),mt.setUserData(E),a(!0)}catch(E){if(((C=E==null?void 0:E.response)==null?void 0:C.status)===401)try{await j();const P=await rn();o(P),mt.setUserData(P),a(!0)}catch{mt.clearAll(),a(!1),o(null)}else E!=null&&E.isConnectionError?k?(o(k),a(!0)):(a(!1),o(null)):(mt.clearAll(),a(!1),o(null))}return}const v=mt.getAccessToken(),N=mt.getUserData();if(!v){a(!1),o(null),n(!1);return}if(ni(v))try{await j();const k=mt.getAccessToken();if(k&&!ni(k)){const E=mt.getUserData();if(E)o(E),a(!0);else try{const P=await rn();o(P),mt.setUserData(P),a(!0)}catch{mt.clearAll(),a(!1),o(null)}}else mt.clearAll(),a(!1),o(null)}catch{mt.clearAll(),a(!1),o(null)}else if(N)o(N),a(!0);else try{const k=await rn();o(k),mt.setUserData(k),a(!0)}catch{mt.clearAll(),a(!1),o(null)}}catch(v){console.error("Error checking auth status:",v),c(v),mt.clearAll(),a(!1),o(null)}finally{n(!1)}},x=async()=>{try{c(null);const b="https://royalenfield.okta.com",C="0oa18b98aari6I6eo2p8",v=`${window.location.origin}/login/callback`,N="code",k="openid profile email",E=Math.random().toString(36).substring(7),P=new URLSearchParams(window.location.search),M=P.has("logout")||P.has("okta_logged_out");let y=`${b}/oauth2/default/v1/authorize?client_id=${C}&redirect_uri=${encodeURIComponent(v)}&response_type=${N}&scope=${encodeURIComponent(k)}&state=${E}`;M&&(y+="&prompt=login"),window.location.href=y}catch(b){throw c(b),b}},g=async()=>{try{mt.getIdToken(),sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),m(!0),a(!1),o(null),c(null),n(!0);try{await Wf()}catch(N){console.error("🚪 Logout API error:",N),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const b=sessionStorage.getItem("__logout_in_progress__"),C=sessionStorage.getItem("__force_logout__");mt.clearAll(),b&&sessionStorage.setItem("__logout_in_progress__",b),C&&sessionStorage.setItem("__force_logout__",C),await new Promise(N=>setTimeout(N,100));const v=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(v)}catch(b){console.error("🚪 Logout error:",b);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const C=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(C)}catch{window.location.replace("/?logout="+Date.now())}}},f=async()=>{{if(s)return"cookie-based-auth";try{return await j(),s?"cookie-based-auth":null}catch{return null}}const b=mt.getAccessToken();if(b&&!ni(b))return b;try{return await j(),mt.getAccessToken()}catch{return null}},j=async()=>{try{const C=await Hf();return}catch(C){throw mt.clearAll(),a(!1),o(null),C}},w={isAuthenticated:s,isLoading:r,user:i,error:l,login:x,logout:g,getAccessTokenSilently:f,refreshTokenSilently:j};return e.jsx(Km.Provider,{value:w,children:t})}function Kf({children:t}){return e.jsx(Gf,{children:t})}function Gt(){const t=p.useContext(Km);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function Aa(t){return(t==null?void 0:t.role)==="ADMIN"}function br(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function Un(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const gc=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,fc=gm,Ym=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return fc(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,o=Object.keys(n).map(d=>{const m=a==null?void 0:a[d],u=i==null?void 0:i[d];if(m===null)return null;const h=gc(m)||gc(u);return n[d][h]}),l=a&&Object.entries(a).reduce((d,m)=>{let[u,h]=m;return h===void 0||(d[u]=h),d},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((d,m)=>{let{class:u,className:h,...x}=m;return Object.entries(x).every(g=>{let[f,j]=g;return Array.isArray(j)?j.includes({...i,...l}[f]):{...i,...l}[f]===j})?[...d,u,h]:d},[]);return fc(t,o,c,a==null?void 0:a.class,a==null?void 0:a.className)},Io="-",Yf=t=>{const s=Xf(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:o=>{const l=o.split(Io);return l[0]===""&&l.length!==1&&l.shift(),Zm(l,s)||Zf(o)},getConflictingClassGroupIds:(o,l)=>{const c=a[o]||[];return l&&r[o]?[...c,...r[o]]:c}}},Zm=(t,s)=>{var o;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?Zm(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(Io);return(o=s.validators.find(({validator:l})=>l(i)))==null?void 0:o.classGroupId},yc=/^\[(.+)\]$/,Zf=t=>{if(yc.test(t)){const s=yc.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},Xf=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return Qf(Object.entries(t.classGroups),a).forEach(([i,o])=>{zi(o,r,i,s)}),r},zi=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:bc(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(Jf(n)){zi(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,o])=>{zi(o,bc(s,i),a,r)})})},bc=(t,s)=>{let a=t;return s.split(Io).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},Jf=t=>t.isThemeGetter,Qf=(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,qf=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)}}},Xm="!",e0=t=>{const{separator:s,experimentalParseClassName:a}=t,r=s.length===1,n=s[0],i=s.length,o=l=>{const c=[];let d=0,m=0,u;for(let j=0;jm?u-m:void 0;return{modifiers:c,hasImportantModifier:x,baseClassName:g,maybePostfixModifierPosition:f}};return a?l=>a({className:l,parseClassName:o}):o},t0=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},s0=t=>({cache:qf(t.cacheSize),parseClassName:e0(t),...Yf(t)}),a0=/\s+/,r0=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],o=t.trim().split(a0);let l="";for(let c=o.length-1;c>=0;c-=1){const d=o[c],{modifiers:m,hasImportantModifier:u,baseClassName:h,maybePostfixModifierPosition:x}=a(d);let g=!!x,f=r(g?h.substring(0,x):h);if(!f){if(!g){l=d+(l.length>0?" "+l:l);continue}if(f=r(h),!f){l=d+(l.length>0?" "+l:l);continue}g=!1}const j=t0(m).join(":"),w=u?j+Xm:j,b=w+f;if(i.includes(b))continue;i.push(b);const C=n(f,g);for(let v=0;v0?" "+l:l)}return l};function n0(){let t=0,s,a,r="";for(;t{if(typeof t=="string")return t;let s,a="";for(let r=0;ru(m),t());return a=s0(d),r=a.cache.get,n=a.cache.set,i=l,l(c)}function l(c){const d=r(c);if(d)return d;const m=r0(c,a);return n(c,m),m}return function(){return i(n0.apply(null,arguments))}}const jt=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},Qm=/^\[(?:([a-z-]+):)?(.+)\]$/i,o0=/^\d+\/\d+$/,l0=new Set(["px","full","screen"]),c0=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,d0=/\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$/,m0=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,u0=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,h0=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,qs=t=>Ya(t)||l0.has(t)||o0.test(t),oa=t=>sr(t,"length",j0),Ya=t=>!!t&&!Number.isNaN(Number(t)),ii=t=>sr(t,"number",Ya),vr=t=>!!t&&Number.isInteger(Number(t)),p0=t=>t.endsWith("%")&&Ya(t.slice(0,-1)),Ze=t=>Qm.test(t),la=t=>c0.test(t),x0=new Set(["length","size","percentage"]),g0=t=>sr(t,x0,qm),f0=t=>sr(t,"position",qm),y0=new Set(["image","url"]),b0=t=>sr(t,y0,w0),v0=t=>sr(t,"",N0),jr=()=>!0,sr=(t,s,a)=>{const r=Qm.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},j0=t=>d0.test(t)&&!m0.test(t),qm=()=>!1,N0=t=>u0.test(t),w0=t=>h0.test(t),C0=()=>{const t=jt("colors"),s=jt("spacing"),a=jt("blur"),r=jt("brightness"),n=jt("borderColor"),i=jt("borderRadius"),o=jt("borderSpacing"),l=jt("borderWidth"),c=jt("contrast"),d=jt("grayscale"),m=jt("hueRotate"),u=jt("invert"),h=jt("gap"),x=jt("gradientColorStops"),g=jt("gradientColorStopPositions"),f=jt("inset"),j=jt("margin"),w=jt("opacity"),b=jt("padding"),C=jt("saturate"),v=jt("scale"),N=jt("sepia"),k=jt("skew"),E=jt("space"),P=jt("translate"),M=()=>["auto","contain","none"],y=()=>["auto","hidden","clip","visible","scroll"],A=()=>["auto",Ze,s],L=()=>[Ze,s],K=()=>["",qs,oa],O=()=>["auto",Ya,Ze],$=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],T=()=>["solid","dashed","dotted","double","none"],S=()=>["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"],I=()=>["","0",Ze],_=()=>["auto","avoid","all","avoid-page","page","left","right","column"],F=()=>[Ya,Ze];return{cacheSize:500,separator:":",theme:{colors:[jr],spacing:[qs,oa],blur:["none","",la,Ze],brightness:F(),borderColor:[t],borderRadius:["none","","full",la,Ze],borderSpacing:L(),borderWidth:K(),contrast:F(),grayscale:I(),hueRotate:F(),invert:I(),gap:L(),gradientColorStops:[t],gradientColorStopPositions:[p0,oa],inset:A(),margin:A(),opacity:F(),padding:L(),saturate:F(),scale:F(),sepia:I(),skew:F(),space:L(),translate:L()},classGroups:{aspect:[{aspect:["auto","square","video",Ze]}],container:["container"],columns:[{columns:[la]}],"break-after":[{"break-after":_()}],"break-before":[{"break-before":_()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...$(),Ze]}],overflow:[{overflow:y()}],"overflow-x":[{"overflow-x":y()}],"overflow-y":[{"overflow-y":y()}],overscroll:[{overscroll:M()}],"overscroll-x":[{"overscroll-x":M()}],"overscroll-y":[{"overscroll-y":M()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[f]}],"inset-x":[{"inset-x":[f]}],"inset-y":[{"inset-y":[f]}],start:[{start:[f]}],end:[{end:[f]}],top:[{top:[f]}],right:[{right:[f]}],bottom:[{bottom:[f]}],left:[{left:[f]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",vr,Ze]}],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",Ze]}],grow:[{grow:I()}],shrink:[{shrink:I()}],order:[{order:["first","last","none",vr,Ze]}],"grid-cols":[{"grid-cols":[jr]}],"col-start-end":[{col:["auto",{span:["full",vr,Ze]},Ze]}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":[jr]}],"row-start-end":[{row:["auto",{span:[vr,Ze]},Ze]}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Ze]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Ze]}],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:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[j]}],mx:[{mx:[j]}],my:[{my:[j]}],ms:[{ms:[j]}],me:[{me:[j]}],mt:[{mt:[j]}],mr:[{mr:[j]}],mb:[{mb:[j]}],ml:[{ml:[j]}],"space-x":[{"space-x":[E]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[E]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Ze,s]}],"min-w":[{"min-w":[Ze,s,"min","max","fit"]}],"max-w":[{"max-w":[Ze,s,"none","full","min","max","fit","prose",{screen:[la]},la]}],h:[{h:[Ze,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Ze,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Ze,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Ze,s,"auto","min","max","fit"]}],"font-size":[{text:["base",la,oa]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",ii]}],"font-family":[{font:[jr]}],"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",Ze]}],"line-clamp":[{"line-clamp":["none",Ya,ii]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",qs,Ze]}],"list-image":[{"list-image":["none",Ze]}],"list-style-type":[{list:["none","disc","decimal",Ze]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[w]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[w]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...T(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",qs,oa]}],"underline-offset":[{"underline-offset":["auto",qs,Ze]}],"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:L()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ze]}],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",Ze]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[w]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...$(),f0]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",g0]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},b0]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[x]}],"gradient-via":[{via:[x]}],"gradient-to":[{to:[x]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[w]}],"border-style":[{border:[...T(),"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":[w]}],"divide-style":[{divide:T()}],"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:["",...T()]}],"outline-offset":[{"outline-offset":[qs,Ze]}],"outline-w":[{outline:[qs,oa]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[w]}],"ring-offset-w":[{"ring-offset":[qs,oa]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",la,v0]}],"shadow-color":[{shadow:[jr]}],opacity:[{opacity:[w]}],"mix-blend":[{"mix-blend":[...S(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":S()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",la,Ze]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[u]}],saturate:[{saturate:[C]}],sepia:[{sepia:[N]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[u]}],"backdrop-opacity":[{"backdrop-opacity":[w]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"backdrop-sepia":[{"backdrop-sepia":[N]}],"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",Ze]}],duration:[{duration:F()}],ease:[{ease:["linear","in","out","in-out",Ze]}],delay:[{delay:F()}],animate:[{animate:["none","spin","ping","pulse","bounce",Ze]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[v]}],"scale-x":[{"scale-x":[v]}],"scale-y":[{"scale-y":[v]}],rotate:[{rotate:[vr,Ze]}],"translate-x":[{"translate-x":[P]}],"translate-y":[{"translate-y":[P]}],"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",Ze]}],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",Ze]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":L()}],"scroll-mx":[{"scroll-mx":L()}],"scroll-my":[{"scroll-my":L()}],"scroll-ms":[{"scroll-ms":L()}],"scroll-me":[{"scroll-me":L()}],"scroll-mt":[{"scroll-mt":L()}],"scroll-mr":[{"scroll-mr":L()}],"scroll-mb":[{"scroll-mb":L()}],"scroll-ml":[{"scroll-ml":L()}],"scroll-p":[{"scroll-p":L()}],"scroll-px":[{"scroll-px":L()}],"scroll-py":[{"scroll-py":L()}],"scroll-ps":[{"scroll-ps":L()}],"scroll-pe":[{"scroll-pe":L()}],"scroll-pt":[{"scroll-pt":L()}],"scroll-pr":[{"scroll-pr":L()}],"scroll-pb":[{"scroll-pb":L()}],"scroll-pl":[{"scroll-pl":L()}],"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",Ze]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[qs,oa,ii]}],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"]}}},S0=i0(C0);function ge(...t){return S0(gm(t))}const Mr=Ym("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"}}),R=p.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const o=r?im:"button";return e.jsx(o,{"data-slot":"button",className:ge(Mr({variant:s,size:a,className:t})),ref:i,...n})});R.displayName="Button";function X({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:ge("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function le({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:ge("@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 ce({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:ge("leading-none",t),...s})}function je({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:ge("text-muted-foreground",t),...s})}function J({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:ge("px-6 [&:last-child]:pb-6",t),...s})}const Mo="/assets/Re_Logo-By51taPS.png";function A0(){const{login:t,isLoading:s,error:a}=Gt(),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(X,{className:"w-full max-w-md shadow-xl",children:[e.jsx(le,{className:"space-y-1 text-center pb-6",children:e.jsxs("div",{className:"flex flex-col items-center justify-center mb-4",children:[e.jsx("img",{src:Mo,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-400 text-center truncate",children:"Approval Portal"})]})}),e.jsxs(J,{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(R,{onClick:r,disabled:s,className:"w-full h-12 text-base font-semibold bg-re-red hover:bg-re-red/90 text-white",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-white border-t-transparent"}),"Logging in..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yg,{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 eu(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Gt(),[n,i]=p.useState("exchanging");p.useEffect(()=>{if(a){i("error");return}if(s){const c=new URLSearchParams(window.location.search).get("code");i(c&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else r&&t&&i("complete")},[t,s,a,r]);const 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.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:Mo,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-400 text-center truncate",children:"Approval Portal"})]})}),e.jsxs("div",{className:"bg-white/10 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/20",children:[e.jsx("div",{className:"mb-6 flex justify-center",children:n==="error"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(Ie,{className:"w-16 h-16 text-red-500"})}),e.jsx(Ie,{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(Er,{className:"w-16 h-16 text-green-500"})}),e.jsx(Er,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Je,{className:"w-16 h-16 animate-spin text-re-red"}),e.jsx("div",{className:"absolute inset-0 border-4 rounded-full border-re-red/20"}),e.jsx("div",{className:"absolute inset-0 border-4 border-transparent border-t-re-red rounded-full animate-spin"})]})}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-white mb-2",children:n==="complete"?"Welcome Back!":n==="error"?"Authentication Error":"Authenticating"}),e.jsx("p",{className:"text-slate-300 text-sm",children: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-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Validating credentials"})]}),e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="fetching"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="fetching"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Loading your profile"})]}),n==="complete"&&e.jsxs("div",{className:"flex items-center gap-3 text-sm transition-all duration-500 text-white",children:[e.jsx("div",{className:"w-2 h-2 rounded-full transition-all duration-500 bg-green-500"}),e.jsx("span",{children:"Setting up your session"})]})]}),n==="error"&&a&&e.jsxs("div",{className:"mt-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx("p",{className:"text-red-400 text-sm",children:a.message||"An error occurred during authentication"}),e.jsx("button",{onClick:()=>{window.location.href="/"},className:"mt-4 text-sm text-red-400 hover:text-red-300 underline",children:"Return to login"})]}),n!=="error"&&n!=="complete"&&e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"h-1.5 bg-slate-700/50 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-re-red rounded-full animate-pulse",style:{animation:"progress 2s ease-in-out infinite"}})}),e.jsx("style",{children:` @keyframes progress { 0%, 100% { width: 20%; } 50% { width: 80%; } } `})]})]}),e.jsx("p",{className:"mt-6 text-slate-500 text-xs",children:n==="complete"?"Loading dashboard...":"Please wait while we secure your session"})]}),e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute top-1/4 left-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse"}),e.jsx("div",{className:"absolute bottom-1/4 right-1/4 w-96 h-96 bg-re-red/5 rounded-full blur-3xl animate-pulse delay-1000"})]})]})}const k0=Ym("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 se({className:t,variant:s,asChild:a=!1,...r}){const n=a?im:"span";return e.jsx(n,{"data-slot":"badge",className:ge(k0({variant:s}),t),...r})}function T0({isOpen:t,onClose:s}){const{user:a,isAuthenticated:r,isLoading:n,error:i}=Uf();return p.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(X,{className:"w-full max-w-2xl max-h-[90vh] overflow-auto",children:[e.jsx(le,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{children:"Authentication Debug Information"}),e.jsx(R,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(ut,{className:"h-4 w-4"})})]})}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold",children:"Status:"}),e.jsx(se,{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 D0="modulepreload",R0=function(t){return"/"+t},vc={},pn=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=R0(c),c in vc)return;vc[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const u=document.createElement("link");if(u.rel=d?"stylesheet":D0,d||(u.as="script"),u.crossOrigin="",u.href=c,l&&u.setAttribute("nonce",l),document.head.appendChild(u),d)return new Promise((h,x)=>{u.addEventListener("load",h),u.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return n.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})},Bt=p.forwardRef(({className:t,...s},a)=>e.jsx(om,{ref:a,"data-slot":"avatar",className:ge("relative flex size-10 shrink-0 overflow-hidden rounded-full",t),...s}));Bt.displayName=om.displayName;const Vn=p.forwardRef(({className:t,...s},a)=>e.jsx(lm,{ref:a,"data-slot":"avatar-image",className:ge("aspect-square size-full",t),...s}));Vn.displayName=lm.displayName;const Ut=p.forwardRef(({className:t,...s},a)=>e.jsx(cm,{ref:a,"data-slot":"avatar-fallback",className:ge("bg-muted flex size-full items-center justify-center rounded-full",t),...s}));Ut.displayName=cm.displayName;function jc({...t}){return e.jsx(Jp,{"data-slot":"dropdown-menu",...t})}function Nc({...t}){return e.jsx(Qp,{"data-slot":"dropdown-menu-trigger",...t})}function wc({className:t,sideOffset:s=4,...a}){return e.jsx(qp,{children:e.jsx(ex,{"data-slot":"dropdown-menu-content",sideOffset:s,className:ge("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 oi({className:t,inset:s,variant:a="default",...r}){return e.jsx(tx,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":a,className:ge("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 P0({...t}){return e.jsx(ax,{"data-slot":"alert-dialog",...t})}function E0({...t}){return e.jsx(sx,{"data-slot":"alert-dialog-portal",...t})}const tu=p.forwardRef(({className:t,...s},a)=>e.jsx(dm,{"data-slot":"alert-dialog-overlay",className:ge("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}));tu.displayName=dm.displayName;const su=p.forwardRef(({className:t,...s},a)=>e.jsxs(E0,{children:[e.jsx(tu,{}),e.jsx(mm,{"data-slot":"alert-dialog-content",ref:a,className:ge("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})]}));su.displayName=mm.displayName;function I0({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-header",className:ge("flex flex-col gap-2 text-center sm:text-left",t),...s})}function M0({className:t,...s}){return e.jsx("div",{"data-slot":"alert-dialog-footer",className:ge("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s})}function F0({className:t,...s}){return e.jsx(rx,{"data-slot":"alert-dialog-title",className:ge("text-lg font-semibold",t),...s})}function _0({className:t,...s}){return e.jsx(nx,{"data-slot":"alert-dialog-description",className:ge("text-muted-foreground text-sm",t),...s})}function L0({className:t,...s}){return e.jsx(ox,{className:ge(Mr(),t),...s})}function O0({className:t,...s}){return e.jsx(ix,{className:ge(Mr({variant:"outline"}),t),...s})}const da={async list(t){return(await he.get("/notifications",{params:t})).data},async getUnreadCount(){return(await he.get("/notifications/unread-count")).data},async markAsRead(t){return(await he.patch(`/notifications/${t}/read`)).data},async markAllAsRead(){return(await he.post("/notifications/mark-all-read")).data},async delete(t){return(await he.delete(`/notifications/${t}`)).data}},$0=async()=>(await he.get("/notifications/subscriptions")).data.data.subscriptions;let wa=null;function B0(){return"https://re-workflow-nt-dev.siplsolutions.com"}function Fr(t){const s=B0();return wa||(wa=nf(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),wa.on("connect",()=>{}),wa.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),wa.on("disconnect",a=>{}),wa)}function Hi(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function au(t,s){t.emit("leave:request",s)}function U0(t,s){t.emit("join:user",{userId:s})}function es({children:t,currentPage:s="dashboard",onNavigate:a,onNewRequest:r,onLogout:n}){const[i,o]=p.useState(!1),[l,c]=p.useState(!1),[d,m]=p.useState([]),[u,h]=p.useState(0),[x,g]=p.useState(!1),{user:f}=Gt(),j=()=>{var N,k;try{if(f!=null&&f.displayName&&typeof f.displayName=="string"){const E=f.displayName.split(" ").filter(Boolean);return E.length>=2?`${((N=E[0])==null?void 0:N[0])||""}${((k=E[E.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(E){return console.error("[PageLayout] Error getting user initials:",E),"U"}},w=p.useMemo(()=>{const N=[{id:"dashboard",label:"Dashboard",icon:bg},{id:"requests",label:"All Requests",icon:km}];return N.push({id:"my-requests",label:"My Requests",icon:St},{id:"open-requests",label:"Open Requests",icon:Ee},{id:"closed-requests",label:"Closed Requests",icon:Ce},{id:"shared-summaries",label:"Shared Summary",icon:qa}),N},[]),b=()=>{o(!i)},C=async N=>{var k;try{if(N.isRead||(await da.markAsRead(N.notificationId),m(E=>E.map(P=>P.notificationId===N.notificationId?{...P,isRead:!0}:P)),h(E=>Math.max(0,E-1))),N.actionUrl&&a){const E=(k=N.metadata)==null?void 0:k.requestNumber;if(E){let P=`request/${E}`;(N.notificationType==="mention"||N.notificationType==="comment"||N.notificationType==="worknote")&&(P+="?tab=worknotes"),a(P)}}g(!1)}catch(E){console.error("[PageLayout] Error handling notification click:",E)}},v=async()=>{try{await da.markAllAsRead(),m(N=>N.map(k=>({...k,isRead:!0}))),h(0)}catch(N){console.error("[PageLayout] Error marking all as read:",N)}};return p.useEffect(()=>{const N=f==null?void 0:f.userId;if(!N)return;let k=!0;(async()=>{var M,y;try{const A=await da.list({page:1,limit:4,unreadOnly:!1});if(!k)return;const L=((M=A.data)==null?void 0:M.notifications)||[];m(L),h(((y=A.data)==null?void 0:y.unreadCount)||0)}catch(A){console.error("[PageLayout] Failed to fetch notifications:",A)}})();const P=Fr();if(P){U0(P,N);const M=y=>{k&&(m(A=>[y.notification,...A].slice(0,4)),h(A=>A+1))};return P.on("notification:new",M),()=>{k=!1,P.off("notification:new",M)}}return()=>{k=!1}},[f]),p.useEffect(()=>{const N=()=>{window.innerWidth>=768?o(!0):o(!1)};return N(),window.addEventListener("resize",N),()=>window.removeEventListener("resize",N)},[]),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:Mo,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain"}),e.jsx("p",{className:"text-xs text-gray-400 text-center mt-1 truncate",children:"RE Flow"})]})}),e.jsxs("div",{className:"p-3 flex-1 overflow-y-auto",children:[e.jsx("div",{className:"space-y-2",children:w.map(N=>e.jsxs("button",{onClick:()=>{a==null||a(N.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===N.id?"bg-re-green text-white font-medium":"text-gray-300 hover:bg-gray-900 hover:text-white"}`,children:[e.jsx(N.icon,{className:"w-4 h-4 shrink-0"}),e.jsx("span",{className:"truncate",children:N.label})]},N.id))}),e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800 px-3",children:e.jsxs(R,{onClick:r,className:"w-full bg-re-green hover:bg-re-green/90 text-white text-sm font-medium",size:"sm",children:[e.jsx(Ws,{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(R,{variant:"ghost",size:"icon",onClick:b,className:"shrink-0 h-10 w-10 sidebar-toggle",children:i?e.jsx(vg,{className:"w-5 h-5 text-gray-600"}):e.jsx(jg,{className:"w-5 h-5 text-gray-600"})})}),e.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[e.jsxs(R,{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(Ws,{className:"w-4 h-4"}),"New Request"]}),e.jsxs(jc,{open:x,onOpenChange:g,children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(R,{variant:"ghost",size:"icon",className:"relative shrink-0 h-10 w-10",children:[e.jsx(cs,{className:"w-5 h-5"}),u>0&&e.jsx(se,{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(wc,{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(R,{variant:"ghost",size:"sm",className:"text-xs text-blue-600 hover:text-blue-700 h-auto p-1",onClick:N=>{N.stopPropagation(),v()},children:"Mark all as read"})]}),e.jsx("div",{className:"max-h-[400px] overflow-y-auto",children:d.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(cs,{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:d.map(N=>e.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer transition-colors ${N.isRead?"":"bg-blue-50"}`,onClick:()=>C(N),children:e.jsxs("div",{className:"flex gap-2",children:[!N.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 ${N.isRead?"font-medium":"font-semibold"}`,children:N.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:N.message}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:Nm(new Date(N.createdAt),{addSuffix:!0})})]})]})},N.notificationId))})}),d.length>0&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(R,{variant:"ghost",className:"w-full text-sm text-blue-600 hover:text-blue-700",onClick:()=>{g(!1),a==null||a("notifications")},children:"View all notifications"})})]})]}),e.jsxs(jc,{children:[e.jsx(Nc,{asChild:!0,children:e.jsxs(Bt,{className:"cursor-pointer shrink-0 h-10 w-10",children:[e.jsx(Vn,{src:(f==null?void 0:f.picture)||""}),e.jsx(Ut,{className:"bg-re-green text-white text-sm",children:j()})]})}),e.jsxs(wc,{align:"end",children:[e.jsxs(oi,{onClick:()=>a==null?void 0:a("profile"),children:[e.jsx(St,{className:"w-4 h-4 mr-2"}),"Profile"]}),e.jsxs(oi,{onClick:()=>a==null?void 0:a("settings"),children:[e.jsx(ua,{className:"w-4 h-4 mr-2"}),"Settings"]}),e.jsxs(oi,{onClick:()=>c(!0),className:"text-red-600 focus:text-red-600",children:[e.jsx(ei,{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(P0,{open:l,onOpenChange:c,children:e.jsxs(su,{children:[e.jsxs(I0,{children:[e.jsxs(F0,{className:"flex items-center gap-2",children:[e.jsx(ei,{className:"w-5 h-5 text-red-600"}),"Confirm Logout"]}),e.jsx(_0,{className:"pt-2",children:"Are you sure you want to logout? You will need to sign in again to access your account."})]}),e.jsxs(M0,{children:[e.jsx(O0,{onClick:()=>c(!1),children:"Cancel"}),e.jsxs(L0,{onClick:async()=>{if(c(!1),n)try{await n()}catch(N){console.error("🔴 Error calling onLogout:",N)}else console.error("🔴 ERROR: onLogout is undefined!")},className:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-600",children:[e.jsx(ei,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]})})]})}const Gr=()=>Ef(),ar=Ff,V0=()=>{try{const t=localStorage.getItem("dashboard_viewAsUser");return t?JSON.parse(t):!1}catch{return!1}},z0={viewAsUser:V0()},ru=tr({name:"dashboard",initialState:z0,reducers:{setViewAsUser:(t,s)=>{t.viewAsUser=s.payload,localStorage.setItem("dashboard_viewAsUser",JSON.stringify(s.payload))}}}),{setViewAsUser:H0}=ru.actions;function W0(){const[t,s]=p.useState("all"),[a,r]=p.useState(void 0),[n,i]=p.useState(void 0),[o,l]=p.useState(!1),c=p.useCallback(u=>{const h=u;s(h),h!=="custom"?(r(void 0),i(void 0),l(!1)):l(!0)},[]),d=p.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]),m=p.useCallback(()=>{r(void 0),i(void 0),l(!1),s("all")},[]);return{dateRange:t,customStartDate:a,customEndDate:n,showCustomDatePicker:o,setDateRange:s,setCustomStartDate:r,setCustomEndDate:i,setShowCustomDatePicker:l,handleDateRangeChange:c,handleApplyCustomDate:d,resetCustomDates:m}}function G0(){const[t,s]=p.useState({page:1,totalPages:1,totalRecords:0}),[a,r]=p.useState({page:1,totalPages:1,totalRecords:0}),[n,i]=p.useState({page:1,totalPages:1,totalRecords:0}),[o,l]=p.useState({page:1,totalPages:1,totalRecords:0}),c=p.useCallback((j,w,b)=>{s({page:j,totalPages:w,totalRecords:b})},[]),d=p.useCallback((j,w,b)=>{r({page:j,totalPages:w,totalRecords:b})},[]),m=p.useCallback((j,w,b)=>{i({page:j,totalPages:w,totalRecords:b})},[]),u=p.useCallback((j,w,b)=>{l({page:j,totalPages:w,totalRecords:b})},[]),h=p.useCallback((j,w)=>{j>=1&&j<=t.totalPages&&(s(b=>({...b,page:j})),w(j))},[t.totalPages]),x=p.useCallback((j,w)=>{j>=1&&j<=a.totalPages&&(r(b=>({...b,page:j})),w(j))},[a.totalPages]),g=p.useCallback((j,w)=>{j>=1&&j<=n.totalPages&&(i(b=>({...b,page:j})),w(j))},[n.totalPages]),f=p.useCallback((j,w)=>{j>=1&&j<=o.totalPages&&(l(b=>({...b,page:j})),w(j))},[o.totalPages]);return{activity:t,critical:a,deadlines:n,approver:o,updateActivityPagination:c,updateCriticalPagination:d,updateDeadlinesPagination:m,updateApproverPagination:u,handleActivityPageChange:h,handleCriticalPageChange:x,handleDeadlinesPageChange:g,handleApproverPageChange:f}}class K0{async getKPIs(s,a,r,n){try{const i={dateRange:s};return s==="custom"&&a&&r&&(i.startDate=a.toISOString(),i.endDate=r.toISOString()),n&&(i.viewAsUser="true"),(await he.get("/dashboard/kpis",{params:i})).data.data}catch(i){throw console.error("Failed to fetch KPIs:",i),i}}async getRequestStats(s,a,r,n,i,o,l,c,d,m,u,h){try{const x={dateRange:s};return s==="custom"&&a&&r&&(x.startDate=a,x.endDate=r),n&&n!=="all"&&(x.status=n),i&&i!=="all"&&(x.priority=i),o&&o!=="all"&&(x.department=o),l&&l!=="all"&&(x.initiator=l),c&&c!=="all"&&(x.approver=c),d&&(x.approverType=d),m&&(x.search=m),u&&u!=="all"&&(x.slaCompliance=u),h&&(x.viewAsUser="true"),(await he.get("/dashboard/stats/requests",{params:x})).data.data}catch(x){throw console.error("Failed to fetch request stats:",x),x}}async getTATEfficiency(s){try{return(await he.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 he.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 he.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 he.get("/dashboard/stats/ai-insights",{params:{dateRange:s}})).data.data}catch(a){throw console.error("Failed to fetch AI insights:",a),a}}async getRecentActivity(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await he.get("/dashboard/activity/recent",{params:n});return{activities:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch recent activity:",n),n}}async getCriticalRequests(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await he.get("/dashboard/requests/critical",{params:n});return{criticalRequests:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch critical requests:",n),n}}async getUpcomingDeadlines(s=1,a=10,r){try{const n={page:s,limit:a};r&&(n.viewAsUser="true");const i=await he.get("/dashboard/deadlines/upcoming",{params:n});return{deadlines:i.data.data,pagination:i.data.pagination}}catch(n){throw console.error("Failed to fetch upcoming deadlines:",n),n}}async getDepartmentStats(s,a,r){try{const n={dateRange:s};return s==="custom"&&a&&r&&(n.startDate=a.toISOString(),n.endDate=r.toISOString()),(await he.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 he.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 he.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,o,l){try{const c={dateRange:s,page:a,limit:r||10};s==="custom"&&n&&i&&(c.startDate=n.toISOString(),c.endDate=i.toISOString()),o&&o!=="all"&&(c.priority=o),l&&l!=="all"&&(c.slaCompliance=l),console.log("[Dashboard Service] Fetching approver performance with params:",c);const d=await he.get("/dashboard/stats/approver-performance",{params:c});return{performance:d.data.data,pagination:d.data.pagination}}catch(c){throw console.error("Failed to fetch approver performance:",c),c}}async getLifecycleReport(s=1,a=50,r,n,i){try{const o={page:s,limit:a};r&&(o.dateRange=r),r==="custom"&&n&&i&&(o.startDate=n.toISOString(),o.endDate=i.toISOString());const l=await he.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,d){try{const m={page:s,limit:a,filterUserId:n,filterType:i,filterCategory:o,filterSeverity:l};r&&(m.dateRange=r),r==="custom"&&c&&d&&(m.startDate=c.toISOString(),m.endDate=d.toISOString());const u=await he.get("/dashboard/reports/activity-log",{params:m});return{activities:u.data.data,pagination:u.data.pagination}}catch(m){throw console.error("Failed to fetch activity log report:",m),m}}async getDepartments(){try{return(await he.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 he.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 getSingleApproverStats(s,a,r,n,i,o){try{const l={approverId:s};return a&&(l.dateRange=a),a==="custom"&&r&&n&&(l.startDate=r.toISOString(),l.endDate=n.toISOString()),i&&i!=="all"&&(l.priority=i),o&&o!=="all"&&(l.slaCompliance=o),(await he.get("/dashboard/stats/single-approver",{params:l})).data.data}catch(l){throw console.error("Failed to fetch single approver stats:",l),l}}async getRequestsByApprover(s,a=1,r=50,n,i,o,l,c,d,m){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),d&&(u.slaCompliance=d),m&&(u.search=m);const h=await he.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 xt=new K0;function Y0({isAdmin:t,viewAsUser:s=!1,userId:a,dateRange:r,customStartDate:n,customEndDate:i,onPaginationUpdate:o}){const[l,c]=p.useState(null),[d,m]=p.useState([]),[u,h]=p.useState([]),[x,g]=p.useState([]),[f,j]=p.useState([]),[w,b]=p.useState([]),[C,v]=p.useState(null),[N,k]=p.useState([]),[E,P]=p.useState(!0),[M,y]=p.useState(!1),A=p.useRef(o);A.current=o;const L=p.useCallback(async(S=!1)=>{try{S?y(!0):P(!0);const D=[xt.getKPIs(r,n,i,s),xt.getRecentActivity(1,10,s),xt.getCriticalRequests(1,10,s),xt.getUpcomingDeadlines(1,10,s)],I=!t&&a?xt.getRequestStats(r,n==null?void 0:n.toISOString(),i==null?void 0:i.toISOString(),void 0,void 0,void 0,a,void 0,void 0,void 0,void 0):null,_=t?[xt.getDepartmentStats(r,n,i),xt.getPriorityDistribution(r,n,i),xt.getAIRemarkUtilization(r,n,i),xt.getApproverPerformance(r,1,10,n,i)]:[],[F,G,B]=await Promise.all([Promise.all(D),I,Promise.all(_)]),re=F[0],ae=F[1],V=F[2],Y=F[3];if(!t&&G&&(re.requestVolume=G),c(re),m(ae.activities),A.current.activity(ae.pagination.currentPage,ae.pagination.totalPages,ae.pagination.totalRecords),h(V.criticalRequests),A.current.critical(V.pagination.currentPage,V.pagination.totalPages,V.pagination.totalRecords),b(Y.deadlines),A.current.deadlines(Y.pagination.currentPage,Y.pagination.totalPages,Y.pagination.totalRecords),t&&B.length>=4){const Z=B[0],U=B[1],ee=B[2],ie=B[3];g(Z),j(U),v(ee),k(ie.performance),A.current.approver(ie.pagination.currentPage,ie.pagination.totalPages,ie.pagination.totalRecords)}else t||(g([]),j([]),v(null),k([]))}catch(D){console.error("Failed to fetch dashboard data:",D)}finally{P(!1),y(!1)}},[t,s,a,r,n,i]),K=p.useCallback(async(S=1)=>{try{const D=await xt.getRecentActivity(S,10,s);m(D.activities),A.current.activity(D.pagination.currentPage,D.pagination.totalPages,D.pagination.totalRecords)}catch(D){console.error("Failed to fetch recent activities:",D)}},[s]),O=p.useCallback(async(S=1)=>{try{const D=await xt.getCriticalRequests(S,10,s);h(D.criticalRequests),A.current.critical(D.pagination.currentPage,D.pagination.totalPages,D.pagination.totalRecords)}catch(D){console.error("Failed to fetch critical requests:",D)}},[s]),$=p.useCallback(async(S=1)=>{try{const D=await xt.getUpcomingDeadlines(S,10,s);b(D.deadlines),A.current.deadlines(D.pagination.currentPage,D.pagination.totalPages,D.pagination.totalRecords)}catch(D){console.error("Failed to fetch upcoming deadlines:",D)}},[s]),T=p.useCallback(async(S=1)=>{try{const D=await xt.getApproverPerformance(r,S,10,n,i);k(D.performance),A.current.approver(D.pagination.currentPage,D.pagination.totalPages,D.pagination.totalRecords)}catch(D){console.error("Failed to fetch approver performance:",D)}},[r,n,i]);return{kpis:l,recentActivity:d,criticalRequests:u,departmentStats:x,priorityDistribution:f,upcomingDeadlines:w,aiRemarkUtilization:C,approverPerformance:N,loading:E,refreshing:M,fetchDashboardData:L,fetchRecentActivities:K,fetchCriticalRequests:O,fetchUpcomingDeadlines:$,fetchApproverPerformance:T}}const ea={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 Z0{constructor(){Xn(this,"config",null);Xn(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 he.get("/config"),r=((s=a.data)==null?void 0:s.data)||a.data;return{...ea,...r,workingHours:{...ea.workingHours,...r.workingHours},tat:{...ea.tat,...r.tat},upload:{...ea.upload,...r.upload},workflow:{...ea.workflow,...r.workflow},workNotes:{...ea.workNotes,...r.workNotes},features:{...ea.features,...r.features},ui:{...ea.ui,...r.ui}}}catch(a){return console.error("[ConfigService] ⚠️ Failed to fetch config from server, using defaults:",a),ea}}async refreshConfig(){return this.config=null,this.loading=null,this.getConfig()}getCachedConfig(){return this.config}isLoaded(){return this.config!==null}}const X0=new Z0;let J0=9,Q0=18,q0=1,ey=5,Cc=!1;async function ty(){if(!Cc)try{const t=await X0.getConfig();J0=t.workingHours.START_HOUR,Q0=t.workingHours.END_HOUR,q0=t.workingHours.START_DAY,ey=t.workingHours.END_DAY,Cc=!0}catch{console.warn("[SLA Tracker] ⚠️ Using default working hours (9 AM - 6 PM)")}}ty().catch(()=>{});function Et(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",d=n===1?"min":"m";return n>0?`${a} ${l} ${r} ${c} ${n}${d}`:`${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 sy(t,s,a){const r=[];let n=1,i=!0;const o=100;for(;i&&n<=o;){const h=await xt.getApproverPerformance(t,n,100,s,a);h.performance&&h.performance.length>0?(r.push(...h.performance),n++,i=n<=h.pagination.totalPages):i=!1}const l=[["Approver Name","Total Approved","TAT Compliance (%)","Avg Response Time","Pending Count"].join(",")];r.forEach(h=>{const x=[`"${(h.approverName||"Unknown").replace(/"/g,'""')}"`,h.totalApproved||0,h.tatCompliancePercent||0,Et(h.avgResponseHours),h.pendingCount||0];l.push(x.join(","))});const c=l.join(` `),d=new Blob([c],{type:"text/csv;charset=utf-8;"}),m=document.createElement("a"),u=URL.createObjectURL(d);m.setAttribute("href",u),m.setAttribute("download",`approver-performance-report-${new Date().toISOString().split("T")[0]}.csv`),m.style.visibility="hidden",document.body.appendChild(m),m.click(),document.body.removeChild(m),URL.revokeObjectURL(u)}async function ay(t,s,a){const r=await xt.getDepartmentStats(t,s,a),n=[["Department","Total Requests","Approved","Rejected","In Progress","Approval Rate (%)"].join(",")];r.forEach(d=>{const m=[`"${(d.department||"Unknown").replace(/"/g,'""')}"`,d.totalRequests||0,d.approved||0,d.rejected||0,d.inProgress||0,d.approvalRate||0];n.push(m.join(","))});const i=n.join(` `),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 ry(){const[t,s]=p.useState(!1),[a,r]=p.useState(!1),n=p.useCallback(async(o,l,c)=>{try{s(!0),await ay(o,l,c)}catch(d){console.error("Failed to export department stats:",d),alert("Failed to export department statistics. Please try again.")}finally{s(!1)}},[]),i=p.useCallback(async(o,l,c)=>{try{r(!0),await sy(o,l,c)}catch(d){console.error("Failed to export approver performance:",d),alert("Failed to export approver performance data. Please try again.")}finally{r(!1)}},[]);return{exportingDeptStats:t,exportingApproverPerformance:a,handleExportDepartmentStats:n,handleExportApproverPerformance:i}}function us({className:t,...s}){return e.jsx(lx,{"data-slot":"switch",className:ge("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(cx,{"data-slot":"switch-thumb",className:ge("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 Q({className:t,...s}){return e.jsx(dx,{"data-slot":"label",className:ge("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 ny({isAdmin:t,effectiveIsAdmin:s,viewAsUser:a,onToggleView:r,quickActions:n,userDisplayName:i,userEmail:o}){const l=i||(o==null?void 0:o.split("@")[0])||"User";return e.jsxs(X,{className:"relative overflow-hidden shadow-xl border-0","data-testid":"dashboard-hero",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsxs(J,{className:"relative z-10 p-4 sm:p-6 lg:p-12",children:[t&&e.jsx("div",{className:"absolute top-4 right-4 sm:top-6 sm:right-6 z-20","data-testid":"view-toggle",children:e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 p-1.5 sm:p-2 bg-white/10 backdrop-blur-sm rounded-lg border border-white/20 shadow-lg",children:[e.jsxs("div",{className:`flex items-center gap-1 sm:gap-1.5 px-1.5 sm:px-2 py-0.5 sm:py-1 rounded transition-all cursor-pointer ${a?"opacity-60 hover:opacity-80":"bg-red-600/20 border border-red-600/50"}`,onClick:()=>r(!1),children:[e.jsx(No,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-gray-300":"text-red-600"}`}),e.jsx(Q,{htmlFor:"view-toggle-switch",className:`text-[10px] sm:text-xs font-medium cursor-pointer whitespace-nowrap ${a?"text-gray-300":"text-red-600"}`,children:"Org"})]}),e.jsx(us,{id:"view-toggle-switch",checked:a,onCheckedChange:r,className:"data-[state=checked]:bg-red-600 data-[state=unchecked]:bg-gray-600 shrink-0 scale-90 sm:scale-100","data-testid":"view-toggle-switch"}),e.jsxs("div",{className:`flex items-center gap-1 sm:gap-1.5 px-1.5 sm:px-2 py-0.5 sm:py-1 rounded transition-all cursor-pointer ${a?"bg-red-600/20 border border-red-600/50":"opacity-60 hover:opacity-80"}`,onClick:()=>r(!0),children:[e.jsx(St,{className:`w-3 h-3 sm:w-3.5 sm:h-3.5 ${a?"text-red-600":"text-gray-300"}`}),e.jsx(Q,{htmlFor:"view-toggle-switch",className:`text-[10px] sm:text-xs font-medium cursor-pointer whitespace-nowrap ${a?"text-red-600":"text-gray-300"}`,children:"Personal"})]})]})}),e.jsx("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4 sm:gap-6",children:e.jsxs("div",{className:`text-white w-full lg:w-auto ${t?"pt-12 sm:pt-0":""}`,children:[e.jsx("div",{className:"flex items-center gap-3 sm:gap-4 mb-4 sm:mb-6",children:e.jsxs("div",{className:"pr-2 sm:pr-0",children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl lg:text-4xl font-bold mb-1 sm:mb-2 text-white","data-testid":"hero-title",children:["Welcome, ",l,"!"]}),e.jsx("p",{className:"text-sm sm:text-lg lg:text-xl text-gray-200","data-testid":"hero-subtitle",children:s?"Organization-wide analytics and insights":"Track your requests and approvals"})]})}),e.jsx("div",{className:"flex flex-wrap gap-2 sm:gap-4 mt-4 sm:mt-8","data-testid":"quick-actions",children:n.map((c,d)=>e.jsxs(R,{onClick:c.action,className:`${c.color} text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200`,size:window.innerWidth<640?"sm":"lg","data-testid":`quick-action-${c.label.toLowerCase().replace(/\s+/g,"-")}`,children:[e.jsx(c.icon,{className:"w-4 h-4 sm:w-5 sm:h-5 mr-1 sm:mr-2"}),c.label]},d))})]})})]})]})}function Be({...t}){return e.jsx(mx,{"data-slot":"select",...t})}function Ue({...t}){return e.jsx(px,{"data-slot":"select-value",...t})}function Ve({className:t,size:s="default",children:a,...r}){return e.jsxs(ux,{"data-slot":"select-trigger","data-size":s,className:ge("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(hx,{asChild:!0,children:e.jsx(Tm,{className:"size-4 opacity-50"})})]})}function ze({className:t,children:s,position:a="popper",...r}){return e.jsx(xx,{children:e.jsxs(gx,{"data-slot":"select-content",className:ge("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(iy,{}),e.jsx(fx,{className:ge("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(oy,{})]})})}function W({className:t,children:s,...a}){return e.jsxs(yx,{"data-slot":"select-item",className:ge("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(bx,{children:e.jsx(er,{className:"size-4"})})}),e.jsx(vx,{children:s})]})}function iy({className:t,...s}){return e.jsx(jx,{"data-slot":"select-scroll-up-button",className:ge("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Ng,{className:"size-4"})})}function oy({className:t,...s}){return e.jsx(Nx,{"data-slot":"select-scroll-down-button",className:ge("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Tm,{className:"size-4"})})}function It({className:t,orientation:s="horizontal",decorative:a=!0,...r}){return e.jsx(wx,{"data-slot":"separator-root",decorative:a,orientation:s,className:ge("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 $s({...t}){return e.jsx(Cx,{"data-slot":"popover",...t})}function Bs({...t}){return e.jsx(Sx,{"data-slot":"popover-trigger",...t})}function Us({className:t,align:s="center",sideOffset:a=4,...r}){return e.jsx(Ax,{children:e.jsx(kx,{"data-slot":"popover-content",align:s,sideOffset:a,className:ge("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 we({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:ge("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 ly({isAdmin:t,dateRange:s,customStartDate:a,customEndDate:r,showCustomDatePicker:n,refreshing:i,onDateRangeChange:o,onCustomStartDateChange:l,onCustomEndDateChange:c,onShowCustomDatePickerChange:d,onApplyCustomDate:m,onResetCustomDates:u,onRefresh:h}){return e.jsx(X,{className:"shadow-md","data-testid":"dashboard-filters-bar",children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zr,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),t&&e.jsx(se,{variant:"outline",className:"bg-purple-50 text-purple-700 border-purple-200","data-testid":"management-badge",children:"Management View"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 w-full sm:w-auto",children:[t?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Be,{value:s,onValueChange:o,"data-testid":"date-range-select",children:[e.jsx(Ve,{className:"w-[140px]",children:e.jsx(Ue,{placeholder:"Select period"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Time"}),e.jsx(W,{value:"today",children:"Today"}),e.jsx(W,{value:"week",children:"This Week"}),e.jsx(W,{value:"month",children:"This Month"}),e.jsx(W,{value:"last7days",children:"Last 7 Days"}),e.jsx(W,{value:"last30days",children:"Last 30 Days"}),e.jsx(W,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs($s,{open:n,onOpenChange:d,children:[e.jsx(Bs,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(qe,{className:"w-4 h-4"}),a&&r?`${Ne(a,"MMM d, yyyy")} - ${Ne(r,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Us,{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(Q,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(we,{id:"start-date",type:"date",value:a?Ne(a,"yyyy-MM-dd"):"",onChange:x=>{const g=x.target.value?new Date(x.target.value):void 0;g?(l(g),r&&g>r&&c(g)):l(void 0)},max:Ne(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":"start-date-input"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(we,{id:"end-date",type:"date",value:r?Ne(r,"yyyy-MM-dd"):"",onChange:x=>{const g=x.target.value?new Date(x.target.value):void 0;g?(c(g),a&&go(x),"data-testid":"date-range-select-user",children:[e.jsx(Ve,{className:"w-[140px]",children:e.jsx(Ue,{placeholder:"Select period"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Time"}),e.jsx(W,{value:"today",children:"Today"}),e.jsx(W,{value:"week",children:"This Week"}),e.jsx(W,{value:"month",children:"This Month"}),e.jsx(W,{value:"last7days",children:"Last 7 Days"}),e.jsx(W,{value:"last30days",children:"Last 30 Days"}),e.jsx(W,{value:"custom",children:"Custom Range"})]})]})]}),e.jsx(It,{orientation:"vertical",className:"h-6 hidden sm:block"}),e.jsxs(R,{variant:"outline",size:"sm",onClick:h,disabled:i,className:"gap-2 min-w-[110px]","data-testid":"refresh-button",children:[e.jsx(Zt,{className:`w-4 h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"inline-block w-[60px] text-center",children:i?"Refreshing...":"Refresh"})]})]})]})})})}function Pa({title:t,value:s,icon:a,iconBgColor:r,iconColor:n,subtitle:i,children:o,testId:l="kpi-card",onClick:c,onJustifyClick:d,showJustifyButton:m=!1}){const u=h=>{h.stopPropagation(),d==null||d()};return e.jsxs(X,{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(le,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ce,{className:"text-sm font-medium text-muted-foreground","data-testid":`${l}-title`,children:t}),e.jsxs("div",{className:"flex items-center gap-2",children:[m&&d&&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(Hr,{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(J,{className:"flex flex-col flex-1 py-3",children:[e.jsx("div",{className:"text-xl sm:text-2xl font-bold text-gray-900 mb-2","data-testid":`${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 Kt({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 Gs({className:t,value:s,indicatorClassName:a,...r}){return e.jsx(Tx,{"data-slot":"progress",className:ge("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",t),...r,children:e.jsx(Dx,{"data-slot":"progress-indicator",className:ge("bg-primary h-full w-full flex-1 transition-all",a),style:{transform:`translateX(-${100-(s||0)}%)`}})})}function cy({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(Pa,{title:"Total Requests",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Ee,iconBgColor:"bg-blue-50",iconColor:"text-blue-600",testId:"kpi-total-requests",onClick:()=>i(o()),children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[e.jsx(Kt,{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(Kt,{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 mb-2",children:[e.jsx(Kt,{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(Kt,{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"})}})]}),(t==null?void 0:t.requestVolume.pausedRequests)!==void 0&&e.jsx("div",{className:"grid grid-cols-2 gap-2",children:e.jsx(Kt,{label:"Paused",value:t.requestVolume.pausedRequests||0,bgColor:"bg-orange-100",textColor:"text-orange-700",testId:"stat-paused",onClick:l=>{l.stopPropagation(),i({...o(),status:"paused"})}})})]}),e.jsx(Pa,{title:"SLA Compliance",value:`${(t==null?void 0:t.tatEfficiency.avgTATCompliance)||0}%`,icon:Dt,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(Gs,{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(Kt,{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(Kt,{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(Pa,{title:"Avg Cycle Time",value:t!=null&&t.tatEfficiency.avgCycleTimeHours?Et(t.tatEfficiency.avgCycleTimeHours):"0 hours",icon:He,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(Kt,{label:"Express",value:(()=>{const l=s.find(d=>d.priority==="express"),c=l?Number(l.avgCycleTimeHours):0;return c>0?Et(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(Kt,{label:"Standard",value:(()=>{const l=s.find(d=>d.priority==="standard"),c=l?Number(l.avgCycleTimeHours):0;return c>0?Et(c):"N/A"})(),bgColor:"bg-blue-50",textColor:"text-blue-600",testId:"stat-standard-time",onClick:l=>{l.stopPropagation(),i({...o(),priority:"standard"})}})]})})})]})}function dy({kpis:t,criticalRequests:s,dateRange:a,customStartDate:r,customEndDate:n,onKPIClick:i,onNavigate:o,userId:l,userDisplayName:c}){const d=()=>({dateRange:a,startDate:r,endDate:n}),m=()=>{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(Pa,{title:"My Requests (Submitted)",value:(t==null?void 0:t.requestVolume.totalRequests)||0,icon:Ee,iconBgColor:"bg-blue-50",iconColor:"text-blue-600",testId:"kpi-my-requests",onClick:()=>i(d()),children:e.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:gap-2",children:[e.jsx(Kt,{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({...d(),status:"approved"})}}),e.jsx(Kt,{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({...d(),status:"pending"})}}),e.jsx(Kt,{label:"Paused",value:(t==null?void 0:t.requestVolume.pausedRequests)||0,bgColor:"bg-amber-50",textColor:"text-amber-600",testId:"stat-user-paused",onClick:h=>{h.stopPropagation(),i({...d(),status:"paused"})}}),e.jsx(Kt,{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({...d(),status:"rejected"})}}),e.jsx(Kt,{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({...d(),status:"closed"})}})]})}),e.jsx(Pa,{title:"Awaiting My Approval",value:(t==null?void 0:t.approverLoad.pendingActions)||0,icon:He,iconBgColor:"bg-orange-50",iconColor:"text-orange-600",subtitle:"at current level",testId:"kpi-pending-actions",onClick:()=>i({...d(),targetPage:"open-requests",status:"pending"}),onJustifyClick:m,showJustifyButton:!!l,children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(Kt,{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({...d(),targetPage:"open-requests",status:"pending"})}}),e.jsx(Kt,{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({...d(),targetPage:"open-requests",status:"pending"})}})]})}),e.jsx(Pa,{title:"Critical Alerts",value:s.length,icon:Os,iconBgColor:"bg-red-50",iconColor:"text-red-600",testId:"kpi-user-critical",onClick:()=>i({...d(),targetPage:"open-requests"}),onJustifyClick:m,showJustifyButton:!!l,children:e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-auto",children:[e.jsx(Kt,{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({...d(),targetPage:"open-requests"})}}),e.jsx(Kt,{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({...d(),targetPage:"open-requests"})}})]})}),e.jsx(Pa,{title:"Success Rate",value:`${u.toFixed(0)}%`,icon:Ce,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(Gs,{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 my=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)))},uy=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 hy({alert:t,onNavigate:s,testId:a="critical-alert-card"}){const r=my(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(wg,{className:"h-3 w-3 text-red-500 flex-shrink-0","data-testid":`${a}-priority-icon`}),t.breachCount>0&&e.jsx(se,{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(se,{variant:"outline",className:"text-xs bg-white border-red-200 text-red-700 font-medium whitespace-nowrap","data-testid":`${a}-remaining-time`,children:uy(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(Gs,{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 py(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 xy(t){return t.filter(s=>{const a=Number(s.tatPercentageUsed)||0;return(Number(s.remainingHours)||0)>0&&a<100})}function gy(t){if(t<=0)return"Just breached";if(t<1)return`${Math.round(t*60)} min`;const s=8;if(t0?`${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 fy(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 nu(t,s,a=3){const r=[];let n=Math.max(1,t-Math.floor(a/2)),i=Math.min(s,n+a-1);i-n0?"animate-pulse":""}`,"data-testid":"critical-count-badge",children:a.totalRecords})]})}),e.jsx(J,{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(Ce,{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(hy,{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(R,{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(Wt,{className:"h-3 w-3 rotate-180"})}),nu(a.page,a.totalPages,3).map(i=>e.jsx(R,{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(R,{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(Wt,{className:"h-3 w-3"})})]})]})})]})}const by=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"}},vy=t=>{const s=new Date,a=new Date(t),r=ng(s,a);if(r<1)return"just now";if(r<60)return`${r} minute${r>1?"s":""} ago`;const n=ig(s,a);if(n<24)return`${n} hour${n>1?"s":""} ago`;const i=og(s,a);return`${i} day${i>1?"s":""} ago`},jy=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()},Ny=t=>{const s=t.toLowerCase();return s.includes("approv")?e.jsx(Ce,{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(Ps,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-blue-600"}):s.includes("escalat")?e.jsx(Os,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600"}):s.includes("submit")?e.jsx(Ee,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600"}):s.includes("document")?e.jsx(In,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600"}):e.jsx(Vt,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600"})};function wy({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(d=>d[0]).join("").toUpperCase().substring(0,2):t.userName?t.userName.split(" ").map(d=>d[0]).join("").toUpperCase().substring(0,2):"SY";return e.jsxs("div",{className:"flex items-start gap-2 sm:gap-3 p-3 sm:p-4 rounded-lg hover:bg-gray-50 transition-all duration-200 cursor-pointer border border-gray-100 hover:border-gray-300",onClick:()=>n==null?void 0:n(t.requestNumber),"data-testid":`${i}-${t.activityId}`,children:[e.jsxs("div",{className:"relative flex-shrink-0 mt-0.5",children:[e.jsxs(Bt,{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(Vn,{src:""}),e.jsx(Ut,{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:Ny(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(se,{variant:"outline",className:`text-xs ${by(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:jy(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:vy(t.timestamp)})]})]}),e.jsx(Wt,{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 Cy({isAdmin:t,recentActivity:s,pagination:a,refreshing:r,onPageChange:n,onRefresh:i,onNavigate:o,currentUserId:l,currentUserDisplayName:c,currentUserEmail:d}){return e.jsxs(X,{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(le,{className:"pb-3 sm:pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"p-2 sm:p-3 bg-blue-100 rounded-lg",children:e.jsx(Vt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(ce,{className:"text-base sm:text-lg text-gray-900",children:"Recent Activity"}),e.jsx(je,{className:"text-xs sm:text-sm text-gray-600 truncate",children:t?"All workflow updates":"My workflow updates"})]})]}),e.jsxs(R,{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(Zt,{className:`w-3 h-3 sm:w-4 sm:h-4 ${r?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline ml-2 sm:w-[60px] sm:text-center",children:r?"Refreshing...":"Refresh"})]})]})}),e.jsx(J,{className:"overflow-y-auto flex-1 p-4",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(Vt,{className:"w-10 h-10 sm:w-12 sm:h-12 mx-auto mb-2 text-gray-400"}),e.jsx("p",{className:"text-sm",children:"No recent activity"}),e.jsx("p",{className:"text-xs",children:"Activity will appear here once requests are processed"})]}):s.map(m=>e.jsx(wy,{activity:m,currentUserId:l,currentUserDisplayName:c,currentUserEmail:d,onNavigate:u=>o==null?void 0:o(`request/${u}`),testId:"dashboard-activity"},m.activityId))})}),a.totalPages>1&&s.length>0&&e.jsx("div",{className:"border-t bg-gray-50 px-4 py-2 flex-shrink-0",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Page ",a.page," of ",a.totalPages," (",a.totalRecords," total)"]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 flex-wrap",children:[e.jsx(R,{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(Wt,{className:"h-3 w-3 rotate-180"})}),nu(a.page,a.totalPages,3).map(m=>e.jsx(R,{variant:m===a.page?"default":"outline",size:"sm",onClick:()=>n(m),className:`h-7 w-7 p-0 text-xs ${m===a.page?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`activity-pagination-page-${m}`,children:m},m)),e.jsx(R,{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(Wt,{className:"h-3 w-3"})})]})]})})]})}function Sy({kpis:t,upcomingDeadlines:s,criticalRequests:a,departmentStats:r,dateRange:n,customStartDate:i,customEndDate:o,exportingDeptStats:l,onKPIClick:c,onExportDepartmentStats:d}){if(!t)return null;const m=()=>({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(X,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"active-levels-card",children:[e.jsx(le,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Vt,{className:"h-4 w-4 text-blue-600"})}),e.jsx(ce,{className:"text-sm",children:"Active Levels"})]})}),e.jsx(J,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl sm:text-3xl font-bold text-blue-600",children:s.length}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"levels"})]}),e.jsx(It,{}),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(X,{className:"shadow-md hover:shadow-lg transition-shadow flex-1","data-testid":"collaboration-card",children:[e.jsx(le,{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(Ps,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ce,{className:"text-sm",children:"Collaboration"})]})}),e.jsx(J,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"text-center p-2 bg-indigo-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-indigo-600",children:t.engagement.workNotesAdded})]}),e.jsxs("div",{className:"text-center p-2 bg-purple-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Files"}),e.jsx("p",{className:"text-lg sm:text-xl font-bold text-purple-600",children:t.engagement.attachmentsUploaded})]})]}),e.jsx(It,{}),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(X,{className:"shadow-md hover:shadow-lg transition-shadow lg:col-span-2","data-testid":"department-stats-card",children:[e.jsx(le,{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(Cg,{className:"h-5 w-5 sm:h-6 sm:w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-base sm:text-lg lg:text-xl",children:"Department-wise Workflow Summary"}),e.jsx(je,{className:"text-xs sm:text-sm",children:"Workflow distribution across departments"})]})]}),e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2 self-start sm:self-auto",onClick:()=>d(n,i,o),disabled:l,"data-testid":"export-dept-stats-button",children:[e.jsx(ss,{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(J,{children:e.jsx(go,{width:"100%",height:400,children:e.jsxs(qx,{data:r,children:[e.jsx(fm,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ym,{dataKey:"department",stroke:"#999",tick:u=>{const{x:h,y:x,payload:g}=u;return e.jsx("g",{transform:`translate(${h},${x})`,children:e.jsx("text",{x:0,y:0,dy:16,textAnchor:"middle",fill:"#999",fontSize:11,className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{c({...m(),department:g.value})},children:g.value})})}}),e.jsx(bm,{stroke:"#999",tick:{fontSize:11}}),e.jsx(fo,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(vm,{verticalAlign:"bottom",height:36,iconType:"square",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(Jn,{dataKey:"approved",fill:"#10b981",name:"Approved"}),e.jsx(Jn,{dataKey:"inProgress",fill:"#f59e0b",name:"Pending"}),e.jsx(Jn,{dataKey:"rejected",fill:"#ef4444",name:"Rejected"})]})})})]})]})}function Ay({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(X,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-activity-card",children:[e.jsx(le,{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(Ps,{className:"h-4 w-4 text-indigo-600"})}),e.jsx(ce,{className:"text-sm",children:"My Activity"})]})}),e.jsx(J,{children:e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"text-center p-3 bg-indigo-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Work Notes"}),e.jsx("p",{className:"text-xl sm:text-2xl font-bold text-indigo-600",children:t.engagement.workNotesAdded})]}),e.jsxs("div",{className:"text-center p-3 bg-purple-50 rounded",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Attachments"}),e.jsx("p",{className:"text-xl sm:text-2xl font-bold text-purple-600",children:t.engagement.attachmentsUploaded})]})]})})})]}),e.jsxs(X,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"user-response-time-card",children:[e.jsx(le,{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(He,{className:"h-4 w-4 text-purple-600"})}),e.jsx(ce,{className:"text-sm",children:"Avg Response Time"})]})}),e.jsx(J,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-baseline gap-2",children:e.jsx("span",{className:"text-2xl sm:text-3xl font-bold text-purple-600",children:Et(t.tatEfficiency.avgCycleTimeHours)})}),e.jsx(It,{}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["≈ ",t.tatEfficiency.avgCycleTimeDays.toFixed(1)," working days"]})]})})]})]}):null}function ky({priorityDistribution:t,onNavigate:s}){return t.length===0?null:e.jsxs(X,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"priority-distribution-report",children:[e.jsx(le,{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(Dt,{className:"h-5 w-5 sm:h-6 sm:w-6 text-green-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-base sm:text-lg lg:text-xl",children:"Priority Distribution Report"}),e.jsx(je,{className:"text-xs sm:text-sm",children:"Express vs Standard workflow analysis"})]})]})}),e.jsxs(J,{children:[e.jsx("div",{className:"grid grid-cols-2 gap-4 mb-6",children:t.map((a,r)=>{const n=Number(a.avgCycleTimeHours)||0,i=a.priority==="express",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: ",Et(n)," cycle"]})]},r)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(go,{width:"100%",height:300,children:e.jsxs(eg,{children:[e.jsx(tg,{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,d=i+35,m=a+d*Math.cos(-n*c),u=r+d*Math.sin(-n*c);return e.jsx("text",{x:m,y:u,fill:"#1f2937",textAnchor:m>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(sg,{fill:a.priority==="express"?"#ef4444":"#3b82f6",style:{cursor:"pointer"}},`cell-${r}`))}),e.jsx(fo,{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 $a({currentPage:t,totalPages:s,itemsPerPage:a,totalRecords:r,onPageChange:n,loading:i=!1,itemLabel:o="items",testIdPrefix:l="pagination"}){const c=()=>{const u=[];let x=Math.max(1,t-Math.floor(2.5)),g=Math.min(s,x+5-1);g-x<4&&(x=Math.max(1,g-5+1));for(let f=x;f<=g;f++)u.push(f);return u},d=r>0?(t-1)*a+1:0,m=Math.min(t*a,r);return s<=1?e.jsx(X,{className:"shadow-md border-gray-200","data-testid":`${l}-container`,children:e.jsx(J,{className:"p-4",children:e.jsx("div",{className:"flex items-center justify-center",children:e.jsx("div",{className:"text-sm sm:text-base font-medium text-gray-700","data-testid":`${l}-info`,children:i?`Loading ${o}...`:r===0?`No ${o} found`:r===1?`Showing 1 ${o.slice(0,-1)}`:d===m?`Showing ${d} of ${r} ${o}`:`Showing ${d} to ${m} of ${r} ${o}`})})})}):e.jsx(X,{className:"shadow-md border-gray-200","data-testid":`${l}-container`,children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-sm sm:text-base font-medium text-gray-700","data-testid":`${l}-info`,children:["Showing ",d," to ",m," of ",r," ",o]}),e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${l}-controls`,children:[e.jsx(R,{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(Wt,{className:"h-4 w-4 rotate-180"})}),t>3&&s>5&&e.jsxs(e.Fragment,{children:[e.jsx(R,{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(R,{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)),t5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground","data-testid":`${l}-ellipsis-end`,children:"..."}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>n(s),className:"h-8 w-8 p-0","data-testid":`${l}-page-${s}`,children:s})]}),e.jsx(R,{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(Wt,{className:"h-4 w-4"})})]})]})})})}function Ty(t,s,a,r="for"){return t==="custom"&&s&&a?`${r} ${Ne(s,"MMM d, yyyy")} - ${Ne(a,"MMM d, yyyy")}`:{all:"(All Time)",today:`${r} Today`,week:`${r} This Week`,month:`${r} This Month`,quarter:`${r} This Quarter`,year:`${r} This Year`,last30days:`${r} Last 30 Days`,custom:`${r} Custom Range`}[t]||`${r} Selected Period`}function Dy(t,s,a){return t==="all"?"All historical data":t==="custom"&&s&&a?`Data from ${Ne(s,"MMM d, yyyy")} to ${Ne(a,"MMM d, yyyy")}`:{all:"All historical data",today:"Today's data",week:"This week data",month:"This month data",quarter:"This quarter data",year:"This year data",last30days:"Last 30 days data",custom:"Custom date range"}[t]||"Filtered data"}function Ry({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(X,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"tat-breach-report",children:[e.jsx(le,{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(ce,{className:"text-base sm:text-lg lg:text-xl",children:"TAT Breach Report"}),e.jsxs(je,{className:"text-xs sm:text-sm",children:["Requests that breached TAT - ",Dy(a,r,n)]})]})]}),e.jsxs(se,{variant:"destructive",className:"text-sm font-medium self-start sm:self-auto",children:[t.length," ",t.length===1?"Breach":"Breaches"]})]})}),e.jsxs(J,{children:[e.jsx("div",{className:"overflow-x-auto -mx-4 sm:mx-0",children:e.jsxs("table",{className:"w-full min-w-[1000px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 bg-gray-50",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Request ID"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[250px]",children:"Title"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Department"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Approver"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Level"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[140px]",children:"Breach Time"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700 w-[300px]",children:"Reason"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-gray-700",children:"Priority"})]})}),e.jsx("tbody",{children:t.map((d,m)=>{const u=d.breachTime||0;return e.jsxs("tr",{className:"border-b border-gray-100 hover:bg-gray-50 transition-colors",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-blue-600 cursor-pointer hover:underline",onClick:()=>l==null?void 0:l(`request/${d.requestNumber}`),"data-testid":`breach-request-${d.requestNumber}`,children:d.requestNumber}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-900 w-[250px]",children:e.jsx("p",{className:"break-words leading-relaxed",children:d.title})}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700 cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{d.department&&d.department!=="Unknown"&&o({...c(),department:d.department})},children:d.department||"Unknown"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:d.approverId?e.jsx("span",{className:"cursor-pointer hover:text-blue-600 hover:underline",onClick:()=>{if(l){const h=new URLSearchParams;h.set("approver",d.approverId),h.set("approverType","current"),h.set("slaCompliance","breached"),l(`requests?${h.toString()}`)}},title:"Click to view all requests for this approver",children:d.approver||"N/A"}):d.approver||"N/A"}),e.jsx("td",{className:"py-3 px-4 text-sm text-gray-700",children:d.currentLevel&&d.totalLevels?e.jsxs("span",{className:"font-medium",children:[d.currentLevel,"/",d.totalLevels]}):d.currentLevel?e.jsxs("span",{className:"font-medium",children:[d.currentLevel,"/—"]}):e.jsx("span",{className:"text-gray-400",children:"—"})}),e.jsx("td",{className:"py-3 px-4 w-[140px]",children:e.jsx("span",{className:"bg-red-500 text-white px-2 py-1 rounded text-xs font-medium whitespace-nowrap",children:gy(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:d.breachReason||"TAT Exceeded"})})}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(se,{variant:"outline",className:`text-xs font-medium ${d.priority==="express"?"bg-orange-100 text-orange-800 border-orange-200":"bg-blue-100 text-blue-800 border-blue-200"}`,children:d.priority})})]},m)})})]})}),e.jsx("div",{className:"mt-4",children:e.jsx($a,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:i,itemLabel:"critical requests",testIdPrefix:"dashboard-critical-pagination"})})]})]})}function Py({isAdmin:t,upcomingDeadlines:s,pagination:a,onPageChange:r,onNavigate:n}){return s.length===0?null:e.jsxs(X,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"upcoming-deadlines-section",children:[e.jsx(le,{children:e.jsx("div",{className:"flex items-center justify-between gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"h-4 w-4 sm:h-5 sm:w-5 text-orange-600"}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-base sm:text-lg",children:"Upcoming Deadlines"}),e.jsx(je,{className:"text-xs sm:text-sm",children:t?"Current active levels organization-wide":"Requests awaiting your approval"})]})]})})}),e.jsxs(J,{children:[e.jsx("div",{className:"space-y-2 sm:space-y-3",children:s.map((i,o)=>{const l=Number(i.tatPercentageUsed)||0,c=Number(i.elapsedHours)||0,d=Number(i.remainingHours)||0;return e.jsxs("div",{className:"p-3 sm:p-4 border rounded-lg hover:shadow-md transition-all cursor-pointer",onClick:()=>n==null?void 0:n(`request/${i.requestNumber}`),"data-testid":`deadline-item-${i.requestNumber}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-xs sm:text-sm",children:i.requestNumber}),e.jsx(se,{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(se,{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(Gs,{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:[Et(c)," elapsed"]}),e.jsxs("span",{children:[Et(d)," left"]})]})]})]},o)})}),e.jsx("div",{className:"mt-4",children:e.jsx($a,{currentPage:a.page,totalPages:a.totalPages,totalRecords:a.totalRecords,itemsPerPage:10,onPageChange:r,itemLabel:"deadlines",testIdPrefix:"dashboard-deadlines-pagination"})})]})]})}function Ey({aiRemarkUtilization:t}){return t?e.jsxs(X,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"ai-remark-utilization-report",children:[e.jsx(le,{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(wo,{className:"h-5 w-5 sm:h-6 sm:w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-base sm:text-lg lg:text-xl",children:"AI Remark Utilization Report"}),e.jsx(je,{className:"text-xs sm:text-sm",children:"AI-generated remarks usage and edits"})]})]})}),e.jsxs(J,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4 mb-6",children:[e.jsxs("div",{className:"bg-purple-50 p-4 rounded-lg text-center","data-testid":"ai-total-usage",children:[e.jsx("div",{className:"text-sm text-gray-600 mb-1",children:"Total Usage"}),e.jsx("div",{className:"text-2xl font-bold text-gray-900",children:t.totalUsage})]}),e.jsxs("div",{className:"bg-pink-50 p-4 rounded-lg text-center","data-testid":"ai-total-edits",children:[e.jsx("div",{className:"text-sm text-gray-600 mb-1",children:"Total Edits"}),e.jsx("div",{className:"text-2xl font-bold text-gray-900",children:t.totalEdits})]}),e.jsxs("div",{className:"bg-purple-50 p-4 rounded-lg text-center","data-testid":"ai-edit-rate",children:[e.jsx("div",{className:"text-sm text-gray-600 mb-1",children:"Edit Rate"}),e.jsxs("div",{className:"text-2xl font-bold text-gray-900",children:[t.editRate,"%"]})]})]}),t.monthlyTrends&&t.monthlyTrends.length>0&&e.jsx(go,{width:"100%",height:250,children:e.jsxs(ag,{data:t.monthlyTrends,children:[e.jsx(fm,{strokeDasharray:"3 3",stroke:"#f0f0f0"}),e.jsx(ym,{dataKey:"month",stroke:"#999",tick:{fontSize:11}}),e.jsx(bm,{stroke:"#999",tick:{fontSize:11}}),e.jsx(fo,{contentStyle:{backgroundColor:"#ffffff",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"12px"}}),e.jsx(vm,{verticalAlign:"bottom",height:36,iconType:"circle",wrapperStyle:{fontSize:"12px",paddingTop:"10px"}}),e.jsx(ic,{type:"monotone",dataKey:"aiUsage",stroke:"#8b5cf6",strokeWidth:2,name:"AI Usage",dot:{fill:"#8b5cf6",r:4}}),e.jsx(ic,{type:"monotone",dataKey:"manualEdits",stroke:"#ec4899",strokeWidth:2,name:"Manual Edits",dot:{fill:"#ec4899",r:4}})]})})]})]}):null}function Iy({approverPerformance:t,pagination:s,dateRange:a,customStartDate:r,customEndDate:n,loading:i,exportingApproverPerformance:o,onPageChange:l,onExport:c,onNavigate:d}){return t.length===0?null:e.jsxs(X,{className:"shadow-md hover:shadow-lg transition-shadow","data-testid":"approver-performance-report",children:[e.jsx(le,{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(Pt,{className:"h-5 w-5 sm:h-6 sm:w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-base sm:text-lg lg:text-xl",children:"Approver Performance Report"}),e.jsx(je,{className:"text-xs sm:text-sm",children:"Response time & TAT compliance tracking"})]})]}),e.jsx(R,{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(Zt,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}),e.jsxs(J,{children:[e.jsx("div",{className:"space-y-3",children:t.map((m,u)=>{const h=m.tatCompliancePercent;return e.jsxs("div",{className:"border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{const x=new URLSearchParams;x.set("approverId",m.approverId),x.set("approverName",m.approverName),x.set("dateRange",a),a==="custom"&&r&&n&&(x.set("startDate",r.toISOString()),x.set("endDate",n.toISOString())),d==null||d(`/approver-performance?${x.toString()}`)},"data-testid":`approver-item-${m.approverId}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-orange-500 rounded-full flex items-center justify-center text-white font-semibold text-sm flex-shrink-0",children:u+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-gray-900 truncate",children:m.approverName}),e.jsxs("div",{className:"text-xs text-gray-500",children:[m.totalApproved," requests approved"]})]})]}),e.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium ${fy(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:Et(m.avgResponseHours)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"Pending"}),e.jsx("div",{className:"text-sm font-medium text-gray-900",children:e.jsx("span",{className:"bg-gray-500 text-white px-2 py-1 rounded text-xs",children:m.pendingCount})})]})]})]},u)})}),e.jsx("div",{className:"mt-4",children:e.jsx($a,{currentPage:s.page,totalPages:s.totalPages,totalRecords:s.totalRecords,itemsPerPage:10,onPageChange:l,itemLabel:"approvers",testIdPrefix:"dashboard-approver-pagination"})})]})]})}function My(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 Fy(t,s,a){const r=[{label:"New Request",icon:Ee,action:()=>s==null?void 0:s(),color:"bg-emerald-600 hover:bg-emerald-700"},{label:"View Pending",icon:He,action:()=>a==null?void 0:a("open-requests"),color:"bg-blue-600 hover:bg-blue-700"},{label:"Settings",icon:ua,action:()=>a==null?void 0:a("settings"),color:"bg-slate-600 hover:bg-slate-700"}];return t&&r.splice(2,0,{label:"Reports",icon:Vt,action:()=>a==null?void 0:a("detailed-reports"),color:"bg-purple-600 hover:bg-purple-700"}),r}function Sc({onNavigate:t,onNewRequest:s}){const{user:a}=Gt(),r=Gr(),n=ar(et=>et.dashboard.viewAsUser),i=p.useMemo(()=>Un(a),[a]),o=i&&!n,l=p.useCallback(et=>{r(H0(et))},[r]),c=W0(),{dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,handleDateRangeChange:x,handleApplyCustomDate:g,resetCustomDates:f,setCustomStartDate:j,setCustomEndDate:w,setShowCustomDatePicker:b}=c,C=G0(),{activity:v,critical:N,deadlines:k,approver:E,updateActivityPagination:P,updateCriticalPagination:M,updateDeadlinesPagination:y,updateApproverPagination:A,handleActivityPageChange:L,handleCriticalPageChange:K,handleDeadlinesPageChange:O,handleApproverPageChange:$}=C,T=Y0({isAdmin:o,viewAsUser:i&&n,userId:a==null?void 0:a.userId,dateRange:d,customStartDate:m,customEndDate:u,onPaginationUpdate:{activity:P,critical:M,deadlines:y,approver:A}}),{kpis:S,recentActivity:D,criticalRequests:I,departmentStats:_,priorityDistribution:F,upcomingDeadlines:G,aiRemarkUtilization:B,approverPerformance:re,loading:ae,refreshing:V,fetchDashboardData:Y,fetchRecentActivities:Z,fetchCriticalRequests:U,fetchUpcomingDeadlines:ee,fetchApproverPerformance:ie}=T,de=ry(),{exportingDeptStats:Ae,exportingApproverPerformance:We,handleExportDepartmentStats:Se,handleExportApproverPerformance:Ye}=de,Ge=p.useMemo(()=>py(I),[I]),Oe=p.useMemo(()=>xy(G),[G]),ct=p.useCallback(()=>{Y(!0)},[d,m,u,Y]),te=p.useCallback(()=>{g(()=>{m&&u&&Y(!1)})},[m,u,g,Y]),xe=p.useCallback(et=>{L(et,Z)},[L,Z]),dt=p.useCallback(et=>{K(et,U)},[K,U]),ue=p.useCallback(et=>{O(et,ee)},[O,ee]),Te=p.useCallback(et=>{$(et,()=>ie(et))},[$,ie]);p.useEffect(()=>{d==="custom"?m&&u&&Y(!1):Y(!1)},[d,m,u,n]);const Qe=p.useMemo(()=>Fy(i,s,t),[i,s,t]),ht=p.useCallback(et=>{const qt=My(et);t==null||t(qt)},[t]);return ae?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(Zt,{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(ny,{isAdmin:i,effectiveIsAdmin:o,viewAsUser:n,onToggleView:l,quickActions:Qe,userDisplayName:a==null?void 0:a.displayName,userEmail:a==null?void 0:a.email}),e.jsx(ly,{isAdmin:o,dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,refreshing:V,onDateRangeChange:x,onCustomStartDateChange:j,onCustomEndDateChange:w,onShowCustomDatePickerChange:b,onApplyCustomDate:te,onResetCustomDates:f,onRefresh:ct}),o?e.jsx(cy,{kpis:S,priorityDistribution:F,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:ht}):e.jsx(dy,{kpis:S,criticalRequests:I,dateRange:d,customStartDate:m,customEndDate:u,onKPIClick:ht,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(yy,{isAdmin:o,breachedRequests:Ge,pagination:N,onPageChange:dt,onNavigate:t}),e.jsx(Cy,{isAdmin:o,recentActivity:D,pagination:v,refreshing:V,onPageChange:xe,onRefresh:ct,onNavigate:t,currentUserId:a==null?void 0:a.userId,currentUserDisplayName:a==null?void 0:a.displayName,currentUserEmail:a==null?void 0:a.email})]}),o&&S&&e.jsx(Sy,{kpis:S,upcomingDeadlines:G,criticalRequests:I,departmentStats:_,dateRange:d,customStartDate:m,customEndDate:u,exportingDeptStats:Ae,onKPIClick:ht,onExportDepartmentStats:Se}),!o&&S&&e.jsx(Ay,{kpis:S}),o&&F.length>0&&e.jsx(ky,{priorityDistribution:F,onNavigate:t}),o&&Ge.length>0&&e.jsx(Ry,{breachedRequests:Ge,pagination:N,dateRange:d,customStartDate:m,customEndDate:u,onPageChange:dt,onKPIClick:ht,onNavigate:t}),Oe.length>0&&e.jsx(Py,{isAdmin:o,upcomingDeadlines:Oe,pagination:k,onPageChange:ue,onNavigate:t}),o&&B&&e.jsx(Ey,{aiRemarkUtilization:B}),o&&re.length>0&&e.jsx(Iy,{approverPerformance:re,pagination:E,dateRange:d,customStartDate:m,customEndDate:u,loading:ae,exportingApproverPerformance:We,onPageChange:Te,onExport:Ye,onNavigate:t})]})}const _y={searchTerm:"",statusFilter:"all",priorityFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},iu=tr({name:"openRequests",initialState:_y,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setSortBy:(t,s)=>{t.sortBy=s.payload},setSortOrder:(t,s)=>{t.sortOrder=s.payload},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.currentPage=1}}}),{setSearchTerm:Ly,setStatusFilter:Oy,setPriorityFilter:$y,setSortBy:By,setSortOrder:Uy,setCurrentPage:Vy,clearFilters:zy}=iu.actions;function Hy(){const t=Gr(),{searchTerm:s,statusFilter:a,priorityFilter:r,sortBy:n,sortOrder:i,currentPage:o}=ar(f=>f.openRequests),l=p.useCallback(f=>t(Ly(f)),[t]),c=p.useCallback(f=>t(Oy(f)),[t]),d=p.useCallback(f=>t($y(f)),[t]),m=p.useCallback(f=>t(By(f)),[t]),u=p.useCallback(f=>t(Uy(f)),[t]),h=p.useCallback(f=>t(Vy(f)),[t]),x=p.useCallback(()=>t(zy()),[t]),g=[s,r!=="all"?r:null,a!=="all"?a:null].filter(Boolean).length;return{searchTerm:s,statusFilter:a,priorityFilter:r,sortBy:n,sortOrder:i,currentPage:o,setSearchTerm:l,setStatusFilter:c,setPriorityFilter:d,setSortBy:m,setSortOrder:u,setCurrentPage:h,clearFilters:x,activeFiltersCount:g}}function li(){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 Wy(t){var l;const s=t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",a=Array.from({length:t.approverCount||1},(c,d)=>{const m=d,u=t.approvers[m]||{},h=m+1,x=u.tat??"";let g=0;typeof x=="number"&&(g=u.tatType==="days"?x*24:x);const f=u.email||"",j=u.name&&u.name.trim()||f.split("@")[0]||`Approver ${h}`;return{levelNumber:h,levelName:`Level ${h}`,approverId:li(),approverEmail:f,approverName:j,tatHours:g>0?g:24,isFinalApprover:h===(t.approverCount||1)}}),r=[...(t.spectators||[]).map(c=>({userId:li(),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:li(),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 he.post("/workflows",n),o=((l=i.data)==null?void 0:l.data)||i.data;return{id:o.id||o.workflowId||""}}async function ou(t,s,a="SUPPORTING"){var l;const r={templateType:t.templateType,title:t.title,description:t.description,priority:t.priorityUi.toUpperCase()==="EXPRESS"?"EXPRESS":"STANDARD",approvers:Array.from({length:t.approverCount||1},(c,d)=>{const m=t.approvers[d]||{},u=typeof m.tat=="number"?m.tat:0;if(!m.email||!m.email.trim())throw new Error(`Email is required for approver at level ${d+1}.`);return{email:m.email,tat:u,tatType:m.tatType||"hours"}})};t.spectators&&t.spectators.length>0&&(r.spectators=t.spectators.filter(c=>c==null?void 0:c.email).map(c=>({email:c.email})));const n=new FormData;n.append("payload",JSON.stringify(r)),n.append("category",a),s.forEach(c=>n.append("files",c));const i=await he.post("/workflows/multipart",n,{headers:{"Content-Type":"multipart/form-data"}}),o=((l=i.data)==null?void 0:l.data)||i.data;return{id:o==null?void 0:o.requestId}}async function Gy(t={}){var g;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:o,initiator:l,approver:c,slaCompliance:d,dateRange:m,startDate:u,endDate:h}=t,x=await he.get("/workflows",{params:{page:s,limit:a,search:r,status:n,priority:i,department:o,initiator:l,approver:c,slaCompliance:d,dateRange:m,startDate:u,endDate:h}});return((g=x.data)==null?void 0:g.data)||x.data}async function Ky(t={}){var f,j,w,b,C;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:o,initiator:l,approver:c,approverType:d,slaCompliance:m,dateRange:u,startDate:h,endDate:x}=t,g=await he.get("/workflows/participant-requests",{params:{page:s,limit:a,search:r,status:n,priority:i,department:o,initiator:l,approver:c,approverType:d,slaCompliance:m,dateRange:u,startDate:h,endDate:x}});return{data:((j=(f=g.data)==null?void 0:f.data)==null?void 0:j.data)||((w=g.data)==null?void 0:w.data)||[],pagination:((C=(b=g.data)==null?void 0:b.data)==null?void 0:C.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Yy(t={}){var g,f,j,w,b;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:o,initiator:l,approver:c,slaCompliance:d,dateRange:m,startDate:u,endDate:h}=t,x=await he.get("/workflows/my",{params:{page:s,limit:a,search:r,status:n,priority:i,department:o,initiator:l,approver:c,slaCompliance:d,dateRange:m,startDate:u,endDate:h}});return{data:((f=(g=x.data)==null?void 0:g.data)==null?void 0:f.data)||((j=x.data)==null?void 0:j.data)||[],pagination:((b=(w=x.data)==null?void 0:w.data)==null?void 0:b.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Zy(t={}){var h,x,g,f,j;const{page:s=1,limit:a=20,search:r,status:n,priority:i,department:o,slaCompliance:l,dateRange:c,startDate:d,endDate:m}=t,u=await he.get("/workflows/my-initiated",{params:{page:s,limit:a,search:r,status:n,priority:i,department:o,slaCompliance:l,dateRange:c,startDate:d,endDate:m}});return{data:((x=(h=u.data)==null?void 0:h.data)==null?void 0:x.data)||((g=u.data)==null?void 0:g.data)||[],pagination:((j=(f=u.data)==null?void 0:f.data)==null?void 0:j.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Xy(t={}){var d,m,u,h,x;const{page:s=1,limit:a=20,search:r,status:n,priority:i,sortBy:o,sortOrder:l}=t,c=await he.get("/workflows/open-for-me",{params:{page:s,limit:a,search:r,status:n,priority:i,sortBy:o,sortOrder:l}});return{data:((m=(d=c.data)==null?void 0:d.data)==null?void 0:m.data)||((u=c.data)==null?void 0:u.data)||[],pagination:((x=(h=c.data)==null?void 0:h.data)==null?void 0:x.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function Jy(t={}){var d,m,u,h,x;const{page:s=1,limit:a=20,search:r,status:n,priority:i,sortBy:o,sortOrder:l}=t,c=await he.get("/workflows/closed-by-me",{params:{page:s,limit:a,search:r,status:n,priority:i,sortBy:o,sortOrder:l}});return{data:((m=(d=c.data)==null?void 0:d.data)==null?void 0:m.data)||((u=c.data)==null?void 0:u.data)||[],pagination:((x=(h=c.data)==null?void 0:h.data)==null?void 0:x.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function xs(t,s){var r;const a=await he.get(`/workflows/${t}/details`);return((r=a.data)==null?void 0:r.data)||a.data}async function Za(t){var a;const s=await he.get(`/workflows/${t}/work-notes`);return((a=s.data)==null?void 0:a.data)||s.data}async function lu(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 he.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 cu(t,s,a,r){var i;const n=await he.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 Qy(t,s,a){var n;const r=await he.post(`/workflows/${t}/approvals/${s}/skip`,{reason:a});return((n=r.data)==null?void 0:n.data)||r.data}async function du(t,s){var r;const a=await he.post(`/workflows/${t}/participants/spectator`,{email:s});return((r=a.data)==null?void 0:r.data)||a.data}async function qy(t,s,a,r){var i;const n=await he.post(`/workflows/${t}/pause`,{levelId:s,reason:a,resumeDate:r.toISOString()});return((i=n.data)==null?void 0:i.data)||n.data}async function eb(t,s){var r;const a=await he.post(`/workflows/${t}/resume`,{notes:s});return((r=a.data)==null?void 0:r.data)||a.data}async function tb(t){var a;const s=await he.post(`/workflows/${t}/pause/retrigger`);return((a=s.data)==null?void 0:a.data)||s.data}async function Ac(t){var a;const s=await he.get(`/workflows/${t}/pause`);return((a=s.data)==null?void 0:a.data)||s.data}function sb(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/work-notes/attachments/${t}/preview`}function mu(t){return`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/documents/${t}/preview`}async function _r(t){var n;const a=`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/documents/${t}/download`,r=!0;try{const o=await fetch(a,{credentials:"include"});if(!o.ok){const x=await o.text();throw new Error(`Download failed: ${o.status} - ${x}`)}const l=await o.blob(),c=window.URL.createObjectURL(l),d=o.headers.get("Content-Disposition"),u=((n=d==null?void 0:d.split("filename=")[1])==null?void 0:n.replace(/"/g,""))||"download",h=document.createElement("a");h.href=c,h.download=u,document.body.appendChild(h),h.click(),document.body.removeChild(h),window.URL.revokeObjectURL(c)}catch(i){throw console.error("[Download] Failed:",i),i}}async function kc(t){var n;const a=`https://re-workflow-nt-dev.siplsolutions.com/api/v1/workflows/work-notes/attachments/${t}/download`,r=!0;try{const o=await fetch(a,{credentials:"include"});if(!o.ok){const x=await o.text();throw new Error(`Download failed: ${o.status} - ${x}`)}const l=await o.blob(),c=window.URL.createObjectURL(l),d=o.headers.get("Content-Disposition"),u=((n=d==null?void 0:d.split("filename=")[1])==null?void 0:n.replace(/"/g,""))||"download",h=document.createElement("a");h.href=c,h.download=u,document.body.appendChild(h),h.click(),document.body.removeChild(h),window.URL.revokeObjectURL(c)}catch(i){throw console.error("[Download] Failed:",i),i}}const hs={createWorkflowFromForm:Wy,createWorkflowMultipart:ou,listWorkflows:Gy,listParticipantRequests:Ky,listMyWorkflows:Yy,listMyInitiatedWorkflows:Zy,listOpenForMe:Xy,listClosedByMe:Jy,submitWorkflow:uu,getWorkflowDetails:xs,getWorkNotes:Za,createWorkNoteMultipart:lu};async function uu(t){var a;const s=await he.patch(`/workflows/${t}/submit`);return((a=s.data)==null?void 0:a.data)||s.data}async function ab(t,s){var r;const a=await he.put(`/workflows/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function rb(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 he.put(`/workflows/${t}/multipart`,i,{headers:{"Content-Type":"multipart/form-data"}});return((l=o.data)==null?void 0:l.data)||o.data}async function Wi(t,s,a){var n;const r=await he.patch(`/workflows/${t}/approvals/${s}/approve`,{action:"APPROVE",comments:a||""});return((n=r.data)==null?void 0:n.data)||r.data}async function Gi(t,s,a,r){var i;const n=await he.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 nb(t,s){const a=await he.put(`/tat/breach-reason/${t}`,{breachReason:s});if(!a.data.success)throw new Error(a.data.error||"Failed to update breach reason")}function Qt(t,s){if(!t)return"N/A";try{const a=typeof t=="string"?new Date(t):t;if(isNaN(a.getTime()))return"Invalid Date";const{includeTime:r=!0,includeSeconds:n=!1,format:i="medium"}=s||{};return r?a.toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",...n&&{second:"2-digit"},hour12:!0}):a.toLocaleDateString("en-US",{year:"numeric",month:i==="short"?"short":"long",day:"numeric"})}catch(a){return console.error("Error formatting date:",a),String(t)}}function hu(t){return Qt(t,{includeTime:!1,format:"short"})}function Ks(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,d=String(a.getMinutes()).padStart(2,"0"),m=String(a.getSeconds()).padStart(2,"0"),u=l>=12?"PM":"AM";return`${r} ${i} ${o}, ${c}:${d}:${m} ${u}`}return`${r} ${i} ${o}`}catch(a){return console.error("Error formatting date:",a),String(t)}}const ib=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Os,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Dt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Dt,iconColor:"text-gray-600"}}},ob=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:He,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Ie,iconColor:"text-green-600",label:"Needs Closure"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:yt,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ce,iconColor:"text-gray-600",label:"Closed"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ie,iconColor:"text-gray-600",label:t}}};function lb({onViewRequest:t}){const[s,a]=p.useState([]),[r,n]=p.useState(!1),[i,o]=p.useState(!1),[l,c]=p.useState(1),[d,m]=p.useState(0),[u]=p.useState(10),h=p.useRef(null),x=Hy(),g=p.useCallback(async(v=1,N)=>{try{v===1&&(n(!0),a([]));const k=await hs.listOpenForMe({page:v,limit:u,search:N==null?void 0:N.search,status:N==null?void 0:N.status,priority:N==null?void 0:N.priority,sortBy:N==null?void 0:N.sortBy,sortOrder:N==null?void 0:N.sortOrder}),E=Array.isArray(k==null?void 0:k.data)?k.data:[],P=k==null?void 0:k.pagination;P&&(x.setCurrentPage(P.page||1),c(P.totalPages||1),m(P.total||0));const M=E.map(y=>{var L,K,O,$;const A=y.submittedAt||y.submitted_at||y.createdAt||y.created_at;return{id:y.requestNumber||y.request_number||y.requestId,requestId:y.requestId,displayId:y.requestNumber||y.request_number||y.requestId,title:y.title,description:y.description,status:(y.status||"").toString().toLowerCase().replace("_","-"),priority:(y.priority||"").toString().toLowerCase(),initiator:{name:((L=y.initiator)==null?void 0:L.displayName)||((K=y.initiator)==null?void 0:K.email)||"—",avatar:(((O=y.initiator)==null?void 0:O.displayName)||(($=y.initiator)==null?void 0:$.email)||"NA").split(" ").map(T=>T[0]).join("").slice(0,2).toUpperCase()},currentApprover:y.currentApprover?{name:y.currentApprover.name||y.currentApprover.email||"—",avatar:(y.currentApprover.name||y.currentApprover.email||"CA").split(" ").map(T=>T[0]).join("").slice(0,2).toUpperCase(),sla:y.currentApprover.sla}:void 0,createdAt:A||"—",approvalStep:y.currentLevel?`Step ${y.currentLevel} of ${y.totalLevels||"?"}`:void 0,department:y.department,currentLevelSLA:y.currentLevelSLA,templateType:y.templateType||y.template_type}});a(M)}finally{n(!1),o(!1)}},[u,x]);h.current=g;const f=()=>{o(!0),g(x.currentPage,{search:x.searchTerm||void 0,status:x.statusFilter!=="all"?x.statusFilter:void 0,priority:x.priorityFilter!=="all"?x.priorityFilter:void 0,sortBy:x.sortBy,sortOrder:x.sortOrder})},j=v=>{v>=1&&v<=l&&(x.setCurrentPage(v),g(v,{search:x.searchTerm||void 0,status:x.statusFilter!=="all"?x.statusFilter:void 0,priority:x.priorityFilter!=="all"?x.priorityFilter:void 0,sortBy:x.sortBy,sortOrder:x.sortOrder}))},w=()=>{const v=[];let k=Math.max(1,x.currentPage-Math.floor(2.5)),E=Math.min(l,k+5-1);E-k<4&&(k=Math.max(1,E-5+1));for(let P=k;P<=E;P++)v.push(P);return v},b=p.useRef(!1);p.useEffect(()=>{if(!b.current){b.current=!0;const v=x.currentPage||1;g(v,{search:x.searchTerm||void 0,status:x.statusFilter!=="all"?x.statusFilter:void 0,priority:x.priorityFilter!=="all"?x.priorityFilter:void 0,sortBy:x.sortBy,sortOrder:x.sortOrder})}},[]),p.useEffect(()=>{if(!b.current)return;const v=setTimeout(()=>{x.setCurrentPage(1),g(1,{search:x.searchTerm||void 0,status:x.statusFilter!=="all"?x.statusFilter:void 0,priority:x.priorityFilter!=="all"?x.priorityFilter:void 0,sortBy:x.sortBy,sortOrder:x.sortOrder})},x.searchTerm?500:0);return()=>clearTimeout(v)},[x.searchTerm,x.statusFilter,x.priorityFilter,x.sortBy,x.sortOrder]);const C=s;return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto",children:[e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-3 sm:gap-4 md:gap-6",children:[e.jsx("div",{className:"space-y-1 sm:space-y-2",children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-slate-800 to-slate-900 rounded-xl flex items-center justify-center shadow-lg",children:e.jsx(Ee,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900",children:"My Open Requests"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:"Manage and track your active approval requests"})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsxs(se,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold",children:[r?"Loading…":`${d||s.length} open`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(R,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:f,disabled:i,children:[e.jsx(Zt,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:i?"Refreshing...":"Refresh"})]})]})]}),e.jsxs(X,{className:"shadow-lg border-0",children:[e.jsx(le,{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(zr,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(je,{className:"text-xs sm:text-sm",children:x.activeFiltersCount>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[x.activeFiltersCount," filter",x.activeFiltersCount>1?"s":""," active"]})})]})]}),x.activeFiltersCount>0&&e.jsxs(R,{variant:"ghost",size:"sm",onClick:x.clearFilters,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(ut,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(J,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ws,{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(we,{placeholder:"Search requests, IDs...",value:x.searchTerm,onChange:v=>x.setSearchTerm(v.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(Be,{value:x.priorityFilter,onValueChange:x.setPriorityFilter,children:[e.jsx(Ve,{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(Ue,{placeholder:"All Priorities"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Priorities"}),e.jsx(W,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(W,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Be,{value:x.statusFilter,onValueChange:x.setStatusFilter,children:[e.jsx(Ve,{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(Ue,{placeholder:"All Statuses"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Statuses"}),e.jsx(W,{value:"pending",children:"Pending (In Approval)"}),e.jsx(W,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Be,{value:x.sortBy,onValueChange:v=>x.setSortBy(v),children:[e.jsx(Ve,{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(Ue,{placeholder:"Sort by"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"due",children:"Due Date"}),e.jsx(W,{value:"created",children:"Date Created"}),e.jsx(W,{value:"priority",children:"Priority"}),e.jsx(W,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>x.setSortOrder(x.sortOrder==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:x.sortOrder==="asc"?e.jsx(Dm,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Rm,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]}),e.jsx("div",{className:"space-y-3",children:C.map(v=>{const N=ib(v.priority),k=ob(v.status);return e.jsx(X,{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(v.id,v.title),children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${N.color} border shadow-sm`,children:e.jsx(N.icon,{className:`w-5 h-5 ${N.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:v.displayId||v.id}),e.jsxs(se,{variant:"outline",className:`${k.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(k.icon,{className:"w-3.5 h-3.5 mr-1"}),k.label||v.status]}),v.department&&e.jsx(se,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:v.department}),e.jsx(se,{variant:"outline",className:`${N.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:v.priority}),(()=>{const E=(v==null?void 0:v.templateType)||(v==null?void 0:v.template_type)||"",P=(E==null?void 0:E.toUpperCase())||"";let M="Custom",y="bg-purple-100 !text-purple-600 border-purple-200";return P==="DEALER CLAIM"?(M="Claim Management",y="bg-blue-100 !text-blue-700 border-blue-200"):P==="TEMPLATE"&&(M="Template"),e.jsx(se,{variant:"outline",className:`${y} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:M})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:v.title}),v.currentLevelSLA&&(()=>{var A;const E=!!(v.isPaused||(A=v.pauseInfo)!=null&&A.isPaused||v.status==="paused"),P=v.currentLevelSLA.percentageUsed||0,y=E?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:P>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:P>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:P>=50?{bg:"bg-amber-50 border border-amber-200",progress:"bg-amber-500",text:"text-amber-600",icon:"text-blue-600"}:{bg:"bg-green-50 border border-green-200",progress:"bg-green-600",text:"text-gray-700",icon:"text-blue-600"};return e.jsxs("div",{className:`p-2 rounded-md ${y.bg}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[E?e.jsx(Ir,{className:`w-3.5 h-3.5 ${y.icon}`}):e.jsx(He,{className:`w-3.5 h-3.5 ${y.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",P,"% ",E&&"(paused)"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:v.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${y.text}`,children:[v.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(Gs,{value:P,className:"h-1.5",indicatorClassName:y.progress})]})})(),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Bt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(Ut,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:v.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:v.initiator.name})]}),v.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Bt,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(Ut,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:v.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:v.currentApprover.name})]}),v.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ie,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:v.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(qe,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",v.createdAt!=="—"?Ks(v.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(Wt,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},v.id)})}),C.length===0&&e.jsx(X,{className:"shadow-lg border-0",children:e.jsxs(J,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Ee,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md",children:x.searchTerm||x.activeFiltersCount>0?"Try adjusting your filters or search terms to see more results.":"No open requests available at the moment."}),x.activeFiltersCount>0&&e.jsx(R,{variant:"outline",className:"mt-4",onClick:x.clearFilters,children:"Clear all filters"})]})}),l>1&&!r&&e.jsx(X,{className:"shadow-md",children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(x.currentPage-1)*u+1," to ",Math.min(x.currentPage*u,d)," of ",d," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{variant:"outline",size:"sm",onClick:()=>j(x.currentPage-1),disabled:x.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(Wt,{className:"h-4 w-4 rotate-180"})}),x.currentPage>3&&l>5&&e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"outline",size:"sm",onClick:()=>j(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),w().map(v=>e.jsx(R,{variant:v===x.currentPage?"default":"outline",size:"sm",onClick:()=>j(v),className:`h-8 w-8 p-0 ${v===x.currentPage?"bg-re-green text-white hover:bg-re-green/90":""}`,children:v},v)),x.currentPage5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>j(l),className:"h-8 w-8 p-0",children:l})]}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>j(x.currentPage+1),disabled:x.currentPage===l,className:"h-8 w-8 p-0",children:e.jsx(Wt,{className:"h-4 w-4"})})]})]})})})]})}function cb({totalRecords:t,loading:s,refreshing:a,onRefresh:r}){return e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-3 sm:gap-4 md:gap-6","data-testid":"closed-requests-header",children:[e.jsx("div",{className:"space-y-1 sm:space-y-2",children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-slate-800 to-slate-900 rounded-xl flex items-center justify-center shadow-lg",children:e.jsx(Ee,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900",children:"My Closed Requests"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:"Review your completed and archived requests"})]})]})}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsxs(se,{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(R,{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(Zt,{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 db({searchTerm:t,priorityFilter:s,statusFilter:a,sortBy:r,sortOrder:n,activeFiltersCount:i,onSearchChange:o,onPriorityChange:l,onStatusChange:c,onSortByChange:d,onSortOrderChange:m,onClearFilters:u}){return e.jsxs(X,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(le,{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(zr,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(je,{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(R,{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(ut,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(J,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ws,{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(we,{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(Be,{value:s,onValueChange:l,children:[e.jsx(Ve,{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(Ue,{placeholder:"All Priorities"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Priorities"}),e.jsx(W,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(W,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(Be,{value:a,onValueChange:c,children:[e.jsx(Ve,{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(Ue,{placeholder:"Closure Type"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Closures"}),e.jsx(W,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(W,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yt,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Be,{value:r,onValueChange:h=>d(h),children:[e.jsx(Ve,{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(Ue,{placeholder:"Sort by"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"due",children:"Due Date"}),e.jsx(W,{value:"created",children:"Date Created"}),e.jsx(W,{value:"priority",children:"Priority"})]})]}),e.jsx(R,{variant:"outline",size:"sm",onClick:m,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(Dm,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Rm,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function mb(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Os,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Dt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Dt,iconColor:"text-gray-600"}}}function ub(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:Ce,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:yt,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ie,iconColor:"text-gray-600",label:t,description:""}}}function hb({request:t,onViewRequest:s}){const a=mb(t.priority),r=ub(t.status),n=a.icon,i=r.icon;return e.jsx(X,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>s==null?void 0:s(t.id,t.title),"data-testid":`closed-request-card-${t.id}`,children:e.jsx(J,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-5",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${a.color} border shadow-sm`,children:e.jsx(n,{className:`w-5 h-5 ${a.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:t.displayId||t.id}),e.jsxs(se,{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(se,{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(se,{variant:"outline",className:`${a.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:t.priority}),(()=>{const o=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",l=(o==null?void 0:o.toUpperCase())||"";let c="Custom",d="bg-purple-100 !text-purple-600 border-purple-200";return l==="DEALER CLAIM"?(c="Claim Management",d="bg-blue-100 !text-blue-700 border-blue-200"):l==="TEMPLATE"&&(c="Template"),e.jsx(se,{variant:"outline",className:`${d} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:c})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children: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(Bt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(Ut,{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(Ce,{className:"w-3.5 h-3.5 text-green-600"}),e.jsxs("span",{className:"font-medium",children:[t.completedLevels||0,"/",t.totalLevels," Approvals"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(qe,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?Ks(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ce,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",Ks(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(Wt,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function pb({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(hb,{request:r,onViewRequest:a},r.id))})}function xb({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(X,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(J,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Ee,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md",children:t||s>0?"Try adjusting your filters or search terms to see more results.":"No closed requests available at the moment."}),s>0&&e.jsx(R,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function gb(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 fb({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const o=gb(a,r);return e.jsx(X,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(a-1)*i+1," to ",Math.min(a*i,n)," of ",n," closed requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{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(Wt,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(R,{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(R,{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)),a5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(R,{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(Wt,{className:"h-4 w-4"})})]})]})})})}function yb(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 bb(t){return t.map(yb)}function vb({itemsPerPage:t=10}={}){const[s,a]=p.useState([]),[r,n]=p.useState(!1),[i,o]=p.useState(!1),[l,c]=p.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=p.useCallback(async(u=1,h)=>{try{u===1&&(n(!0),a([]));const x=await hs.listClosedByMe({page:u,limit:t,search:h==null?void 0:h.search,status:h!=null&&h.status&&h.status!=="all"?h.status:void 0,priority:h==null?void 0:h.priority,sortBy:h==null?void 0:h.sortBy,sortOrder:h==null?void 0:h.sortOrder}),g=Array.isArray(x==null?void 0:x.data)?x.data:[],f=bb(g);a(f);const j=x==null?void 0:x.pagination;j&&c({currentPage:j.page||1,totalPages:j.totalPages||1,totalRecords:j.total||0,itemsPerPage:t})}catch(x){console.error("[ClosedRequests] Error fetching requests:",x),a([])}finally{n(!1),o(!1)}},[t]),m=p.useCallback(u=>{o(!0),d(l.currentPage,u)},[d,l.currentPage]);return{requests:s,loading:r,refreshing:i,pagination:l,fetchRequests:d,handleRefresh:m}}const jb={searchTerm:"",statusFilter:"all",priorityFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},pu=tr({name:"closedRequests",initialState:jb,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setSortBy:(t,s)=>{t.sortBy=s.payload},setSortOrder:(t,s)=>{t.sortOrder=s.payload},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.currentPage=1}}}),{setSearchTerm:Nb,setStatusFilter:wb,setPriorityFilter:Cb,setSortBy:Sb,setSortOrder:Ab,setCurrentPage:kb,clearFilters:Tb}=pu.actions;function Db({onFiltersChange:t,debounceMs:s=500}={}){const a=Gr(),r=p.useRef(null),n=p.useRef(!0),{searchTerm:i,statusFilter:o,priorityFilter:l,sortBy:c,sortOrder:d,currentPage:m}=ar(v=>v.closedRequests),u=p.useCallback(v=>a(Nb(v)),[a]),h=p.useCallback(v=>a(wb(v)),[a]),x=p.useCallback(v=>a(Cb(v)),[a]),g=p.useCallback(v=>a(Sb(v)),[a]),f=p.useCallback(v=>a(Ab(v)),[a]),j=p.useCallback(v=>a(kb(v)),[a]),w=p.useCallback(()=>({search:i,status:o,priority:l,sortBy:c,sortOrder:d}),[i,o,l,c,d]);p.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const v=setTimeout(()=>{t&&t(w())},i?s:0);return r.current=v,()=>{r.current&&clearTimeout(r.current)}},[i,o,l,c,d,t,w,s]);const b=p.useCallback(()=>{a(Tb())},[a]),C=[i,l!=="all"?l:null,o!=="all"?o:null].filter(Boolean).length;return{searchTerm:i,priorityFilter:l,statusFilter:o,sortBy:c,sortOrder:d,currentPage:m,setSearchTerm:u,setPriorityFilter:x,setStatusFilter:h,setSortBy:g,setSortOrder:f,setCurrentPage:j,clearFilters:b,activeFiltersCount:C,getFilters:w}}function Rb({onViewRequest:t}){const s=vb({itemsPerPage:10}),a=p.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=Db(),n=p.useRef({searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,sortBy:r.sortBy,sortOrder:r.sortOrder}),i=p.useRef(!1);p.useEffect(()=>{const c=r.currentPage||1;a.current(c,{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}),i.current=!0},[]),p.useEffect(()=>{if(!i.current)return;const c=n.current;if(!(c.searchTerm!==r.searchTerm||c.statusFilter!==r.statusFilter||c.priorityFilter!==r.priorityFilter||c.sortBy!==r.sortBy||c.sortOrder!==r.sortOrder))return;const m=setTimeout(()=>{r.setCurrentPage(1),a.current(1,{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}),n.current={searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,sortBy:r.sortBy,sortOrder:r.sortOrder}},r.searchTerm!==c.searchTerm?500:0);return()=>clearTimeout(m)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.sortBy,r.sortOrder]);const o=p.useCallback(c=>{c>=1&&c<=s.pagination.totalPages&&(r.setCurrentPage(c),s.fetchRequests(c,{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]),l=p.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(cb,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:l}),e.jsx(db,{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(pb,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(xb,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(fb,{pagination:s.pagination,onPageChange:o})]})}const xu={"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"]}},Pb={"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 Fo(t,s=[],a){const[r,n]=p.useState(null),[i,o]=p.useState(!1),[l,c]=p.useState(!0),[d,m]=p.useState(null),[u,h]=p.useState(null),[x,g]=p.useState(!1),f=(N,k)=>(N||k||"NA").toString().split(" ").map(P=>P[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),j=N=>{const k=(N||"").toUpperCase();return k==="IN_PROGRESS"?"in-review":k==="PENDING"?"pending":k==="APPROVED"?"approved":k==="REJECTED"?"rejected":k==="CLOSED"?"closed":k==="SKIPPED"?"skipped":(N||"").toLowerCase()},w=p.useCallback(async()=>{var N,k,E,P,M,y,A,L,K,O,$,T,S;o(!0);try{const D=await hs.getWorkflowDetails(t);if(!D){console.warn("[useRequestDetails] No details returned from API");return}const I=D.workflow||{},_=Array.isArray(D.approvals)?D.approvals:[],F=Array.isArray(D.participants)?D.participants:[],G=Array.isArray(D.documents)?D.documents:[],B=D.summary||{},re=Array.isArray(D.tatAlerts)?D.tatAlerts:[];re.length>0;const ae=(B==null?void 0:B.currentLevel)||I.currentLevel||1,V=_.map(te=>{const xe=te.levelNumber||0,dt=(te.status||"").toString().toUpperCase(),ue=te.levelId||te.level_id;let Te=j(te.status);xe>ae&&dt!=="APPROVED"&&dt!=="REJECTED"?Te="waiting":xe===ae&&dt==="PENDING"&&(Te="pending");const Qe=re.filter(ht=>ht.levelId===ue);return{step:xe,levelId:ue,role:te.levelName||te.approverName||"Approver",status:Te,approver:te.approverName||te.approverEmail,approverId:te.approverId||te.approver_id,approverEmail:te.approverEmail,tatHours:Number(te.tatHours||0),elapsedHours:Number(te.elapsedHours||0),remainingHours:Number(te.remainingHours||0),tatPercentageUsed:Number(te.tatPercentageUsed||0),actualHours:te.levelEndTime&&te.levelStartTime?Math.max(0,(new Date(te.levelEndTime).getTime()-new Date(te.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:te.comments||void 0,timestamp:te.actionDate||void 0,levelStartTime:te.levelStartTime||te.tatStartTime,tatAlerts:Qe,skipReason:te.skipReason||void 0,isSkipped:dt==="SKIPPED"||te.isSkipped||!1}}),Y=F.filter(te=>(te.participantType||te.participant_type||"").toUpperCase()==="SPECTATOR").map(te=>({name:te.userName||te.user_name||te.userEmail||te.user_email,role:"Spectator",email:te.userEmail||te.user_email,avatar:f(te.userName||te.user_name,te.userEmail||te.user_email)})),Z=te=>{var dt,ue;if(!te)return;const xe=F.find(Te=>Te.userId===te||Te.user_id===te);return xe!=null&&xe.userName||xe!=null&&xe.user_name?xe.userName||xe.user_name:I.initiatorId===te?((dt=I.initiator)==null?void 0:dt.displayName)||((ue=I.initiator)==null?void 0:ue.email):te},U=G.map(te=>{const xe=Number(te.fileSize||te.file_size||0),dt=(xe/(1024*1024)).toFixed(2)+" MB";return{documentId:te.documentId||te.document_id,name:te.originalFileName||te.fileName||te.file_name,fileType:te.fileType||te.file_type||"",size:dt,sizeBytes:xe,uploadedBy:Z(te.uploadedBy||te.uploaded_by),uploadedAt:te.uploadedAt||te.uploaded_at}}),ee=Array.isArray(D.activities)?D.activities.filter(te=>(te.type||"").toLowerCase()!=="sla_warning"):[];let ie=null;try{ie=await Ac(I.requestId)}catch(te){console.debug("Pause details not available:",te)}let de=null,Ae=null,We=null,Se=null;if(I.workflowType==="CLAIM_MANAGEMENT"||I.templateType==="claim-management")try{console.debug("[useRequestDetails] Fetching claim details for requestId:",I.requestId);const te=await he.get(`/dealer-claims/${I.requestId}`);console.debug("[useRequestDetails] Claim API response:",{status:te.status,hasData:!!te.data,dataKeys:te.data?Object.keys(te.data):[],fullResponse:te.data});const xe=((N=te.data)==null?void 0:N.data)||te.data;if(console.debug("[useRequestDetails] Extracted claimData:",{hasClaimData:!!xe,claimDataKeys:xe?Object.keys(xe):[],hasClaimDetails:!!(xe!=null&&xe.claimDetails||xe!=null&&xe.claim_details),hasProposalDetails:!!(xe!=null&&xe.proposalDetails||xe!=null&&xe.proposal_details),hasCompletionDetails:!!(xe!=null&&xe.completionDetails||xe!=null&&xe.completion_details),hasInternalOrder:!!(xe!=null&&xe.internalOrder||xe!=null&&xe.internal_order)}),xe){de=xe.claimDetails||xe.claim_details,Ae=xe.proposalDetails||xe.proposal_details,We=xe.completionDetails||xe.completion_details,Se=xe.internalOrder||xe.internal_order||null;const dt=xe.budgetTracking||xe.budget_tracking||null,ue=xe.invoice||null,Te=xe.creditNote||xe.credit_note||null,Qe=xe.completionExpenses||xe.completion_expenses||null;de&&(de.budgetTracking=dt,de.invoice=ue,de.creditNote=Te,de.completionExpenses=Qe),console.debug("[useRequestDetails] Extracted details:",{claimDetails:de?{hasActivityName:!!(de.activityName||de.activity_name),hasActivityType:!!(de.activityType||de.activity_type),hasLocation:!!de.location,activityName:de.activityName||de.activity_name,activityType:de.activityType||de.activity_type,location:de.location,allKeys:Object.keys(de)}:null,hasProposalDetails:!!Ae,hasCompletionDetails:!!We,hasInternalOrder:!!Se,hasBudgetTracking:!!dt,hasInvoice:!!ue,hasCreditNote:!!Te,hasCompletionExpenses:Array.isArray(Qe)&&Qe.length>0})}else console.warn("[useRequestDetails] No claimData found in response")}catch(te){console.error("[useRequestDetails] Error fetching claim details:",{error:(te==null?void 0:te.message)||te,status:(k=te==null?void 0:te.response)==null?void 0:k.status,statusText:(E=te==null?void 0:te.response)==null?void 0:E.statusText,responseData:(P=te==null?void 0:te.response)==null?void 0:P.data,requestId:I.requestId})}const Ye={...I,id:I.requestNumber||I.requestId,requestId:I.requestId,requestNumber:I.requestNumber,title:I.title,description:I.description,status:j(I.status),priority:(I.priority||"").toString().toLowerCase(),workflowType:I.workflowType||(I.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:V,approvals:_,participants:F,documents:U,spectators:Y,summary:B,initiator:{name:((M=I.initiator)==null?void 0:M.displayName)||((y=I.initiator)==null?void 0:y.email),role:((A=I.initiator)==null?void 0:A.designation)||void 0,department:((L=I.initiator)==null?void 0:L.department)||void 0,email:((K=I.initiator)==null?void 0:K.email)||void 0,phone:((O=I.initiator)==null?void 0:O.phone)||void 0,avatar:f(($=I.initiator)==null?void 0:$.displayName,(T=I.initiator)==null?void 0:T.email)},createdAt:I.createdAt,updatedAt:I.updatedAt,totalSteps:I.totalLevels||1,currentStepRaw:(B==null?void 0:B.currentLevel)||I.currentLevel||1,currentStep:Math.min(Math.max(1,(B==null?void 0:B.currentLevel)||I.currentLevel||1),I.totalLevels||1),auditTrail:ee,conclusionRemark:I.conclusionRemark||null,closureDate:I.closureDate||null,pauseInfo:ie||null,claimDetails:de||null,proposalDetails:Ae||null,completionDetails:We||null,internalOrder:Se||null,budgetTracking:(de==null?void 0:de.budgetTracking)||null,invoice:(de==null?void 0:de.invoice)||null,creditNote:(de==null?void 0:de.creditNote)||null,completionExpenses:(de==null?void 0:de.completionExpenses)||null};n(Ye);const Ge=(S=a==null?void 0:a.email)==null?void 0:S.toLowerCase(),Oe=_.find(te=>{const xe=(te.status||"").toString().toUpperCase(),dt=(te.approverEmail||"").toLowerCase(),ue=te.levelNumber||0;return(xe==="PENDING"||xe==="IN_PROGRESS"||xe==="PAUSED")&&dt===Ge&&ue===ae});h(Oe||null);const ct=a==null?void 0:a.userId;if(ct){const te=F.some(xe=>(xe.participantType||xe.participant_type||"").toUpperCase()==="SPECTATOR"&&(xe.userId||xe.user_id)===ct);g(te)}else g(!1)}catch(D){console.error("[useRequestDetails] Error refreshing details:",D),alert("Failed to refresh request details. Please try again.")}finally{o(!1)}},[t,a]);p.useEffect(()=>{if(!t){c(!1);return}let N=!0;return c(!0),m(null),(async()=>{var k,E,P,M,y,A,L,K,O,$,T,S,D,I;try{const _=await hs.getWorkflowDetails(t);if(!N||!_){N&&c(!1);return}const F=_.workflow||{},G=Array.isArray(_.approvals)?_.approvals:[],B=Array.isArray(_.participants)?_.participants:[],re=Array.isArray(_.documents)?_.documents:[],ae=_.summary||{},V=Array.isArray(_.tatAlerts)?_.tatAlerts:[],Y=(F.priority||"").toString().toLowerCase(),Z=(ae==null?void 0:ae.currentLevel)||F.currentLevel||1,U=G.map(ue=>{const Te=ue.levelNumber||0,Qe=(ue.status||"").toString().toUpperCase(),ht=ue.levelId||ue.level_id;let et=j(ue.status);Qe==="PAUSED"?et="paused":Te>Z&&Qe!=="APPROVED"&&Qe!=="REJECTED"?et="waiting":Te===Z&&(Qe==="PENDING"||Qe==="IN_PROGRESS")&&(et=Qe==="IN_PROGRESS"?"in-review":"pending");const qt=V.filter(Es=>Es.levelId===ht);return{step:Te,levelId:ht,role:ue.levelName||ue.approverName||"Approver",status:et,approver:ue.approverName||ue.approverEmail,approverId:ue.approverId||ue.approver_id,approverEmail:ue.approverEmail,tatHours:Number(ue.tatHours||0),elapsedHours:Number(ue.elapsedHours||0),remainingHours:Number(ue.remainingHours||0),tatPercentageUsed:Number(ue.tatPercentageUsed||0),actualHours:ue.elapsedHours!==void 0&&ue.elapsedHours!==null?Number(ue.elapsedHours):void 0,comment:ue.comments||void 0,timestamp:ue.actionDate||void 0,levelStartTime:ue.levelStartTime||ue.tatStartTime,tatAlerts:qt}}),ee=B.filter(ue=>(ue.participantType||"").toUpperCase()==="SPECTATOR").map(ue=>({name:ue.userName||ue.userEmail,role:"Spectator",avatar:f(ue.userName,ue.userEmail)})),ie=ue=>{var Qe,ht;if(!ue)return;const Te=B.find(et=>et.userId===ue);return Te!=null&&Te.userName?Te.userName:F.initiatorId===ue?((Qe=F.initiator)==null?void 0:Qe.displayName)||((ht=F.initiator)==null?void 0:ht.email):ue},de=re.map(ue=>{const Te=Number(ue.fileSize||0),Qe=(Te/(1024*1024)).toFixed(2)+" MB";return{documentId:ue.documentId||ue.document_id,name:ue.originalFileName||ue.fileName,fileType:ue.fileType||ue.file_type||"",size:Qe,sizeBytes:Te,uploadedBy:ie(ue.uploadedBy),uploadedAt:ue.uploadedAt}}),Ae=Array.isArray(_.activities)?_.activities.filter(ue=>(ue.type||"").toLowerCase()!=="sla_warning"):[];let We=null;try{We=await Ac(F.requestId)}catch(ue){console.debug("Pause details not available:",ue)}let Se=null,Ye=null,Ge=null,Oe=null;if(F.workflowType==="CLAIM_MANAGEMENT"||F.templateType==="claim-management")try{console.debug("[useRequestDetails] Initial load - Fetching claim details for requestId:",F.requestId);const ue=await he.get(`/dealer-claims/${F.requestId}`);console.debug("[useRequestDetails] Initial load - Claim API response:",{status:ue.status,hasData:!!ue.data,dataKeys:ue.data?Object.keys(ue.data):[]});const Te=((k=ue.data)==null?void 0:k.data)||ue.data;if(Te){Se=Te.claimDetails||Te.claim_details,Ye=Te.proposalDetails||Te.proposal_details,Ge=Te.completionDetails||Te.completion_details,Oe=Te.internalOrder||Te.internal_order||null;const Qe=Te.budgetTracking||Te.budget_tracking||null,ht=Te.invoice||null,et=Te.creditNote||Te.credit_note||null,qt=Te.completionExpenses||Te.completion_expenses||null;Se&&(Se.budgetTracking=Qe,Se.invoice=ht,Se.creditNote=et,Se.completionExpenses=qt),console.debug("[useRequestDetails] Initial load - Extracted details:",{hasClaimDetails:!!Se,claimDetailsKeys:Se?Object.keys(Se):[],hasProposalDetails:!!Ye,hasCompletionDetails:!!Ge,hasInternalOrder:!!Oe,hasBudgetTracking:!!Qe,hasInvoice:!!ht,hasCreditNote:!!et,hasCompletionExpenses:Array.isArray(qt)&&qt.length>0})}}catch(ue){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(ue==null?void 0:ue.message)||ue,status:(E=ue==null?void 0:ue.response)==null?void 0:E.status,requestId:F.requestId})}const ct={id:F.requestNumber||F.requestId,requestId:F.requestId,title:F.title,description:F.description,priority:Y,status:j(F.status),workflowType:F.workflowType||(F.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:ae,initiator:{name:((P=F.initiator)==null?void 0:P.displayName)||((M=F.initiator)==null?void 0:M.email),role:((y=F.initiator)==null?void 0:y.designation)||void 0,department:((A=F.initiator)==null?void 0:A.department)||void 0,email:((L=F.initiator)==null?void 0:L.email)||void 0,phone:((K=F.initiator)==null?void 0:K.phone)||void 0,avatar:f((O=F.initiator)==null?void 0:O.displayName,($=F.initiator)==null?void 0:$.email)},createdAt:F.createdAt,updatedAt:F.updatedAt,totalSteps:F.totalLevels||1,currentStepRaw:(ae==null?void 0:ae.currentLevel)||F.currentLevel||1,currentStep:Math.min(Math.max(1,(ae==null?void 0:ae.currentLevel)||F.currentLevel||1),F.totalLevels||1),approvalFlow:U,approvals:G,documents:de,spectators:ee,auditTrail:Ae,conclusionRemark:F.conclusionRemark||null,closureDate:F.closureDate||null,pauseInfo:We||null,claimDetails:Se||null,proposalDetails:Ye||null,completionDetails:Ge||null,internalOrder:Oe||null,budgetTracking:(Se==null?void 0:Se.budgetTracking)||null,invoice:(Se==null?void 0:Se.invoice)||null,creditNote:(Se==null?void 0:Se.creditNote)||null,completionExpenses:(Se==null?void 0:Se.completionExpenses)||null};n(ct);const te=(T=a==null?void 0:a.email)==null?void 0:T.toLowerCase(),xe=G.find(ue=>{const Te=(ue.status||"").toString().toUpperCase(),Qe=(ue.approverEmail||"").toLowerCase(),ht=ue.levelNumber||0;return(Te==="PENDING"||Te==="IN_PROGRESS"||Te==="PAUSED")&&Qe===te&&ht===Z});h(xe||null);const dt=a==null?void 0:a.userId;if(dt){const ue=B.some(Te=>(Te.participantType||"").toUpperCase()==="SPECTATOR"&&Te.userId===dt);g(ue)}else g(!1)}catch(_){if(console.error("[useRequestDetails] Error loading request details:",_),N){if(((S=_==null?void 0:_.response)==null?void 0:S.status)===403){const F=((I=(D=_==null?void 0:_.response)==null?void 0:D.data)==null?void 0:I.message)||"You do not have permission to view this request. Access is restricted to the initiator, approvers, and spectators of this request.";m({denied:!0,message:F})}n(null)}}finally{N&&c(!1)}})(),()=>{N=!1}},[t,a]);const b=p.useMemo(()=>{if(r)return r;const N=xu[t];if(N)return N;const k=Pb[t];if(k)return k;const E=s.find(P=>P.id===t||P.requestNumber===t||P.request_number===t);return E||null},[t,s,r]),C=p.useMemo(()=>{var E,P,M;if(!b||!a)return!1;const N=(E=a==null?void 0:a.email)==null?void 0:E.toLowerCase(),k=(M=(P=b.initiator)==null?void 0:P.email)==null?void 0:M.toLowerCase();return N===k},[b,a]),v=p.useMemo(()=>{var k;if(!b)return[];const N=[];return(k=b.initiator)!=null&&k.email&&N.push({email:b.initiator.email.toLowerCase(),participantType:"INITIATOR",name:b.initiator.name}),b.approvalFlow&&Array.isArray(b.approvalFlow)&&b.approvalFlow.forEach(E=>{E.approverEmail&&N.push({email:E.approverEmail.toLowerCase(),participantType:"APPROVER",name:E.approver})}),b.spectators&&Array.isArray(b.spectators)&&b.spectators.forEach(E=>{E.email&&N.push({email:E.email.toLowerCase(),participantType:"SPECTATOR",name:E.name})}),b.participants&&Array.isArray(b.participants)&&b.participants.forEach(E=>{const P=(E.userEmail||E.email||"").toLowerCase(),M=(E.participantType||E.participant_type||"").toUpperCase(),y=E.userName||E.user_name||E.name;P&&M&&!N.find(A=>A.email===P)&&N.push({email:P,participantType:M,name:y})}),N},[b]);return p.useEffect(()=>{if(!t||!r)return;const N=Fr();if(!N){console.warn("[useRequestDetails] Socket not available");return}console.log("[useRequestDetails] Setting up socket listener for request:",r.requestId);const k=E=>{console.log("[useRequestDetails] 📡 Received request:updated event:",E),(E==null?void 0:E.requestId)===r.requestId||(E==null?void 0:E.requestNumber)===t?(console.log("[useRequestDetails] 🔄 Request updated remotely, refreshing silently..."),w()):console.log("[useRequestDetails] ⚠️ Event for different request, ignoring")};return N.on("request:updated",k),console.log("[useRequestDetails] ✅ Registered listener for request:updated"),()=>{console.log("[useRequestDetails] 🧹 Cleaning up socket listener"),N.off("request:updated",k)}},[t,r,w]),{request:b,apiRequest:r,loading:l,refreshing:i,refreshDetails:w,currentApprovalLevel:u,isSpectator:x,isInitiator:C,existingParticipants:v,accessDenied:d}}function Eb(t){return t?t.workflowType==="CLAIM_MANAGEMENT"||t.workflowType==="DEALER_CLAIM"||t.templateType==="claim-management"||t.template==="claim-management"||t.templateType==="dealer-claim"||t.templateName==="Claim Management"||t.templateCode==="CLAIM_MANAGEMENT"||t.templateCode==="DEALER_CLAIM":!1}function Ib(t){return Eb(t)?"DEALER_CLAIM":"CUSTOM"}function t4(t,s){return`/request/${t}`}const nn=[{name:"No Color",value:"transparent",class:"bg-gray-200 border-2 border-gray-400",icon:"×"},{name:"Yellow",value:"#FFEB3B",class:"bg-yellow-400"},{name:"Green",value:"#4CAF50",class:"bg-green-400"},{name:"Blue",value:"#2196F3",class:"bg-blue-400"},{name:"Red",value:"#F44336",class:"bg-red-400"},{name:"Orange",value:"#FF9800",class:"bg-orange-400"},{name:"Purple",value:"#9C27B0",class:"bg-purple-400"},{name:"Pink",value:"#E91E63",class:"bg-pink-400"},{name:"Cyan",value:"#00BCD4",class:"bg-cyan-400"},{name:"Teal",value:"#009688",class:"bg-teal-400"},{name:"Amber",value:"#FFC107",class:"bg-amber-400"},{name:"Indigo",value:"#3F51B5",class:"bg-indigo-400"}];function gu({value:t,onChange:s,placeholder:a="Enter text...",className:r,minHeight:n="120px",...i}){const o=p.useRef(null),[l,c]=p.useState(!1),[d,m]=p.useState(new Set),[u,h]=p.useState(!1),[x,g]=p.useState(null),[f,j]=p.useState("#FFEB3B"),[w,b]=p.useState(!1),[C,v]=p.useState(null),[N,k]=p.useState("#000000");p.useEffect(()=>{o.current&&o.current.innerHTML!==t&&o.current.innerHTML!==t&&(o.current.innerHTML=t||"")},[t]);const E=p.useCallback(S=>(S=S.replace(//g,""),S=S.replace(/]*>[\s\S]*?<\/style>/gi,""),S=S.replace(/]*>[\s\S]*?<\/script>/gi,""),S=S.replace(/]*>/gi,""),S=S.replace(/\s*class="Mso[^"]*"/gi,""),S=S.replace(/\s*class="mso[^"]*"/gi,""),S=S.replace(/\s*style="[^"]*mso-[^"]*"/gi,""),S=S.replace(/\s*style="[^"]*font-family:[^"]*"/gi,""),S=S.replace(/\s*xmlns[^=]*="[^"]*"/gi,""),S=S.replace(/<\/?o:p[^>]*>/gi,""),S=S.replace(/]*>[\s\S]*?<\/v:[^>]*>/gi,""),S=S.replace(/]*\/>/gi,""),S=S.replace(/]*>\s*<\/p>/gi,""),S=S.replace(/]*>\s*<\/div>/gi,""),S=S.replace(/\s+/g," "),S=S.trim(),S),[]),P=p.useCallback(S=>{S.preventDefault();const D=S.clipboardData;let I=D.getData("text/html")||D.getData("text/plain");if((I.includes("/g,"");V.innerHTML=Z,V.removeAttribute("style"),V.removeAttribute("class"),B.appendChild(V)}else if(ae.tagName==="BR")B.appendChild(ae.cloneNode(!0));else{const V=ae.textContent||"";if(V.trim()){const Y=document.createElement("p");Y.textContent=V.trim(),B.appendChild(Y)}}}else if(re.nodeType===Node.TEXT_NODE){const ae=re.textContent||"";if(ae.trim()){const V=document.createElement("p");V.textContent=ae.trim(),B.appendChild(V)}}}),B.childNodes.length===0&&D.getData("text/plain").split(` `).forEach(V=>{if(V.trim()){const Y=document.createElement("p");Y.textContent=V.trim(),B.appendChild(Y)}else B.appendChild(document.createElement("br"))}),F.insertNode(B),F.collapse(!1),_.removeAllRanges(),_.addRange(F),o.current&&s(o.current.innerHTML)},[s,E]),M=p.useCallback(()=>{if(!o.current||!l)return;const S=new Set,D=window.getSelection();if(D&&D.rangeCount>0){const _=D.getRangeAt(0).commonAncestorContainer;let F=null;for(_.nodeType===Node.TEXT_NODE?F=_.parentElement:F=_;F&&F!==o.current;){const G=F.tagName.toLowerCase();(G==="strong"||G==="b")&&S.add("bold"),(G==="em"||G==="i")&&S.add("italic"),G==="u"&&S.add("underline"),G==="h1"&&S.add("h1"),G==="h2"&&S.add("h2"),G==="h3"&&S.add("h3"),G==="ul"&&S.add("ul"),G==="ol"&&S.add("ol");const B=window.getComputedStyle(F);B.textAlign==="center"&&S.add("center"),B.textAlign==="right"&&S.add("right"),B.textAlign==="left"&&S.add("left");const re=Z=>{if(Z.startsWith("#"))return Z.toUpperCase();const U=Z.match(/\d+/g);if(!U||U.length<3)return null;const ee=U[0],ie=U[1],de=U[2];if(!ee||!ie||!de)return null;const Ae=parseInt(ee).toString(16).padStart(2,"0"),We=parseInt(ie).toString(16).padStart(2,"0"),Se=parseInt(de).toString(16).padStart(2,"0");return`#${Ae}${We}${Se}`.toUpperCase()},ae=B.backgroundColor;if(ae&&ae!=="rgba(0, 0, 0, 0)"&&ae!=="transparent"&&ae!=="rgb(255, 255, 255)"&&ae!=="#ffffff"&&ae!=="#FFFFFF"){S.add("highlight");const Z=re(ae);if(Z){const U=nn.find(ee=>ee.value==="transparent"?!1:ee.value.toUpperCase()===Z);g(U?U.value:Z)}}else S.has("highlight")||g(null);const V=B.color,Y=re(V);if(V&&Y&&V!=="rgba(0, 0, 0, 0)"&&Y!=="#000000"){S.add("textColor");const Z=nn.find(U=>U.value==="transparent"?!1:U.value.toUpperCase()===Y);v(Z?Z.value:Y)}else S.has("textColor")||v(Y==="#000000"||!Y?"#000000":null);F=F.parentElement}}m(S)},[l]),y=p.useCallback((S,D)=>{if(!o.current)return;l||o.current.focus();const I=window.getSelection();if(!I||I.rangeCount===0){o.current.focus();return}document.execCommand(S,!1,D),o.current&&s(o.current.innerHTML),setTimeout(M,10)},[l,s,M]),A=p.useCallback(S=>{if(!o.current)return;l||o.current.focus();const D=window.getSelection();if(!D||D.rangeCount===0){o.current.focus();return}let I=!1;if(D.rangeCount>0){const G=D.getRangeAt(0).commonAncestorContainer;let B=null;for(G.nodeType===Node.TEXT_NODE?B=G.parentElement:B=G;B&&B!==o.current;){const ae=window.getComputedStyle(B).backgroundColor;if(ae&&ae!=="rgba(0, 0, 0, 0)"&&ae!=="transparent"&&ae!=="rgb(255, 255, 255)"&&ae!=="#ffffff"&&ae!=="#FFFFFF"){const Y=(Z=>{if(Z.startsWith("#"))return Z.toUpperCase();const U=Z.match(/\d+/g);if(!U||U.length<3)return null;const ee=U[0],ie=U[1],de=U[2];if(!ee||!ie||!de)return null;const Ae=parseInt(ee).toString(16).padStart(2,"0"),We=parseInt(ie).toString(16).padStart(2,"0"),Se=parseInt(de).toString(16).padStart(2,"0");return`#${Ae}${We}${Se}`.toUpperCase()})(ae);if(Y&&Y===S.toUpperCase()){I=!0;break}}B=B.parentElement}}if(S==="transparent"||I){const F=D.getRangeAt(0);if(F.collapsed)document.execCommand("removeFormat",!1);else{const G=F.extractContents(),B=document.createDocumentFragment(),re=ae=>{if(ae.nodeType===Node.TEXT_NODE)return ae.cloneNode(!0);if(ae.nodeType===Node.ELEMENT_NODE){const V=ae,Y=document.createElement(V.tagName.toLowerCase());return Array.from(V.attributes).forEach(Z=>{Z.name!=="style"&&Z.name!=="class"&&Y.setAttribute(Z.name,Z.value)}),Array.from(V.childNodes).forEach(Z=>{const U=re(Z);U&&Y.appendChild(U)}),V.style.backgroundColor&&(Y.style.backgroundColor=""),Y}return null};Array.from(G.childNodes).forEach(ae=>{const V=re(ae);V&&B.appendChild(V)}),F.insertNode(B),document.execCommand("removeFormat",!1)}g(null),j("#FFEB3B")}else if(D.rangeCount>0&&!D.getRangeAt(0).collapsed)document.execCommand("backColor",!1,S),g(S),S!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(S)&&j(S);else return;const _=window.getSelection();_&&_.removeAllRanges(),o.current&&s(o.current.innerHTML),h(!1),setTimeout(()=>{o.current&&o.current.focus(),M()},50)},[l,s,M]),L=p.useCallback(S=>{if(!o.current)return;l||o.current.focus();const D=window.getSelection();if(!D||D.rangeCount===0){o.current.focus();return}let I=!1;if(D.rangeCount>0){const F=D.getRangeAt(0).commonAncestorContainer;let G=null;for(F.nodeType===Node.TEXT_NODE?G=F.parentElement:G=F;G&&G!==o.current;){const re=window.getComputedStyle(G).color;if(re){const V=(Y=>{if(Y.startsWith("#"))return Y.toUpperCase();const Z=Y.match(/\d+/g);if(!Z||Z.length<3)return null;const U=Z[0],ee=Z[1],ie=Z[2];if(!U||!ee||!ie)return null;const de=parseInt(U).toString(16).padStart(2,"0"),Ae=parseInt(ee).toString(16).padStart(2,"0"),We=parseInt(ie).toString(16).padStart(2,"0");return`#${de}${Ae}${We}`.toUpperCase()})(re);if(S==="#000000"){if(V==="#000000"||!V){I=!0;break}}else if(V&&V===S.toUpperCase()){I=!0;break}}G=G.parentElement}}if(S==="transparent"||S==="default"||I){if(S==="#000000"&&I){b(!1);return}document.execCommand("removeFormat",!1),v(null),k("#000000")}else document.execCommand("foreColor",!1,S),v(S),S!=="transparent"&&/^#[0-9A-Fa-f]{6}$/i.test(S)&&k(S);o.current&&s(o.current.innerHTML),b(!1),setTimeout(M,10)},[l,s,M]),K=p.useCallback(()=>{o.current&&s(o.current.innerHTML),M()},[s,M]),O=p.useCallback(S=>{if(S.ctrlKey&&S.key==="b"){S.preventDefault(),y("bold");return}if(S.ctrlKey&&S.key==="i"){S.preventDefault(),y("italic");return}if(S.ctrlKey&&S.key==="u"){S.preventDefault(),y("underline");return}},[y]),$=p.useCallback(()=>{c(!0)},[]),T=p.useCallback(()=>{c(!1),o.current&&s(o.current.innerHTML)},[s]);return p.useEffect(()=>{if(!l)return;const S=()=>{M()};return document.addEventListener("selectionchange",S),()=>{document.removeEventListener("selectionchange",S)}},[l,M]),e.jsxs("div",{className:"relative border border-gray-300 rounded-md bg-white",children:[e.jsxs("div",{className:"flex items-center gap-1 p-2 border-b border-gray-200 bg-gray-50 rounded-t-md flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ge("h-7 w-7 p-0",d.has("bold")&&"bg-blue-100 text-blue-700"),onClick:()=>y("bold"),title:"Bold (Ctrl+B)",children:e.jsx(Sg,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ge("h-7 w-7 p-0",d.has("italic")&&"bg-blue-100 text-blue-700"),onClick:()=>y("italic"),title:"Italic (Ctrl+I)",children:e.jsx(Ag,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ge("h-7 w-7 p-0",d.has("underline")&&"bg-blue-100 text-blue-700"),onClick:()=>y("underline"),title:"Underline (Ctrl+U)",children:e.jsx(kg,{className:"h-4 w-4"})}),e.jsxs($s,{open:u,onOpenChange:h,children:[e.jsx(Bs,{asChild:!0,children:e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ge("h-7 w-7 p-0",d.has("highlight")&&"bg-blue-100 text-blue-700"),title:"Text Highlight",children:e.jsx(Tg,{className:"h-4 w-4"})})}),e.jsx(Us,{className:"w-auto p-2",align:"start",onPointerDownOutside:S=>{S.target.closest("[data-popover-content]")&&S.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:S=>S.stopPropagation(),children:[e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:S=>{S.stopPropagation(),h(!1)},title:"Close",children:e.jsx(ut,{className:"h-4 w-4 text-gray-500"})}),e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-2 pr-6",children:"Highlight Color"}),e.jsx("div",{className:"grid grid-cols-6 gap-1.5 pr-1 mb-2",children:nn.map(S=>{const D=x===S.value,I=S.value==="transparent";return e.jsxs("button",{type:"button",onClick:_=>{_.preventDefault(),_.stopPropagation(),A(D&&!I?"transparent":S.value)},className:ge("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md relative",S.class,D&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",I&&"border-gray-400 bg-white",!I&&!D&&"border-gray-300"),title:D&&!I?`${S.name} (Click to remove)`:S.name,style:I?{}:{backgroundColor:S.value},children:[I&&e.jsx("span",{className:"text-[10px] text-gray-600 font-bold",children:"×"}),D&&!I&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]},S.value)})}),x&&x!=="transparent"&&e.jsx("div",{className:"mb-2",children:e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:S=>{S.stopPropagation(),A("transparent")},title:"Remove highlight color",children:"Remove Highlight"})}),e.jsxs("div",{className:"border-t border-gray-200 pt-2 mt-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-1.5",children:"Custom Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:x&&x!=="transparent"?x:f,onChange:S=>{const D=S.target.value;j(D);const I=window.getSelection();I&&I.rangeCount>0&&!I.getRangeAt(0).collapsed&&A(D)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom color"}),e.jsx("input",{type:"text",value:x&&x!=="transparent"?x:f,onChange:S=>{S.stopPropagation();const D=S.target.value;j(D)},onKeyDown:S=>{if(S.stopPropagation(),S.key==="Enter"){S.preventDefault();const D=S.currentTarget.value.trim();/^#[0-9A-Fa-f]{6}$/i.test(D)&&A(D)}},onPaste:S=>{S.stopPropagation();const D=S.clipboardData.getData("text").trim();S.preventDefault(),setTimeout(()=>{if(/^#[0-9A-Fa-f]{6}$/i.test(D)){j(D);const I=window.getSelection();I&&I.rangeCount>0&&!I.getRangeAt(0).collapsed&&A(D)}else{const I=D.match(/^([0-9A-Fa-f]{6})$/);if(I){const _=`#${I[1]}`;j(_);const F=window.getSelection();F&&F.rangeCount>0&&!F.getRangeAt(0).collapsed&&A(_)}}},0)},onClick:S=>{S.stopPropagation()},onFocus:S=>{S.stopPropagation(),S.target.select()},onBlur:S=>{const D=S.target.value.trim();if(/^#[0-9A-Fa-f]{6}$/i.test(D)){const I=window.getSelection();I&&I.rangeCount>0&&!I.getRangeAt(0).collapsed&&A(D)}else j(D===""?x||"#FFEB3B":D)},placeholder:"#FFEB3B",className:"flex-1 h-7 px-2 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Enter hex color code (Press Enter or click Apply). Supports copy-paste.",autoComplete:"off",spellCheck:"false"}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{const S=f.trim();/^#[0-9A-Fa-f]{6}$/i.test(S)?A(S):j(x||"#FFEB3B")},title:"Apply custom color",children:"Apply"})]})]})]})})]}),e.jsxs($s,{open:w,onOpenChange:b,children:[e.jsx(Bs,{asChild:!0,children:e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ge("h-7 w-7 p-0",d.has("textColor")&&"bg-blue-100 text-blue-700"),title:"Text Color",children:e.jsx(Dg,{className:"h-4 w-4"})})}),e.jsx(Us,{className:"w-auto p-2",align:"start",onPointerDownOutside:S=>{S.target.closest("[data-popover-content]")&&S.preventDefault()},children:e.jsxs("div",{className:"space-y-2 relative",onClick:S=>S.stopPropagation(),children:[e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"absolute top-0 right-0 h-6 w-6 p-0 hover:bg-gray-100",onClick:S=>{S.stopPropagation(),b(!1)},title:"Close",children:e.jsx(ut,{className:"h-4 w-4 text-gray-500"})}),e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-2 pr-6",children:"Text Color"}),e.jsxs("div",{className:"grid grid-cols-6 gap-1.5 pr-1 mb-2",children:[e.jsxs("button",{type:"button",onClick:S=>{S.preventDefault(),S.stopPropagation(),C==="#000000"||!C&&!d.has("textColor")||L("#000000")},className:ge("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center bg-black",(C==="#000000"||!C&&!d.has("textColor"))&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",C!=="#000000"&&(C||d.has("textColor"))&&"border-gray-300"),title:"Default (Black)",children:[e.jsx("span",{className:"text-[10px] text-white font-bold",children:"A"}),(C==="#000000"||!C&&!d.has("textColor"))&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]}),nn.filter(S=>S.value!=="transparent").map(S=>{const D=C===S.value;return e.jsxs("button",{type:"button",onClick:I=>{I.preventDefault(),I.stopPropagation(),L(D?"#000000":S.value)},className:ge("w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:shadow-md flex items-center justify-center relative",D&&"ring-2 ring-blue-600 ring-offset-1 border-blue-600",!D&&"border-gray-300"),title:D?`${S.name} (Click to reset to default)`:S.name,style:{color:S.value,borderColor:D?"#2563eb":S.value},children:[e.jsx("span",{className:"text-xs font-bold",children:"A"}),D&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-white rounded-full shadow-sm"})})]},`text-${S.value}`)})]}),C&&C!=="#000000"&&e.jsx("div",{className:"mb-2",children:e.jsx(R,{type:"button",variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:S=>{S.stopPropagation(),L("#000000")},title:"Reset to default black",children:"Reset to Default"})}),e.jsxs("div",{className:"border-t border-gray-200 pt-2 mt-2",children:[e.jsx("div",{className:"text-xs font-semibold text-gray-700 mb-1.5",children:"Custom Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:C||N,onChange:S=>{const D=S.target.value;k(D),L(D)},className:"w-8 h-8 rounded border border-gray-300 cursor-pointer",title:"Pick a custom text color"}),e.jsx("input",{type:"text",value:C||N,onChange:S=>{const D=S.target.value;k(D)},onKeyDown:S=>{if(S.key==="Enter"){S.preventDefault();const D=S.currentTarget.value;/^#[0-9A-Fa-f]{6}$/.test(D)&&L(D)}},onBlur:S=>{const D=S.target.value;/^#[0-9A-Fa-f]{6}$/.test(D)?L(D):D===""&&k(C||"#000000")},placeholder:"#000000",className:"flex-1 h-7 px-2 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Enter hex color code (Press Enter or click Apply)"}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>L(N),title:"Apply custom text color",children:"Apply"})]})]})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ge("h-7 w-7 p-0",d.has("h1")&&"bg-blue-100 text-blue-700"),onClick:()=>y("formatBlock","

"),title:"Heading 1",children:e.jsx(Rg,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ge("h-7 w-7 p-0",d.has("h2")&&"bg-blue-100 text-blue-700"),onClick:()=>y("formatBlock","

"),title:"Heading 2",children:e.jsx(Pg,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ge("h-7 w-7 p-0",d.has("h3")&&"bg-blue-100 text-blue-700"),onClick:()=>y("formatBlock","

"),title:"Heading 3",children:e.jsx(Eg,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1 border-r border-gray-300 pr-2",children:[e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ge("h-7 w-7 p-0",d.has("ul")&&"bg-blue-100 text-blue-700"),onClick:()=>y("insertUnorderedList"),title:"Bullet List",children:e.jsx(km,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ge("h-7 w-7 p-0",d.has("ol")&&"bg-blue-100 text-blue-700"),onClick:()=>y("insertOrderedList"),title:"Numbered List",children:e.jsx(Ig,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ge("h-7 w-7 p-0",d.has("left")&&"bg-blue-100 text-blue-700"),onClick:()=>y("justifyLeft"),title:"Align Left",children:e.jsx(Mg,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ge("h-7 w-7 p-0",d.has("center")&&"bg-blue-100 text-blue-700"),onClick:()=>y("justifyCenter"),title:"Align Center",children:e.jsx(Fg,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:ge("h-7 w-7 p-0",d.has("right")&&"bg-blue-100 text-blue-700"),onClick:()=>y("justifyRight"),title:"Align Right",children:e.jsx(_g,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:o,contentEditable:!0,onPaste:P,onInput:K,onFocus:$,onBlur:T,onKeyDown:O,onMouseUp:M,onKeyUp:M,"data-placeholder":a,className:ge("w-full rounded-b-md border-0 px-3 py-2 text-base transition-all outline-none","bg-white text-gray-900","min-h-[120px]","overflow-y-auto","overflow-x-auto","md:overflow-x-visible","md:text-sm","empty:before:content-[attr(data-placeholder)] empty:before:text-muted-foreground empty:before:pointer-events-none","focus-visible:outline-none","[&_ul]:list-disc [&_ul]:ml-6 [&_ul]:my-2 [&_ul]:list-outside","[&_ol]:list-decimal [&_ol]:ml-6 [&_ol]:my-2 [&_ol]:list-outside","[&_li]:my-1 [&_li]:pl-2","[&_.table-wrapper]:overflow-x-auto [&_.table-wrapper]:max-w-full [&_.table-wrapper]:my-2","[&_.table-wrapper_table]:border-collapse [&_.table-wrapper_table]:border [&_.table-wrapper_table]:border-gray-300 [&_.table-wrapper_table]:min-w-full","[&_.table-wrapper_table_td]:border [&_.table-wrapper_table_td]:border-gray-300 [&_.table-wrapper_table_td]:px-3 [&_.table-wrapper_table_td]:py-2 [&_.table-wrapper_table_td]:text-sm [&_.table-wrapper_table_td]:whitespace-nowrap","[&_.table-wrapper_table_th]:border [&_.table-wrapper_table_th]:border-gray-300 [&_.table-wrapper_table_th]:px-3 [&_.table-wrapper_table_th]:py-2 [&_.table-wrapper_table_th]:bg-gray-50 [&_.table-wrapper_table_th]:font-semibold [&_.table-wrapper_table_th]:text-sm [&_.table-wrapper_table_th]:text-left [&_.table-wrapper_table_th]:whitespace-nowrap","[&_.table-wrapper_table_tr:nth-child(even)]:bg-gray-50","[&_table]:border-collapse [&_table]:my-2 [&_table]:border [&_table]:border-gray-300 [&_table]:w-full","[&_table_td]:border [&_table_td]:border-gray-300 [&_table_td]:px-3 [&_table_td]:py-2 [&_table_td]:text-sm","[&_table_th]:border [&_table_th]:border-gray-300 [&_table_th]:px-3 [&_table_th]:py-2 [&_table_th]:bg-gray-50 [&_table_th]:font-semibold [&_table_th]:text-sm [&_table_th]:text-left","[&_table_tr:nth-child(even)]:bg-gray-50","[&_p]:my-1 [&_p]:leading-relaxed","[&_strong]:font-bold","[&_em]:italic","[&_u]:underline","[&_span[style*='background']]:px-0.5 [&_span[style*='background']]:rounded","[&_h1]:text-xl [&_h1]:font-bold [&_h1]:my-2","[&_h2]:text-lg [&_h2]:font-semibold [&_h2]:my-2","[&_h3]:text-base [&_h3]:font-semibold [&_h3]:my-1",r),style:{minHeight:n},...i})]})}function ma({content:t,className:s}){const a=p.useMemo(()=>{if(!t)return"";let r=t;const n=/]*>[\s\S]*?<\/table>/gi;return r=r.replace(n,i=>i.includes("table-wrapper")?i:`
${i}
`),r},[t]);return t?e.jsx("div",{className:ge("text-sm text-gray-700 max-w-none","overflow-x-auto","md:overflow-x-visible","[&_ul]:list-disc [&_ul]:ml-6 [&_ul]:my-2 [&_ul]:list-outside","[&_ol]:list-decimal [&_ol]:ml-6 [&_ol]:my-2 [&_ol]:list-outside","[&_li]:my-1 [&_li]:pl-2","[&_.table-wrapper]:overflow-x-auto [&_.table-wrapper]:max-w-full [&_.table-wrapper]:my-2 [&_.table-wrapper]:-mx-2 [&_.table-wrapper]:px-2","[&_.table-wrapper_table]:border-collapse [&_.table-wrapper_table]:border [&_.table-wrapper_table]:border-gray-300 [&_.table-wrapper_table]:min-w-full","[&_.table-wrapper_table_td]:border [&_.table-wrapper_table_td]:border-gray-300 [&_.table-wrapper_table_td]:px-3 [&_.table-wrapper_table_td]:py-2 [&_.table-wrapper_table_td]:text-sm [&_.table-wrapper_table_td]:whitespace-nowrap","[&_.table-wrapper_table_th]:border [&_.table-wrapper_table_th]:border-gray-300 [&_.table-wrapper_table_th]:px-3 [&_.table-wrapper_table_th]:py-2 [&_.table-wrapper_table_th]:bg-gray-50 [&_.table-wrapper_table_th]:font-semibold [&_.table-wrapper_table_th]:text-sm [&_.table-wrapper_table_th]:text-left [&_.table-wrapper_table_th]:whitespace-nowrap","[&_.table-wrapper_table_tr:nth-child(even)]:bg-gray-50","[&_table]:border-collapse [&_table]:my-2 [&_table]:border [&_table]:border-gray-300","[&_table_td]:border [&_table_td]:border-gray-300 [&_table_td]:px-3 [&_table_td]:py-2 [&_table_td]:text-sm","[&_table_th]:border [&_table_th]:border-gray-300 [&_table_th]:px-3 [&_table_th]:py-2 [&_table_th]:bg-gray-50 [&_table_th]:font-semibold [&_table_th]:text-sm [&_table_th]:text-left","[&_table_tr:nth-child(even)]:bg-gray-50","[&_p]:my-1 [&_p]:leading-relaxed","[&_strong]:font-bold","[&_em]:italic","[&_u]:underline","[&_h1]:text-xl [&_h1]:font-bold [&_h1]:my-2","[&_h2]:text-lg [&_h2]:font-semibold [&_h2]:my-2","[&_h3]:text-base [&_h3]:font-semibold [&_h3]:my-1",s),dangerouslySetInnerHTML:{__html:a}}):null}var fu={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Pn,function(){var a=1e3,r=6e4,n=36e5,i="millisecond",o="second",l="minute",c="hour",d="day",m="week",u="month",h="quarter",x="year",g="date",f="Invalid Date",j=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,w=/\[([^\]]+)]|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,b={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(O){var $=["th","st","nd","rd"],T=O%100;return"["+O+($[(T-20)%10]||$[T]||$[0])+"]"}},C=function(O,$,T){var S=String(O);return!S||S.length>=$?O:""+Array($+1-S.length).join(T)+O},v={s:C,z:function(O){var $=-O.utcOffset(),T=Math.abs($),S=Math.floor(T/60),D=T%60;return($<=0?"+":"-")+C(S,2,"0")+":"+C(D,2,"0")},m:function O($,T){if($.date()1)return O(_[0])}else{var F=$.name;k[F]=$,D=F}return!S&&D&&(N=D),D||!S&&N},y=function(O,$){if(P(O))return O.clone();var T=typeof $=="object"?$:{};return T.date=O,T.args=arguments,new L(T)},A=v;A.l=M,A.i=P,A.w=function(O,$){return y(O,{locale:$.$L,utc:$.$u,x:$.$x,$offset:$.$offset})};var L=function(){function O(T){this.$L=M(T.locale,null,!0),this.parse(T),this.$x=this.$x||T.x||{},this[E]=!0}var $=O.prototype;return $.parse=function(T){this.$d=function(S){var D=S.date,I=S.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 _=D.match(j);if(_){var F=_[2]-1||0,G=(_[7]||"0").substring(0,3);return I?new Date(Date.UTC(_[1],F,_[3]||1,_[4]||0,_[5]||0,_[6]||0,G)):new Date(_[1],F,_[3]||1,_[4]||0,_[5]||0,_[6]||0,G)}}return new Date(D)}(T),this.init()},$.init=function(){var T=this.$d;this.$y=T.getFullYear(),this.$M=T.getMonth(),this.$D=T.getDate(),this.$W=T.getDay(),this.$H=T.getHours(),this.$m=T.getMinutes(),this.$s=T.getSeconds(),this.$ms=T.getMilliseconds()},$.$utils=function(){return A},$.isValid=function(){return this.$d.toString()!==f},$.isSame=function(T,S){var D=y(T);return this.startOf(S)<=D&&D<=this.endOf(S)},$.isAfter=function(T,S){return y(T)0,k<=N.r||!N.r){k<=1&&v>0&&(N=b[v-1]);var E=w[N.l];x&&(k=x(""+k)),f=typeof E=="string"?E.replace("%d",k):E(k,m,N.l,j);break}}if(m)return f;var P=j?w.future:w.past;return typeof P=="function"?P(f):P.replace("%s",f)},i.to=function(d,m){return l(d,m,this,!0)},i.from=function(d,m){return l(d,m,this)};var c=function(d){return d.$u?n.utc():n()};i.toNow=function(d){return this.to(c(this),d)},i.fromNow=function(d){return this.from(c(this),d)}}})})(yu);var Fb=yu.exports;const _b=En(Fb);kt.extend(_b);function Lb({request:t,isInitiator:s,needsClosure:a,conclusionRemark:r,setConclusionRemark:n,conclusionLoading:i,conclusionSubmitting:o,aiGenerated:l,handleGenerateConclusion:c,handleFinalizeConclusion:d,onPause:m,onResume:u,onRetrigger:h,currentUserIsApprover:x=!1,pausedByUserId:g,currentUserId:f}){var E,P,M,y,A,L,K,O;const{user:j}=Gt(),w=t==null?void 0:t.pauseInfo,b=(w==null?void 0:w.isPaused)||!1,C=(E=w==null?void 0:w.pausedBy)==null?void 0:E.userId,v=(j==null?void 0:j.userId)||"",N=b&&u&&(x||s),k=b&&s&&C&&C!==v&&h;return e.jsxs("div",{className:"space-y-4 sm:space-y-6","data-testid":"overview-tab-content",children:[e.jsxs(X,{"data-testid":"initiator-card",children:[e.jsx(le,{className:"pb-3 sm:pb-4",children:e.jsxs(ce,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(St,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Initiator"]})}),e.jsx(J,{children:e.jsxs("div",{className:"flex items-start gap-3 sm:gap-4",children:[e.jsx(Bt,{className:"h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0",children:e.jsx(Ut,{className:"bg-gray-700 text-white font-semibold text-sm",children:((P=t.initiator)==null?void 0:P.avatar)||"U"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:((M=t.initiator)==null?void 0:M.name)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 truncate",children:((y=t.initiator)==null?void 0:y.role)||"N/A"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 truncate",children:((A=t.initiator)==null?void 0:A.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(aa,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:((L=t.initiator)==null?void 0:L.email)||"N/A"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs sm:text-sm text-gray-600",children:[e.jsx(Mn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{children:((K=t.initiator)==null?void 0:K.phone)||"N/A"})]})]})]})]})})]}),e.jsxs(X,{"data-testid":"request-details-card",children:[e.jsx(le,{className:"pb-3 sm:pb-4",children:e.jsxs(ce,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ee,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Details"]})}),e.jsxs(J,{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs sm:text-sm font-medium text-gray-700 block mb-2",children:"Description"}),e.jsx("div",{className:"bg-gray-50 rounded-lg p-3 sm:p-4 border border-gray-300",children:e.jsx(ma,{content:t.description||"",className:"text-xs sm:text-sm"})})]}),(t.category||t.subcategory)&&e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t border-gray-300",children:[t.category&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Category"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.category})]}),t.subcategory&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Subcategory"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.subcategory})]})]}),t.amount&&e.jsxs("div",{className:"pt-4 border-t border-gray-300",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Amount"}),e.jsx("p",{className:"text-lg font-bold text-gray-900 mt-1",children:t.amount})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t border-gray-300",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Created"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:Qt(t.createdAt)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Last Updated"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:Qt(t.updatedAt)})]})]})]})]}),b&&w&&e.jsxs(X,{className:"border-orange-300 bg-orange-50/50","data-testid":"pause-status-card",children:[e.jsx(le,{className:"pb-3 sm:pb-4",children:e.jsxs(ce,{className:"flex items-center gap-2 text-sm sm:text-base text-orange-800",children:[e.jsx(ha,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Workflow Paused"]})}),e.jsxs(J,{className:"space-y-3 sm:space-y-4",children:[e.jsx("div",{className:"bg-white rounded-lg p-3 sm:p-4 border border-orange-200",children:e.jsxs("div",{className:"space-y-2 sm:space-y-3",children:[w.pauseReason&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Reason"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:w.pauseReason})]}),w.pausedBy&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused By"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:w.pausedBy.name||w.pausedBy.email})]}),w.pauseResumeDate&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Auto-Resume Date"}),e.jsxs("p",{className:"text-sm text-gray-900 mt-1",children:[Qt(w.pauseResumeDate),kt(w.pauseResumeDate).isAfter(kt())&&e.jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",kt(w.pauseResumeDate).fromNow(),")"]})]})]}),w.pausedAt&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:"Paused At"}),e.jsx("p",{className:"text-sm text-gray-900 mt-1",children:Qt(w.pausedAt)})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 border-t border-orange-200",children:[N&&u&&e.jsxs(R,{onClick:u,className:"bg-green-600 hover:bg-green-700 text-white text-xs sm:text-sm h-8 sm:h-9",size:"sm",children:[e.jsx(Nn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Resume Now"]}),k&&h&&e.jsxs(R,{onClick:h,variant:"outline",className:"border-orange-300 text-orange-700 hover:bg-orange-50 text-xs sm:text-sm h-8 sm:h-9",size:"sm",children:[e.jsx(Ie,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5"}),"Request Resume"]})]})]})]}),t.claimDetails&&e.jsxs(X,{children:[e.jsx(le,{className:"pb-4",children:e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ee,{className:"w-5 h-5 text-purple-600"}),"Claim Management Details"]})}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.activityName||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Type"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.activityType||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Location"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.location||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Date"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.activityDate?hu(t.claimDetails.activityDate):"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Code"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.dealerCode||"N/A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.claimDetails.dealerName||"N/A"})]})]}),t.claimDetails.requestDescription&&e.jsxs("div",{className:"pt-4 border-t border-gray-300",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Request Description"}),e.jsx("div",{className:"mt-2 bg-gray-50 p-3 rounded-lg",children:e.jsx(ma,{content:t.claimDetails.requestDescription,className:"text-sm"})})]})]})]}),t.status==="closed"&&t.conclusionRemark&&e.jsxs(X,{children:[e.jsxs(le,{className:"bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200",children:[e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ce,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(je,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(J,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(ma,{content:t.conclusionRemark||"",className:"text-sm"})}),t.closureDate&&e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs text-gray-500 border-t border-gray-200 pt-3",children:[e.jsxs("span",{children:["Request closed on ",Qt(t.closureDate)]}),e.jsxs("span",{children:["By ",((O=t.initiator)==null?void 0:O.name)||"Initiator"]})]})]})]}),a&&e.jsxs(X,{"data-testid":"conclusion-remark-card",children:[e.jsx(le,{className:`bg-gradient-to-r border-b ${t.status==="rejected"?"from-red-50 to-rose-50 border-red-200":"from-green-50 to-emerald-50 border-green-200"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(ce,{className:`flex items-center gap-2 text-base sm:text-lg ${t.status==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx(Ce,{className:`w-5 h-5 ${t.status==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(je,{className:"mt-1 text-xs sm:text-sm",children:t.status==="rejected"?"This request was rejected. Please review the AI-generated closure remark and finalize it to close this request.":"All approvals are complete. Please review and finalize the conclusion to close this request."})]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:c,disabled:i,className:"gap-2 shrink-0","data-testid":"generate-ai-conclusion-button",children:[e.jsx(Zt,{className:`w-3.5 h-3.5 ${i?"animate-spin":""}`}),l?"Regenerate":"Generate with AI"]})]})}),e.jsx(J,{className:"pt-4",children:i?e.jsx("div",{className:"flex items-center justify-center py-8","data-testid":"conclusion-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Je,{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(gu,{value:r,onChange:$=>n($),placeholder:"Enter a professional conclusion remark summarizing the request outcome, key decisions, and approvals...",className:"text-sm",minHeight:"160px","data-testid":"conclusion-remark-textarea"}),e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"This will be the final summary for this request"}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":"character-count",children:[r?r.replace(/<[^>]*>/g,"").length:0," / 2000 characters"]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-blue-900 mb-1.5",children:"Finalizing this request will:"}),e.jsxs("ul",{className:"text-xs sm:text-sm text-blue-800 space-y-0.5 pl-4",children:[e.jsx("li",{className:"list-disc",children:'Change request status to "CLOSED"'}),e.jsx("li",{className:"list-disc",children:"Notify all participants of closure"}),e.jsx("li",{className:"list-disc",children:"Move request to Closed Requests"}),e.jsx("li",{className:"list-disc",children:"Save conclusion remark permanently"})]})]}),e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(R,{onClick:d,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(Je,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function xn({delayDuration:t=0,...s}){return e.jsx(Rx,{"data-slot":"tooltip-provider",delayDuration:t,...s})}function ci({...t}){return e.jsx(xn,{children:e.jsx(Px,{"data-slot":"tooltip",...t})})}function di({...t}){return e.jsx(Ex,{"data-slot":"tooltip-trigger",...t})}function mi({className:t,sideOffset:s=0,children:a,...r}){return e.jsx(Ix,{children:e.jsxs(Mx,{"data-slot":"tooltip-content",sideOffset:s,className:ge("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(Fx,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function nt({...t}){return e.jsx(Ox,{"data-slot":"dialog",...t})}function Ob({...t}){return e.jsx(Lx,{"data-slot":"dialog-portal",...t})}const bu=p.forwardRef(({className:t,...s},a)=>e.jsx(um,{ref:a,"data-slot":"dialog-overlay",className:ge("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}));bu.displayName=um.displayName;const tt=p.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(Ob,{"data-slot":"dialog-portal",children:[e.jsx(bu,{}),e.jsxs(hm,{ref:r,"data-slot":"dialog-content",className:ge("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(_x,{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(ut,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));tt.displayName=hm.displayName;const it=p.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-header",className:ge("flex flex-col gap-2 text-center sm:text-left",t),...s}));it.displayName="DialogHeader";const Nt=p.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,"data-slot":"dialog-footer",className:ge("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...s}));Nt.displayName="DialogFooter";const st=p.forwardRef(({className:t,...s},a)=>e.jsx(pm,{ref:a,"data-slot":"dialog-title",className:ge("text-lg leading-none font-semibold",t),...s}));st.displayName=pm.displayName;const Mt=p.forwardRef(({className:t,...s},a)=>e.jsx(xm,{ref:a,"data-slot":"dialog-description",className:ge("text-muted-foreground text-sm",t),...s}));Mt.displayName=xm.displayName;function ns({className:t,...s}){return e.jsx("textarea",{"data-slot":"textarea",className:ge("resize-none border-gray-400 placeholder:text-muted-foreground bg-white text-gray-900 flex field-sizing-content min-h-16 w-full rounded-md border px-3 py-2 text-base transition-all outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","hover:border-gray-500","focus-visible:border-re-light-green focus-visible:ring-0 focus-visible:outline-none","aria-invalid:ring-destructive/20 aria-invalid:border-destructive",t),...s})}const Tc=t=>{if(t<8)return Et(t);const a=Math.floor(t/8),r=t%8;return r>0?`${a}d ${Et(r)}`:`${a}d`},$b=(t,s)=>{if(s)return e.jsx(Ie,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"});switch(t){case"approved":return e.jsx(Ce,{className:"w-4 h-4 sm:w-5 sm:w-5 text-green-600"});case"rejected":return e.jsx(yt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-red-600"});case"paused":return e.jsx(Pm,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-600"});case"pending":case"in-review":return e.jsx(He,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"});case"waiting":return e.jsx(He,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"});default:return e.jsx(He,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}};function Bb({step:t,index:s,approval:a,isCurrentUser:r=!1,isInitiator:n=!1,isCurrentLevel:i=!1,onSkipApprover:o,onRefresh:l,testId:c="approval-step"}){const{user:d}=Gt(),[m,u]=p.useState(!1),[h,x]=p.useState(""),[g,f]=p.useState(!1),j=(a==null?void 0:a.breachReason)||(t==null?void 0:t.breachReason)||"";p.useEffect(()=>{m||x("")},[m]);const w=t.status==="pending"||t.status==="in-review",b=t.status==="approved",C=t.status==="rejected",v=t.status==="waiting",N=t.status==="paused",k=Number(t.tatHours||0),E=t.actualHours??0,P=b&&E?Math.max(0,k-E):0,M=k>0?E/k*100:0,y=M>=100,A=(d==null?void 0:d.role)==="ADMIN",L=Un(d),K=t.approverId===(d==null?void 0:d.userId),O=A||L||K,$=async()=>{var T,S;if(!h.trim()){ne.error("Breach Reason Required",{description:"Please enter a reason for the breach."});return}f(!0);try{await nb(t.levelId,h.trim()),u(!1),x(""),ne.success("Breach Reason Updated",{description:"The breach reason has been saved and will appear in the TAT Breach Report.",duration:5e3}),l?await l():setTimeout(()=>{window.location.reload()},1e3)}catch(D){console.error("Error updating breach reason:",D);const I=((S=(T=D==null?void 0:D.response)==null?void 0:T.data)==null?void 0:S.error)||(D==null?void 0:D.message)||"Failed to update breach reason. Please try again.";ne.error("Failed to Update Breach Reason",{description:I,duration:5e3})}finally{f(!1)}};return e.jsxs("div",{className:`relative p-3 sm:p-4 md:p-5 rounded-lg border-2 transition-all ${t.isSkipped?"border-orange-500 bg-orange-50":w?"border-blue-500 bg-blue-50 shadow-md":b?"border-green-500 bg-green-50":C?"border-red-500 bg-red-50":v?"border-gray-300 bg-gray-50":"border-gray-200 bg-white"}`,"data-testid":`${c}-${t.step}`,children:[e.jsxs("div",{className:"flex items-start gap-2 sm:gap-3 md:gap-4",children:[e.jsx("div",{className:`p-2 sm:p-2.5 md:p-3 rounded-xl flex-shrink-0 ${t.isSkipped?"bg-orange-100":N?"bg-yellow-100":w?"bg-blue-100":b?"bg-green-100":C?"bg-red-100":v?"bg-gray-200":"bg-gray-100"}`,children:$b(t.status,t.isSkipped)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2 sm:gap-4 mb-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs("h4",{className:"font-semibold text-gray-900 text-base sm:text-lg","data-testid":`${c}-approver-label`,children:["Approver ",s+1]}),e.jsx(se,{variant:"outline",className:`text-xs shrink-0 capitalize ${t.isSkipped?"bg-orange-100 text-orange-800 border-orange-200":w?"bg-yellow-100 text-yellow-800 border-yellow-200":b?"bg-green-100 text-green-800 border-green-200":C?"bg-red-100 text-red-800 border-red-200":v?"bg-gray-200 text-gray-600 border-gray-300":"bg-gray-100 text-gray-800 border-gray-200"}`,"data-testid":`${c}-status-badge`,children:t.isSkipped?"skipped":t.status}),t.isSkipped&&t.skipReason&&e.jsx(xn,{delayDuration:200,children:e.jsxs(ci,{children:[e.jsx(di,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity",onClick:T=>T.stopPropagation(),children:e.jsx(Ie,{className:"w-4 h-4 text-orange-600"})})}),e.jsxs(mi,{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(cc,{className:"w-3 h-3"}),"Skip Reason:"]}),e.jsx("p",{className:"text-xs text-gray-700",children:t.skipReason})]})]})}),b&&E&&e.jsx(se,{className:"bg-green-600 text-white text-xs","data-testid":`${c}-completion-time`,children:Tc(E)})]}),e.jsx("p",{className:"text-sm font-semibold text-gray-900","data-testid":`${c}-approver-name`,children:r?e.jsx("span",{className:"text-blue-600",children:"You"}):t.approver}),e.jsx("p",{className:"text-xs text-gray-600","data-testid":`${c}-role`,children:t.role})]}),e.jsxs("div",{className:"text-left sm:text-right flex-shrink-0",children:[e.jsx("p",{className:"text-xs text-gray-500 font-medium",children:"Turnaround Time (TAT)"}),e.jsxs("p",{className:"text-lg font-bold text-gray-900","data-testid":`${c}-tat-hours`,children:[k," hours"]})]})]}),b&&E!==void 0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Completed:"}),e.jsx("span",{className:"font-medium text-gray-900",children:t.timestamp?Qt(t.timestamp):"N/A"})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Completed in:"}),e.jsx("span",{className:"font-medium text-gray-900",children:Tc(E)})]}),e.jsx("div",{className:"space-y-2",children:(()=>{const T=Math.min(100,M),S=()=>y?"bg-red-600":M>=75?"bg-orange-500":M>=50?"bg-amber-500":"bg-green-600",D=()=>y?"text-red-600":M>=75?"text-orange-600":M>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(Gs,{value:T,className:"h-2 bg-gray-200",indicatorClassName:S(),"data-testid":`${c}-progress-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`font-semibold ${D()}`,children:[Math.round(T),"% of TAT used"]}),y&&O&&e.jsx(xn,{children:e.jsxs(ci,{children:[e.jsx(di,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{x(j),u(!0)},children:e.jsx(an,{className:"w-3 h-3"})})}),e.jsx(mi,{children:e.jsx("p",{children:j?"Edit breach reason":"Add breach reason"})})]})})]}),P>0&&e.jsxs("span",{className:"text-green-600 font-semibold",children:["Saved ",Et(P)]})]})]})})()}),y&&j&&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(an,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:j})]}),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(Ps,{className:"w-3.5 h-3.5 text-blue-600"}),"Conclusion Remark:"]}),e.jsx("p",{className:"text-sm text-gray-700 italic leading-relaxed",children:t.comment})]})]}),i&&(w||N)&&(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?Ks(a.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${N?"bg-gray-100 border-gray-300":(a.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(a.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(a.sla.percentageUsed||0)>=50?"bg-amber-50 border-amber-200":"bg-green-50 border-green-200"}`,children:[e.jsxs("p",{className:"text-xs font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",N&&"(Paused)"]}),e.jsxs("div",{className:"space-y-2 text-xs mb-3",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time elapsed since assigned:"}),e.jsx("span",{className:"font-medium text-gray-900",children:a.sla.elapsedText})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time used:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[a.sla.elapsedText," / ",Et(k)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const T=a.sla.percentageUsed||0,S=()=>N?"bg-gray-500":T>=100?"bg-red-600":T>=75?"bg-orange-500":T>=50?"bg-amber-500":"bg-green-600",D=()=>N?"text-gray-600":T>=100?"text-red-600":T>=75?"text-orange-600":T>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(Gs,{value:a.sla.percentageUsed,className:"h-3",indicatorClassName:S(),"data-testid":`${c}-sla-progress`}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`text-xs font-semibold ${D()}`,children:["Progress: ",Math.min(100,a.sla.percentageUsed),"% of TAT used"]}),a.sla.status==="breached"&&O&&e.jsx(xn,{children:e.jsxs(ci,{children:[e.jsx(di,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",onClick:()=>{x(j),u(!0)},children:e.jsx(an,{className:"w-3 h-3"})})}),e.jsx(mi,{children:e.jsx("p",{children:j?"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($i,{className:"w-4 h-4"}),"Deadline Breached"]}),j&&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(an,{className:"w-3.5 h-3.5"}),"Breach Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed whitespace-pre-line",children:j})]})]}),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"]})]})]})]}),v&&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(Pm,{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 ",k," hours for approval"]})]})}),C&&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(yt,{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(cc,{className:"w-3.5 h-3.5"}),"Skip Reason:"]}),e.jsx("p",{className:"text-sm text-gray-700 leading-relaxed",children:t.skipReason}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Skipped on ",Qt(t.timestamp)]})]}),t.tatAlerts&&t.tatAlerts.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 space-y-2",children:t.tatAlerts.map((T,S)=>{var D,I,_,F,G,B;return e.jsx("div",{className:`p-2 sm:p-3 rounded-lg border ${T.isBreached?"bg-red-50 border-red-200":(T.thresholdPercentage||0)===75?"bg-orange-50 border-orange-200":"bg-yellow-50 border-yellow-200"}`,"data-testid":`${c}-tat-alert-${S}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[(T.thresholdPercentage||0)===50&&e.jsx(Lg,{className:"w-5 h-5 text-yellow-600"}),(T.thresholdPercentage||0)===75&&e.jsx(as,{className:"w-5 h-5 text-orange-600"}),(T.thresholdPercentage||0)===100&&e.jsx($i,{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 ",S+1," - ",T.thresholdPercentage||0,"% TAT"]}),e.jsx(se,{variant:"outline",className:`text-[10px] sm:text-xs shrink-0 ${T.isBreached?"bg-red-100 text-red-800 border-red-300":"bg-amber-100 text-amber-800 border-amber-300"}`,children:T.isBreached?"BREACHED":"WARNING"})]}),e.jsxs("p",{className:"text-[10px] sm:text-xs md:text-sm text-gray-700 mt-1",children:[T.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:Et(Number(T.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:[Et(Number(T.tatHoursElapsed||0)),((D=T.metadata)==null?void 0:D.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(T.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 ${(T.tatHoursRemaining||0)<2?"text-red-600":"text-gray-900"}`,children:[Et(Number(T.tatHoursRemaining||0)),((I=T.metadata)==null?void 0:I.tatTestMode)&&e.jsxs("span",{className:"text-purple-600 ml-1",children:["(",(Number(T.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:T.expectedCompletionTime?Ks(T.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"}),(((_=T.metadata)==null?void 0:_.testMode)||((F=T.metadata)==null?void 0:F.tatTestMode))&&e.jsx(se,{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: ",T.alertSentAt?Qt(T.alertSentAt):"N/A"]}),(((G=T.metadata)==null?void 0:G.testMode)||((B=T.metadata)==null?void 0:B.tatTestMode))&&e.jsx("p",{className:"text-[10px] text-purple-600 mt-1 italic",children:"Note: Test mode active (1 hour = 1 minute)"})]})]})]})},S)})}),t.timestamp&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[b?"Approved":C?"Rejected":"Actioned"," on ",Qt(t.timestamp)]}),n&&!N&&(w||t.status==="pending")&&!b&&!C&&t.levelId&&o&&e.jsxs("div",{className:"mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-200",children:[e.jsxs(R,{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:()=>o({levelId:t.levelId,approverName:t.approver,levelNumber:t.step}),"data-testid":`${c}-skip-button`,children:[e.jsx(Ie,{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:N?"Skip this approver to resume the workflow and move to next level":"Skip if approver is unavailable and move to next level"})]})]})]}),e.jsx(nt,{open:m,onOpenChange:u,children:e.jsxs(tt,{className:"sm:max-w-[500px]",children:[e.jsxs(it,{children:[e.jsx(st,{children:j?"Edit Breach Reason":"Add Breach Reason"}),e.jsx(Mt,{children:j?"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(ns,{placeholder:"Enter the reason for the breach...",value:h,onChange:T=>x(T.target.value),className:"min-h-[100px]",maxLength:500}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[h.length,"/500 characters"]})]}),e.jsxs(Nt,{children:[e.jsx(R,{variant:"outline",onClick:()=>{u(!1),x("")},disabled:g,children:"Cancel"}),e.jsx(R,{onClick:$,disabled:!h.trim()||g,className:"bg-red-600 hover:bg-red-700",children:g?"Saving...":"Save Reason"})]})]})})]})}function Ub({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){return e.jsxs(X,{children:[e.jsx(le,{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(ce,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Zs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Approval Workflow"]}),e.jsx(je,{className:"mt-1 sm:mt-2 text-xs sm:text-sm",children:"Track the approval progress through each step"})]}),t.totalSteps&&(()=>{var x;const i=t.totalSteps||1,o=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,l=((x=t.approvalFlow)==null?void 0:x.filter(g=>{const f=(g.status||"").toLowerCase();return f==="approved"||f==="rejected"}).length)||0,c=l>=i,d=(t.status||"").toLowerCase(),m=d==="approved"||d==="rejected"||d==="closed",u=o>i,h=Math.min(Math.max(1,o),i);return u?e.jsxs(se,{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"]}):m||c?e.jsxs(se,{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(se,{variant:"outline",className:"font-medium text-xs sm:text-sm shrink-0",children:["Step ",h," of ",i," - ",l," completed"]})})()]})}),e.jsx(J,{children:t.approvalFlow&&t.approvalFlow.length>0?e.jsx("div",{className:"space-y-4 sm:space-y-6",children:t.approvalFlow.map((i,o)=>{var x,g,f;const l=(x=t.approvals)==null?void 0:x.find(j=>j.levelId===i.levelId),c=(g=s==null?void 0:s.email)==null?void 0:g.toLowerCase(),d=(f=i.approverEmail)==null?void 0:f.toLowerCase(),m=c&&d&&c===d,u=t.currentStepRaw!==void 0?t.currentStepRaw:t.currentStep||1,h=i.step===u;return e.jsx(Bb,{step:i,index:o,approval:l,isCurrentUser:m,isInitiator:a,isCurrentLevel:h,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 _o=p.createContext({});function Lo(t){const s=p.useRef(null);return s.current===null&&(s.current=t()),s.current}const Oo=typeof window<"u",vu=Oo?p.useLayoutEffect:p.useEffect,zn=p.createContext(null);function $o(t,s){t.indexOf(s)===-1&&t.push(s)}function Bo(t,s){const a=t.indexOf(s);a>-1&&t.splice(a,1)}const ra=(t,s,a)=>a>s?s:a{};const na={},ju=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Nu(t){return typeof t=="object"&&t!==null}const wu=t=>/^0[^.\s]+$/u.test(t);function Vo(t){let s;return()=>(s===void 0&&(s=t()),s)}const Ds=t=>t,Vb=(t,s)=>a=>s(t(a)),Kr=(...t)=>t.reduce(Vb),Lr=(t,s,a)=>{const r=s-t;return r===0?1:(a-t)/r};class zo{constructor(){this.subscriptions=[]}add(s){return $o(this.subscriptions,s),()=>Bo(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;it*1e3,Ts=t=>t/1e3;function Cu(t,s){return s?t*(1e3/s):0}const Su=(t,s,a)=>(((1-3*a+3*s)*t+(3*a-6*s))*t+3*s)*t,zb=1e-7,Hb=12;function Wb(t,s,a,r,n){let i,o,l=0;do o=s+(a-s)/2,i=Su(o,r,n)-t,i>0?a=o:s=o;while(Math.abs(i)>zb&&++lWb(i,0,1,t,a);return i=>i===0||i===1?i:Su(n(i),s,r)}const Au=t=>s=>s<=.5?t(2*s)/2:(2-t(2*(1-s)))/2,ku=t=>s=>1-t(1-s),Tu=Yr(.33,1.53,.69,.99),Ho=ku(Tu),Du=Au(Ho),Ru=t=>(t*=2)<1?.5*Ho(t):.5*(2-Math.pow(2,-10*(t-1))),Wo=t=>1-Math.sin(Math.acos(t)),Pu=ku(Wo),Eu=Au(Wo),Gb=Yr(.42,0,1,1),Kb=Yr(0,0,.58,1),Iu=Yr(.42,0,.58,1),Yb=t=>Array.isArray(t)&&typeof t[0]!="number",Mu=t=>Array.isArray(t)&&typeof t[0]=="number",Zb={linear:Ds,easeIn:Gb,easeInOut:Iu,easeOut:Kb,circIn:Wo,circInOut:Eu,circOut:Pu,backIn:Ho,backInOut:Du,backOut:Tu,anticipate:Ru},Xb=t=>typeof t=="string",Dc=t=>{if(Mu(t)){Uo(t.length===4);const[s,a,r,n]=t;return Yr(s,a,r,n)}else if(Xb(t))return Zb[t];return t},on=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Jb(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(m){o.has(m)&&(d.schedule(m),t()),m(l)}const d={schedule:(m,u=!1,h=!1)=>{const g=h&&n?a:r;return u&&o.add(m),g.has(m)||g.add(m),m},cancel:m=>{r.delete(m),o.delete(m)},process:m=>{if(l=m,n){i=!0;return}n=!0,[a,r]=[r,a],a.forEach(c),a.clear(),n=!1,i&&(i=!1,d.process(m))}};return d}const Qb=40;function Fu(t,s){let a=!1,r=!0;const n={delta:0,timestamp:0,isProcessing:!1},i=()=>a=!0,o=on.reduce((C,v)=>(C[v]=Jb(i),C),{}),{setup:l,read:c,resolveKeyframes:d,preUpdate:m,update:u,preRender:h,render:x,postRender:g}=o,f=()=>{const C=na.useManualTiming?n.timestamp:performance.now();a=!1,na.useManualTiming||(n.delta=r?1e3/60:Math.max(Math.min(C-n.timestamp,Qb),1)),n.timestamp=C,n.isProcessing=!0,l.process(n),c.process(n),d.process(n),m.process(n),u.process(n),h.process(n),x.process(n),g.process(n),n.isProcessing=!1,a&&s&&(r=!1,t(f))},j=()=>{a=!0,r=!0,n.isProcessing||t(f)};return{schedule:on.reduce((C,v)=>{const N=o[v];return C[v]=(k,E=!1,P=!1)=>(a||j(),N.schedule(k,E,P)),C},{}),cancel:C=>{for(let v=0;v(gn===void 0&&fs.set(Jt.isProcessing||na.useManualTiming?Jt.timestamp:performance.now()),gn),set:t=>{gn=t,queueMicrotask(qb)}},_u=t=>s=>typeof s=="string"&&s.startsWith(t),Go=_u("--"),ev=_u("var(--"),Ko=t=>ev(t)?tv.test(t.split("/*")[0].trim()):!1,tv=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,rr={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Or={...rr,transform:t=>ra(0,1,t)},ln={...rr,default:1},Ar=t=>Math.round(t*1e5)/1e5,Yo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function sv(t){return t==null}const av=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Zo=(t,s)=>a=>!!(typeof a=="string"&&av.test(a)&&a.startsWith(t)||s&&!sv(a)&&Object.prototype.hasOwnProperty.call(a,s)),Lu=(t,s,a)=>r=>{if(typeof r!="string")return r;const[n,i,o,l]=r.match(Yo);return{[t]:parseFloat(n),[s]:parseFloat(i),[a]:parseFloat(o),alpha:l!==void 0?parseFloat(l):1}},rv=t=>ra(0,255,t),hi={...rr,transform:t=>Math.round(rv(t))},Ea={test:Zo("rgb","red"),parse:Lu("red","green","blue"),transform:({red:t,green:s,blue:a,alpha:r=1})=>"rgba("+hi.transform(t)+", "+hi.transform(s)+", "+hi.transform(a)+", "+Ar(Or.transform(r))+")"};function nv(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 Ki={test:Zo("#"),parse:nv,transform:Ea.transform},Zr=t=>({test:s=>typeof s=="string"&&s.endsWith(t)&&s.split(" ").length===1,parse:parseFloat,transform:s=>`${s}${t}`}),ca=Zr("deg"),zs=Zr("%"),Fe=Zr("px"),iv=Zr("vh"),ov=Zr("vw"),Rc={...zs,parse:t=>zs.parse(t)/100,transform:t=>zs.transform(t*100)},za={test:Zo("hsl","hue"),parse:Lu("hue","saturation","lightness"),transform:({hue:t,saturation:s,lightness:a,alpha:r=1})=>"hsla("+Math.round(t)+", "+zs.transform(Ar(s))+", "+zs.transform(Ar(a))+", "+Ar(Or.transform(r))+")"},Ot={test:t=>Ea.test(t)||Ki.test(t)||za.test(t),parse:t=>Ea.test(t)?Ea.parse(t):za.test(t)?za.parse(t):Ki.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Ea.transform(t):za.transform(t),getAnimatableNone:t=>{const s=Ot.parse(t);return s.alpha=0,Ot.transform(s)}},lv=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function cv(t){var s,a;return isNaN(t)&&typeof t=="string"&&(((s=t.match(Yo))==null?void 0:s.length)||0)+(((a=t.match(lv))==null?void 0:a.length)||0)>0}const Ou="number",$u="color",dv="var",mv="var(",Pc="${}",uv=/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 $r(t){const s=t.toString(),a=[],r={color:[],number:[],var:[]},n=[];let i=0;const l=s.replace(uv,c=>(Ot.test(c)?(r.color.push(i),n.push($u),a.push(Ot.parse(c))):c.startsWith(mv)?(r.var.push(i),n.push(dv),a.push(c)):(r.number.push(i),n.push(Ou),a.push(parseFloat(c))),++i,Pc)).split(Pc);return{values:a,split:l,indexes:r,types:n}}function Bu(t){return $r(t).values}function Uu(t){const{split:s,types:a}=$r(t),r=s.length;return n=>{let i="";for(let o=0;otypeof t=="number"?0:Ot.test(t)?Ot.getAnimatableNone(t):t;function pv(t){const s=Bu(t);return Uu(t)(s.map(hv))}const ga={test:cv,parse:Bu,createTransformer:Uu,getAnimatableNone:pv};function pi(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 xv({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=pi(c,l,t+1/3),i=pi(c,l,t),o=pi(c,l,t-1/3)}return{red:Math.round(n*255),green:Math.round(i*255),blue:Math.round(o*255),alpha:r}}function Cn(t,s){return a=>a>0?s:t}const Tt=(t,s,a)=>t+(s-t)*a,xi=(t,s,a)=>{const r=t*t,n=a*(s*s-r)+r;return n<0?0:Math.sqrt(n)},gv=[Ki,Ea,za],fv=t=>gv.find(s=>s.test(t));function Ec(t){const s=fv(t);if(!s)return!1;let a=s.parse(t);return s===za&&(a=xv(a)),a}const Ic=(t,s)=>{const a=Ec(t),r=Ec(s);if(!a||!r)return Cn(t,s);const n={...a};return i=>(n.red=xi(a.red,r.red,i),n.green=xi(a.green,r.green,i),n.blue=xi(a.blue,r.blue,i),n.alpha=Tt(a.alpha,r.alpha,i),Ea.transform(n))},Yi=new Set(["none","hidden"]);function yv(t,s){return Yi.has(t)?a=>a<=0?t:s:a=>a>=1?s:t}function bv(t,s){return a=>Tt(t,s,a)}function Xo(t){return typeof t=="number"?bv:typeof t=="string"?Ko(t)?Cn:Ot.test(t)?Ic:Nv:Array.isArray(t)?Vu:typeof t=="object"?Ot.test(t)?Ic:vv:Cn}function Vu(t,s){const a=[...t],r=a.length,n=t.map((i,o)=>Xo(i)(i,s[o]));return i=>{for(let o=0;o{for(const i in r)a[i]=r[i](n);return a}}function jv(t,s){const a=[],r={color:0,var:0,number:0};for(let n=0;n{const a=ga.createTransformer(s),r=$r(t),n=$r(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?Yi.has(t)&&!n.values.length||Yi.has(s)&&!r.values.length?yv(t,s):Kr(Vu(jv(r,n),n.values),a):Cn(t,s)};function zu(t,s,a){return typeof t=="number"&&typeof s=="number"&&typeof a=="number"?Tt(t,s,a):Xo(t)(t,s)}const wv=t=>{const s=({timestamp:a})=>t(a);return{start:(a=!0)=>At.update(s,a),stop:()=>xa(s),now:()=>Jt.isProcessing?Jt.timestamp:fs.now()}},Hu=(t,s,a=10)=>{let r="";const n=Math.max(Math.round(s/a),2);for(let i=0;i=Sn?1/0:s}function Cv(t,s=100,a){const r=a({...t,keyframes:[0,s]}),n=Math.min(Jo(r),Sn);return{type:"keyframes",ease:i=>r.next(n*i).value/s,duration:Ts(n)}}const Sv=5;function Wu(t,s,a){const r=Math.max(s-Sv,0);return Cu(a-t(r),s-r)}const Rt={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},gi=.001;function Av({duration:t=Rt.duration,bounce:s=Rt.bounce,velocity:a=Rt.velocity,mass:r=Rt.mass}){let n,i,o=1-s;o=ra(Rt.minDamping,Rt.maxDamping,o),t=ra(Rt.minDuration,Rt.maxDuration,Ts(t)),o<1?(n=d=>{const m=d*o,u=m*t,h=m-a,x=Zi(d,o),g=Math.exp(-u);return gi-h/x*g},i=d=>{const u=d*o*t,h=u*a+a,x=Math.pow(o,2)*Math.pow(d,2)*t,g=Math.exp(-u),f=Zi(Math.pow(d,2),o);return(-n(d)+gi>0?-1:1)*((h-x)*g)/f}):(n=d=>{const m=Math.exp(-d*t),u=(d-a)*t+1;return-gi+m*u},i=d=>{const m=Math.exp(-d*t),u=(a-d)*(t*t);return m*u});const l=5/t,c=Tv(n,i,l);if(t=Vs(t),isNaN(c))return{stiffness:Rt.stiffness,damping:Rt.damping,duration:t};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:o*2*Math.sqrt(r*d),duration:t}}}const kv=12;function Tv(t,s,a){let r=a;for(let n=1;nt[a]!==void 0)}function Pv(t){let s={velocity:Rt.velocity,stiffness:Rt.stiffness,damping:Rt.damping,mass:Rt.mass,isResolvedFromDuration:!1,...t};if(!Mc(t,Rv)&&Mc(t,Dv))if(t.visualDuration){const a=t.visualDuration,r=2*Math.PI/(a*1.2),n=r*r,i=2*ra(.05,1,1-(t.bounce||0))*Math.sqrt(n);s={...s,mass:Rt.mass,stiffness:n,damping:i}}else{const a=Av(t);s={...s,...a,mass:Rt.mass},s.isResolvedFromDuration=!0}return s}function An(t=Rt.visualDuration,s=Rt.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:d,mass:m,duration:u,velocity:h,isResolvedFromDuration:x}=Pv({...a,velocity:-Ts(a.velocity||0)}),g=h||0,f=d/(2*Math.sqrt(c*m)),j=o-i,w=Ts(Math.sqrt(c/m)),b=Math.abs(j)<5;r||(r=b?Rt.restSpeed.granular:Rt.restSpeed.default),n||(n=b?Rt.restDelta.granular:Rt.restDelta.default);let C;if(f<1){const N=Zi(w,f);C=k=>{const E=Math.exp(-f*w*k);return o-E*((g+f*w*j)/N*Math.sin(N*k)+j*Math.cos(N*k))}}else if(f===1)C=N=>o-Math.exp(-w*N)*(j+(g+w*j)*N);else{const N=w*Math.sqrt(f*f-1);C=k=>{const E=Math.exp(-f*w*k),P=Math.min(N*k,300);return o-E*((g+f*w*j)*Math.sinh(P)+N*j*Math.cosh(P))/N}}const v={calculatedDuration:x&&u||null,next:N=>{const k=C(N);if(x)l.done=N>=u;else{let E=N===0?g:0;f<1&&(E=N===0?Vs(g):Wu(C,N,k));const P=Math.abs(E)<=r,M=Math.abs(o-k)<=n;l.done=P&&M}return l.value=l.done?o:k,l},toString:()=>{const N=Math.min(Jo(v),Sn),k=Hu(E=>v.next(N*E).value,N,30);return N+"ms "+k},toTransition:()=>{}};return v}An.applyToOptions=t=>{const s=Cv(t,100,An);return t.ease=s.ease,t.duration=Vs(s.duration),t.type="keyframes",t};function Xi({keyframes:t,velocity:s=0,power:a=.8,timeConstant:r=325,bounceDamping:n=10,bounceStiffness:i=500,modifyTarget:o,min:l,max:c,restDelta:d=.5,restSpeed:m}){const u=t[0],h={done:!1,value:u},x=P=>l!==void 0&&Pc,g=P=>l===void 0?c:c===void 0||Math.abs(l-P)-f*Math.exp(-P/r),C=P=>w+b(P),v=P=>{const M=b(P),y=C(P);h.done=Math.abs(M)<=d,h.value=h.done?w:y};let N,k;const E=P=>{x(h.value)&&(N=P,k=An({keyframes:[h.value,g(h.value)],velocity:Wu(C,P,h.value),damping:n,stiffness:i,restDelta:d,restSpeed:m}))};return E(0),{calculatedDuration:null,next:P=>{let M=!1;return!k&&N===void 0&&(M=!0,v(P),E(P)),N!==void 0&&P>=N?k.next(P-N):(!M&&v(P),h)}}}function Ev(t,s,a){const r=[],n=a||na.mix||zu,i=t.length-1;for(let o=0;os[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=Ev(s,r,n),c=l.length,d=m=>{if(o&&m1)for(;ud(ra(t[0],t[i-1],m)):d}function Mv(t,s){const a=t[t.length-1];for(let r=1;r<=s;r++){const n=Lr(0,s,r);t.push(Tt(a,1,n))}}function Fv(t){const s=[0];return Mv(s,t.length-1),s}function _v(t,s){return t.map(a=>a*s)}function Lv(t,s){return t.map(()=>s||Iu).splice(0,t.length-1)}function kr({duration:t=300,keyframes:s,times:a,ease:r="easeInOut"}){const n=Yb(r)?r.map(Dc):Dc(r),i={done:!1,value:s[0]},o=_v(a&&a.length===s.length?a:Fv(s),t),l=Iv(o,s,{ease:Array.isArray(n)?n:Lv(s,n)});return{calculatedDuration:t,next:c=>(i.value=l(c),i.done=c>=t,i)}}const Ov=t=>t!==null;function Qo(t,{repeat:s,repeatType:a="loop"},r,n=1){const i=t.filter(Ov),l=n<0||s&&a!=="loop"&&s%2===1?0:i.length-1;return!l||r===void 0?i[l]:r}const $v={decay:Xi,inertia:Xi,tween:kr,keyframes:kr,spring:An};function Gu(t){typeof t.type=="string"&&(t.type=$v[t.type])}class qo{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 Bv=t=>t/100;class el extends qo{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!==fs.now()&&this.tick(fs.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;Gu(s);const{type:a=kr,repeat:r=0,repeatDelay:n=0,repeatType:i,velocity:o=0}=s;let{keyframes:l}=s;const c=a||kr;c!==kr&&typeof l[0]!="number"&&(this.mixKeyframes=Kr(Bv,zu(l[0],l[1])),l=[0,100]);const d=c({...s,keyframes:l});i==="mirror"&&(this.mirroredGenerator=c({...s,keyframes:[...l].reverse(),velocity:-o})),d.calculatedDuration===null&&(d.calculatedDuration=Jo(d));const{calculatedDuration:m}=d;this.calculatedDuration=m,this.resolvedDuration=m+n,this.totalDuration=this.resolvedDuration*(r+1)-n,this.generator=d}updateTime(s){const a=Math.round(s-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=a}tick(s,a=!1){const{generator:r,totalDuration:n,mixKeyframes:i,mirroredGenerator:o,resolvedDuration:l,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:m,repeat:u,repeatType:h,repeatDelay:x,type:g,onUpdate:f,finalKeyframe:j}=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 w=this.currentTime-d*(this.playbackSpeed>=0?1:-1),b=this.playbackSpeed>=0?w<0:w>n;this.currentTime=Math.max(w,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=n);let C=this.currentTime,v=r;if(u){const P=Math.min(this.currentTime,n)/l;let M=Math.floor(P),y=P%1;!y&&P>=1&&(y=1),y===1&&M--,M=Math.min(M,u+1),!!(M%2)&&(h==="reverse"?(y=1-y,x&&(y-=x/l)):h==="mirror"&&(v=o)),C=ra(0,1,y)*l}const N=b?{done:!1,value:m[0]}:v.next(C);i&&(N.value=i(N.value));let{done:k}=N;!b&&c!==null&&(k=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const E=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&k);return E&&g!==Xi&&(N.value=Qo(m,this.options,j,this.speed)),f&&f(N.value),E&&this.finish(),N}then(s,a){return this.finished.then(s,a)}get duration(){return Ts(this.calculatedDuration)}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+Ts(s)}get time(){return Ts(this.currentTime)}set time(s){var a;s=Vs(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(fs.now());const a=this.playbackSpeed!==s;this.playbackSpeed=s,a&&(this.time=Ts(this.currentTime))}play(){var n,i;if(this.isStopped)return;const{driver:s=wv,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(fs.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 Uv(t){for(let s=1;st*180/Math.PI,Ji=t=>{const s=Ia(Math.atan2(t[1],t[0]));return Qi(s)},Vv={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Ji,rotateZ:Ji,skewX:t=>Ia(Math.atan(t[1])),skewY:t=>Ia(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Qi=t=>(t=t%360,t<0&&(t+=360),t),Fc=Ji,_c=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Lc=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),zv={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:_c,scaleY:Lc,scale:t=>(_c(t)+Lc(t))/2,rotateX:t=>Qi(Ia(Math.atan2(t[6],t[5]))),rotateY:t=>Qi(Ia(Math.atan2(-t[2],t[0]))),rotateZ:Fc,rotate:Fc,skewX:t=>Ia(Math.atan(t[4])),skewY:t=>Ia(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function qi(t){return t.includes("scale")?1:0}function eo(t,s){if(!t||t==="none")return qi(s);const a=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,n;if(a)r=zv,n=a;else{const l=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=Vv,n=l}if(!n)return qi(s);const i=r[s],o=n[1].split(",").map(Wv);return typeof i=="function"?i(o):o[i]}const Hv=(t,s)=>{const{transform:a="none"}=getComputedStyle(t);return eo(a,s)};function Wv(t){return parseFloat(t.trim())}const nr=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],ir=new Set(nr),Oc=t=>t===rr||t===Fe,Gv=new Set(["x","y","z"]),Kv=nr.filter(t=>!Gv.has(t));function Yv(t){const s=[];return Kv.forEach(a=>{const r=t.getValue(a);r!==void 0&&(s.push([a,r.get()]),r.set(a.startsWith("scale")?1:0))}),s}const Ma={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})=>eo(s,"x"),y:(t,{transform:s})=>eo(s,"y")};Ma.translateX=Ma.x;Ma.translateY=Ma.y;const Fa=new Set;let to=!1,so=!1,ao=!1;function Ku(){if(so){const t=Array.from(Fa).filter(r=>r.needsMeasurement),s=new Set(t.map(r=>r.element)),a=new Map;s.forEach(r=>{const n=Yv(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)})}so=!1,to=!1,Fa.forEach(t=>t.complete(ao)),Fa.clear()}function Yu(){Fa.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(so=!0)})}function Zv(){ao=!0,Yu(),Ku(),ao=!1}class tl{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?(Fa.add(this),to||(to=!0,At.read(Yu),At.resolveKeyframes(Ku))):(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])}Uv(s)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(s=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,s),Fa.delete(this)}cancel(){this.state==="scheduled"&&(Fa.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Xv=t=>t.startsWith("--");function Jv(t,s,a){Xv(s)?t.style.setProperty(s,a):t.style[s]=a}const Qv=Vo(()=>window.ScrollTimeline!==void 0),qv={};function ej(t,s){const a=Vo(t);return()=>qv[s]??a()}const Zu=ej(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Cr=([t,s,a,r])=>`cubic-bezier(${t}, ${s}, ${a}, ${r})`,$c={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Cr([0,.65,.55,1]),circOut:Cr([.55,0,1,.45]),backIn:Cr([.31,.01,.66,-.59]),backOut:Cr([.33,1.53,.69,.99])};function Xu(t,s){if(t)return typeof t=="function"?Zu()?Hu(t,s):"ease-out":Mu(t)?Cr(t):Array.isArray(t)?t.map(a=>Xu(a,s)||$c.easeOut):$c[t]}function tj(t,s,a,{delay:r=0,duration:n=300,repeat:i=0,repeatType:o="loop",ease:l="easeOut",times:c}={},d=void 0){const m={[s]:a};c&&(m.offset=c);const u=Xu(l,n);Array.isArray(u)&&(m.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 d&&(h.pseudoElement=d),t.animate(m,h)}function Ju(t){return typeof t=="function"&&"applyToOptions"in t}function sj({type:t,...s}){return Ju(t)&&Zu()?t.applyToOptions(s):(s.duration??(s.duration=300),s.ease??(s.ease="easeOut"),s)}class aj extends qo{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,Uo(typeof s.type!="string");const d=sj(s);this.animation=tj(a,r,n,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const m=Qo(n,this.options,l,this.speed);this.updateMotionValue?this.updateMotionValue(m):Jv(a,r,m),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var s,a;(a=(s=this.animation).finish)==null||a.call(s)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:s}=this;s==="idle"||s==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var s,a;this.isPseudoElement||(a=(s=this.animation).commitStyles)==null||a.call(s)}get duration(){var a,r;const s=((r=(a=this.animation.effect)==null?void 0:a.getComputedTiming)==null?void 0:r.call(a).duration)||0;return Ts(Number(s))}get iterationDuration(){const{delay:s=0}=this.options||{};return this.duration+Ts(s)}get time(){return Ts(Number(this.animation.currentTime)||0)}set time(s){this.finishedTime=null,this.animation.currentTime=Vs(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&&Qv()?(this.animation.timeline=s,Ds):a(this)}}const Qu={anticipate:Ru,backInOut:Du,circInOut:Eu};function rj(t){return t in Qu}function nj(t){typeof t.ease=="string"&&rj(t.ease)&&(t.ease=Qu[t.ease])}const Bc=10;class ij extends aj{constructor(s){nj(s),Gu(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 el({...o,autoplay:!1}),c=Vs(this.finishedTime??this.time);a.setWithVelocity(l.sample(c-Bc).value,l.sample(c).value,Bc),l.stop()}}const Uc=(t,s)=>s==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(ga.test(t)||t==="0")&&!t.startsWith("url("));function oj(t){const s=t[0];if(t.length===1)return!0;for(let a=0;aObject.hasOwnProperty.call(Element.prototype,"animate"));function mj(t){var m;const{motionValue:s,name:a,repeatDelay:r,repeatType:n,damping:i,type:o}=t;if(!(((m=s==null?void 0:s.owner)==null?void 0:m.current)instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:d}=s.owner.getProps();return dj()&&a&&cj.has(a)&&(a!=="transform"||!d)&&!c&&!r&&n!=="mirror"&&i!==0&&o!=="inertia"}const uj=40;class hj extends qo{constructor({autoplay:s=!0,delay:a=0,type:r="keyframes",repeat:n=0,repeatDelay:i=0,repeatType:o="loop",keyframes:l,name:c,motionValue:d,element:m,...u}){var g;super(),this.stop=()=>{var f,j;this._animation&&(this._animation.stop(),(f=this.stopTimeline)==null||f.call(this)),(j=this.keyframeResolver)==null||j.cancel()},this.createdAt=fs.now();const h={autoplay:s,delay:a,type:r,repeat:n,repeatDelay:i,repeatType:o,name:c,motionValue:d,element:m,...u},x=(m==null?void 0:m.KeyframeResolver)||tl;this.keyframeResolver=new x(l,(f,j,w)=>this.onKeyframesResolved(f,j,h,!w),c,d,m),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(s,a,r,n){this.keyframeResolver=void 0;const{name:i,type:o,velocity:l,delay:c,isHandoff:d,onUpdate:m}=r;this.resolvedAt=fs.now(),lj(s,i,o,l)||((na.instantAnimations||!c)&&(m==null||m(Qo(s,r,a))),s[0]=s[s.length-1],ro(r),r.repeat=0);const h={startTime:n?this.resolvedAt?this.resolvedAt-this.createdAt>uj?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:a,...r,keyframes:s},x=!d&&mj(h)?new ij({...h,element:h.motionValue.owner.current}):new el(h);x.finished.then(()=>this.notifyFinished()).catch(Ds),this.pendingTimeline&&(this.stopTimeline=x.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=x}get finished(){return this._animation?this.animation.finished:this._finished}then(s,a){return this.finished.finally(s).then(()=>{})}get animation(){var s;return this._animation||((s=this.keyframeResolver)==null||s.resume(),Zv()),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 pj=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function xj(t){const s=pj.exec(t);if(!s)return[,];const[,a,r,n]=s;return[`--${a??r}`,n]}function qu(t,s,a=1){const[r,n]=xj(t);if(!r)return;const i=window.getComputedStyle(s).getPropertyValue(r);if(i){const o=i.trim();return ju(o)?parseFloat(o):o}return Ko(n)?qu(n,s,a+1):n}function sl(t,s){return(t==null?void 0:t[s])??(t==null?void 0:t.default)??t}const eh=new Set(["width","height","top","left","right","bottom",...nr]),gj={test:t=>t==="auto",parse:t=>t},th=t=>s=>s.test(t),sh=[rr,Fe,zs,ca,ov,iv,gj],Vc=t=>sh.find(th(t));function fj(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||wu(t):!0}const yj=new Set(["brightness","contrast","saturate","opacity"]);function bj(t){const[s,a]=t.slice(0,-1).split("(");if(s==="drop-shadow")return t;const[r]=a.match(Yo)||[];if(!r)return t;const n=a.replace(r,"");let i=yj.has(s)?1:0;return r!==a&&(i*=100),s+"("+i+n+")"}const vj=/\b([a-z-]*)\(.*?\)/gu,no={...ga,getAnimatableNone:t=>{const s=t.match(vj);return s?s.map(bj).join(" "):t}},zc={...rr,transform:Math.round},jj={rotate:ca,rotateX:ca,rotateY:ca,rotateZ:ca,scale:ln,scaleX:ln,scaleY:ln,scaleZ:ln,skew:ca,skewX:ca,skewY:ca,distance:Fe,translateX:Fe,translateY:Fe,translateZ:Fe,x:Fe,y:Fe,z:Fe,perspective:Fe,transformPerspective:Fe,opacity:Or,originX:Rc,originY:Rc,originZ:Fe},al={borderWidth:Fe,borderTopWidth:Fe,borderRightWidth:Fe,borderBottomWidth:Fe,borderLeftWidth:Fe,borderRadius:Fe,radius:Fe,borderTopLeftRadius:Fe,borderTopRightRadius:Fe,borderBottomRightRadius:Fe,borderBottomLeftRadius:Fe,width:Fe,maxWidth:Fe,height:Fe,maxHeight:Fe,top:Fe,right:Fe,bottom:Fe,left:Fe,padding:Fe,paddingTop:Fe,paddingRight:Fe,paddingBottom:Fe,paddingLeft:Fe,margin:Fe,marginTop:Fe,marginRight:Fe,marginBottom:Fe,marginLeft:Fe,backgroundPositionX:Fe,backgroundPositionY:Fe,...jj,zIndex:zc,fillOpacity:Or,strokeOpacity:Or,numOctaves:zc},Nj={...al,color:Ot,backgroundColor:Ot,outlineColor:Ot,fill:Ot,stroke:Ot,borderColor:Ot,borderTopColor:Ot,borderRightColor:Ot,borderBottomColor:Ot,borderLeftColor:Ot,filter:no,WebkitFilter:no},ah=t=>Nj[t];function rh(t,s){let a=ah(t);return a!==no&&(a=ga),a.getAnimatableNone?a.getAnimatableNone(s):void 0}const wj=new Set(["auto","none","0"]);function Cj(t,s,a){let r=0,n;for(;r{s.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function Aj(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 nh=(t,s)=>s&&typeof t=="number"?s.transform(t):t;function ih(t){return Nu(t)&&"offsetHeight"in t}const Hc=30,kj=t=>!isNaN(parseFloat(t));class Tj{constructor(s,a={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const n=fs.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=fs.now(),this.canTrackVelocity===null&&s!==void 0&&(this.canTrackVelocity=kj(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 zo);const r=this.events[s].add(a);return s==="change"?()=>{r(),At.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=fs.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||s-this.updatedAt>Hc)return 0;const a=Math.min(this.updatedAt-this.prevUpdatedAt,Hc);return Cu(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 Ja(t,s){return new Tj(t,s)}const{schedule:rl}=Fu(queueMicrotask,!1),Fs={x:!1,y:!1};function oh(){return Fs.x||Fs.y}function Dj(t){return t==="x"||t==="y"?Fs[t]?null:(Fs[t]=!0,()=>{Fs[t]=!1}):Fs.x||Fs.y?null:(Fs.x=Fs.y=!0,()=>{Fs.x=Fs.y=!1})}function lh(t,s){const a=Aj(t),r=new AbortController,n={passive:!0,...s,signal:r.signal};return[a,n,()=>r.abort()]}function Wc(t){return!(t.pointerType==="touch"||oh())}function Rj(t,s,a={}){const[r,n,i]=lh(t,a),o=l=>{if(!Wc(l))return;const{target:c}=l,d=s(c,l);if(typeof d!="function"||!c)return;const m=u=>{Wc(u)&&(d(u),c.removeEventListener("pointerleave",m))};c.addEventListener("pointerleave",m,n)};return r.forEach(l=>{l.addEventListener("pointerenter",o,n)}),i}const ch=(t,s)=>s?t===s?!0:ch(t,s.parentElement):!1,nl=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Pj=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Ej(t){return Pj.has(t.tagName)||t.tabIndex!==-1}const fn=new WeakSet;function Gc(t){return s=>{s.key==="Enter"&&t(s)}}function fi(t,s){t.dispatchEvent(new PointerEvent("pointer"+s,{isPrimary:!0,bubbles:!0}))}const Ij=(t,s)=>{const a=t.currentTarget;if(!a)return;const r=Gc(()=>{if(fn.has(a))return;fi(a,"down");const n=Gc(()=>{fi(a,"up")}),i=()=>fi(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 Kc(t){return nl(t)&&!oh()}function Mj(t,s,a={}){const[r,n,i]=lh(t,a),o=l=>{const c=l.currentTarget;if(!Kc(l))return;fn.add(c);const d=s(c,l),m=(x,g)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",h),fn.has(c)&&fn.delete(c),Kc(x)&&typeof d=="function"&&d(x,{success:g})},u=x=>{m(x,c===window||c===document||a.useGlobalTarget||ch(c,x.target))},h=x=>{m(x,!1)};window.addEventListener("pointerup",u,n),window.addEventListener("pointercancel",h,n)};return r.forEach(l=>{(a.useGlobalTarget?window:l).addEventListener("pointerdown",o,n),ih(l)&&(l.addEventListener("focus",d=>Ij(d,n)),!Ej(l)&&!l.hasAttribute("tabindex")&&(l.tabIndex=0))}),i}function dh(t){return Nu(t)&&"ownerSVGElement"in t}function Fj(t){return dh(t)&&t.tagName==="svg"}const ts=t=>!!(t&&t.getVelocity),_j=[...sh,Ot,ga],Lj=t=>_j.find(th(t)),il=p.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function Yc(t,s){if(typeof t=="function")return t(s);t!=null&&(t.current=s)}function Oj(...t){return s=>{let a=!1;const r=t.map(n=>{const i=Yc(n,s);return!a&&typeof i=="function"&&(a=!0),i});if(a)return()=>{for(let n=0;n{const{width:d,height:m,top:u,left:h,right:x}=o.current;if(s||!i.current||!d||!m)return;const g=a==="left"?`left: ${h}`:`right: ${x}`;i.current.dataset.motionPopId=n;const f=document.createElement("style");l&&(f.nonce=l);const j=r??document.head;return j.appendChild(f),f.sheet&&f.sheet.insertRule(` [data-motion-pop-id="${n}"] { position: absolute !important; width: ${d}px !important; height: ${m}px !important; ${g}px !important; top: ${u}px !important; } `),()=>{j.contains(f)&&j.removeChild(f)}},[s]),e.jsx(Bj,{isPresent:s,childRef:i,sizeRef:o,children:p.cloneElement(t,{ref:c})})}const Vj=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:o,anchorX:l,root:c})=>{const d=Lo(zj),m=p.useId();let u=!0,h=p.useMemo(()=>(u=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:x=>{d.set(x,!0);for(const g of d.values())if(!g)return;r&&r()},register:x=>(d.set(x,!1),()=>d.delete(x))}),[a,d,r]);return i&&u&&(h={...h}),p.useMemo(()=>{d.forEach((x,g)=>d.set(g,!1))},[a]),p.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),o==="popLayout"&&(t=e.jsx(Uj,{isPresent:a,anchorX:l,root:c,children:t})),e.jsx(zn.Provider,{value:h,children:t})};function zj(){return new Map}function mh(t=!0){const s=p.useContext(zn);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=p.useId();p.useEffect(()=>{if(t)return n(i)},[t]);const o=p.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,o]:[!0]}const cn=t=>t.key||"";function Zc(t){const s=[];return p.Children.forEach(t,a=>{p.isValidElement(a)&&s.push(a)}),s}const Hn=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:o=!1,anchorX:l="left",root:c})=>{const[d,m]=mh(o),u=p.useMemo(()=>Zc(t),[t]),h=o&&!d?[]:u.map(cn),x=p.useRef(!0),g=p.useRef(u),f=Lo(()=>new Map),[j,w]=p.useState(u),[b,C]=p.useState(u);vu(()=>{x.current=!1,g.current=u;for(let k=0;k{const E=cn(k),P=o&&!d?!1:u===b||h.includes(E),M=()=>{if(f.has(E))f.set(E,!0);else return;let y=!0;f.forEach(A=>{A||(y=!1)}),y&&(N==null||N(),C(g.current),o&&(m==null||m()),r&&r())};return e.jsx(Vj,{isPresent:P,initial:!x.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:P?void 0:M,anchorX:l,children:k},E)})})},uh=p.createContext({strict:!1}),Xc={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"]},Qa={};for(const t in Xc)Qa[t]={isEnabled:s=>Xc[t].some(a=>!!s[a])};function Hj(t){for(const s in t)Qa[s]={...Qa[s],...t[s]}}const Wj=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 kn(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Wj.has(t)}let hh=t=>!kn(t);function Gj(t){typeof t=="function"&&(hh=s=>s.startsWith("on")?!kn(s):t(s))}try{Gj(require("@emotion/is-prop-valid").default)}catch{}function Kj(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(hh(n)||a===!0&&kn(n)||!s&&!kn(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Wn=p.createContext({});function Gn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Br(t){return typeof t=="string"||Array.isArray(t)}const ol=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ll=["initial",...ol];function Kn(t){return Gn(t.animate)||ll.some(s=>Br(t[s]))}function ph(t){return!!(Kn(t)||t.variants)}function Yj(t,s){if(Kn(t)){const{initial:a,animate:r}=t;return{initial:a===!1||Br(a)?a:void 0,animate:Br(r)?r:void 0}}return t.inherit!==!1?s:{}}function Zj(t){const{initial:s,animate:a}=Yj(t,p.useContext(Wn));return p.useMemo(()=>({initial:s,animate:a}),[Jc(s),Jc(a)])}function Jc(t){return Array.isArray(t)?t.join(" "):t}const Ur={};function Xj(t){for(const s in t)Ur[s]=t[s],Go(s)&&(Ur[s].isCSSVariable=!0)}function xh(t,{layout:s,layoutId:a}){return ir.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!Ur[t]||t==="opacity")}const Jj={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Qj=nr.length;function qj(t,s,a){let r="",n=!0;for(let i=0;i({style:{},transform:{},transformOrigin:{},vars:{}});function gh(t,s,a){for(const r in s)!ts(s[r])&&!xh(r,a)&&(t[r]=s[r])}function eN({transformTemplate:t},s){return p.useMemo(()=>{const a=dl();return cl(a,s,t),Object.assign({},a.vars,a.style)},[s])}function tN(t,s){const a=t.style||{},r={};return gh(r,a,t),Object.assign(r,eN(t,s)),r}function sN(t,s){const a={},r=tN(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 aN={offset:"stroke-dashoffset",array:"stroke-dasharray"},rN={offset:"strokeDashoffset",array:"strokeDasharray"};function nN(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?aN:rN;t[i.offset]=Fe.transform(-r);const o=Fe.transform(s),l=Fe.transform(a);t[i.array]=`${o} ${l}`}function fh(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:o=0,...l},c,d,m){if(cl(t,l,d),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=(m==null?void 0:m.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&&nN(u,n,i,o,!1)}const yh=()=>({...dl(),attrs:{}}),bh=t=>typeof t=="string"&&t.toLowerCase()==="svg";function iN(t,s,a,r){const n=p.useMemo(()=>{const i=yh();return fh(i,s,bh(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};gh(i,t.style,t),n.style={...i,...n.style}}return n}const oN=["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 ml(t){return typeof t!="string"||t.includes("-")?!1:!!(oN.indexOf(t)>-1||/[A-Z]/u.test(t))}function lN(t,s,a,{latestValues:r},n,i=!1){const l=(ml(t)?iN:sN)(s,r,n,t),c=Kj(s,typeof t=="string",i),d=t!==p.Fragment?{...c,...l,ref:a}:{},{children:m}=s,u=p.useMemo(()=>ts(m)?m.get():m,[m]);return p.createElement(t,{...d,children:u})}function Qc(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function ul(t,s,a,r){if(typeof s=="function"){const[n,i]=Qc(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]=Qc(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function yn(t){return ts(t)?t.get():t}function cN({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:dN(a,r,n,t),renderState:s()}}function dN(t,s,a,r){const n={},i=r(t,{});for(const h in i)n[h]=yn(i[h]);let{initial:o,animate:l}=t;const c=Kn(t),d=ph(t);s&&d&&!c&&t.inherit!==!1&&(o===void 0&&(o=s.initial),l===void 0&&(l=s.animate));let m=a?a.initial===!1:!1;m=m||o===!1;const u=m?l:o;if(u&&typeof u!="boolean"&&!Gn(u)){const h=Array.isArray(u)?u:[u];for(let x=0;x(s,a)=>{const r=p.useContext(Wn),n=p.useContext(zn),i=()=>cN(t,s,r,n);return a?i():Lo(i)};function hl(t,s,a){var i;const{style:r}=t,n={};for(const o in r)(ts(r[o])||s.style&&ts(s.style[o])||xh(o,t)||((i=a==null?void 0:a.getValue(o))==null?void 0:i.liveStyle)!==void 0)&&(n[o]=r[o]);return n}const mN=vh({scrapeMotionValuesFromProps:hl,createRenderState:dl});function jh(t,s,a){const r=hl(t,s,a);for(const n in t)if(ts(t[n])||ts(s[n])){const i=nr.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const uN=vh({scrapeMotionValuesFromProps:jh,createRenderState:yh}),hN=Symbol.for("motionComponentSymbol");function Ha(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function pN(t,s,a){return p.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):Ha(a)&&(a.current=r))},[s])}const pl=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),xN="framerAppearId",Nh="data-"+pl(xN),wh=p.createContext({});function gN(t,s,a,r,n){var f,j;const{visualElement:i}=p.useContext(Wn),o=p.useContext(uh),l=p.useContext(zn),c=p.useContext(il).reducedMotion,d=p.useRef(null);r=r||o.renderer,!d.current&&r&&(d.current=r(t,{visualState:s,parent:i,props:a,presenceContext:l,blockInitialAnimation:l?l.initial===!1:!1,reducedMotionConfig:c}));const m=d.current,u=p.useContext(wh);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&fN(d.current,a,n,u);const h=p.useRef(!1);p.useInsertionEffect(()=>{m&&h.current&&m.update(a,l)});const x=a[Nh],g=p.useRef(!!x&&!((f=window.MotionHandoffIsComplete)!=null&&f.call(window,x))&&((j=window.MotionHasOptimisedAnimation)==null?void 0:j.call(window,x)));return vu(()=>{m&&(h.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),p.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var w;(w=window.MotionHandoffMarkAsComplete)==null||w.call(window,x)}),g.current=!1),m.enteringChildren=void 0)}),m}function fN(t,s,a,r){const{layoutId:n,layout:i,drag:o,dragConstraints:l,layoutScroll:c,layoutRoot:d,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:Ch(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!o||l&&Ha(l),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function Ch(t){if(t)return t.options.allowProjection!==!1?t.projection:Ch(t.parent)}function yi(t,{forwardMotionProps:s=!1}={},a,r){a&&Hj(a);const n=ml(t)?uN:mN;function i(l,c){let d;const m={...p.useContext(il),...l,layoutId:yN(l)},{isStatic:u}=m,h=Zj(l),x=n(l,u);if(!u&&Oo){bN();const g=vN(m);d=g.MeasureLayout,h.visualElement=gN(t,x,m,r,g.ProjectionNode)}return e.jsxs(Wn.Provider,{value:h,children:[d&&h.visualElement?e.jsx(d,{visualElement:h.visualElement,...m}):null,lN(t,l,pN(x,h.visualElement,c),x,u,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const o=p.forwardRef(i);return o[hN]=t,o}function yN({layoutId:t}){const s=p.useContext(_o).id;return s&&t!==void 0?s+"-"+t:t}function bN(t,s){p.useContext(uh).strict}function vN(t){const{drag:s,layout:a}=Qa;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 jN(t,s){if(typeof Proxy>"u")return yi;const a=new Map,r=(i,o)=>yi(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,yi(o,void 0,t,s)),a.get(o))})}function Sh({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function NN({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function wN(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 bi(t){return t===void 0||t===1}function io({scale:t,scaleX:s,scaleY:a}){return!bi(t)||!bi(s)||!bi(a)}function ka(t){return io(t)||Ah(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Ah(t){return qc(t.x)||qc(t.y)}function qc(t){return t&&t!=="0%"}function Tn(t,s,a){const r=t-a,n=s*r;return a+n}function ed(t,s,a,r,n){return n!==void 0&&(t=Tn(t,n,r)),Tn(t,a,r)+s}function oo(t,s=0,a=1,r,n){t.min=ed(t.min,s,a,r,n),t.max=ed(t.max,s,a,r,n)}function kh(t,{x:s,y:a}){oo(t.x,s.translate,s.scale,s.originPoint),oo(t.y,a.translate,a.scale,a.originPoint)}const td=.999999999999,sd=1.0000000000001;function CN(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,o;for(let l=0;ltd&&(s.x=1),s.ytd&&(s.y=1)}function Wa(t,s){t.min=t.min+s,t.max=t.max+s}function ad(t,s,a,r,n=.5){const i=Tt(t.min,t.max,n);oo(t,s,a,i,r)}function Ga(t,s){ad(t.x,s.x,s.scaleX,s.scale,s.originX),ad(t.y,s.y,s.scaleY,s.scale,s.originY)}function Th(t,s){return Sh(wN(t.getBoundingClientRect(),s))}function SN(t,s,a){const r=Th(t,a),{scroll:n}=s;return n&&(Wa(r.x,n.offset.x),Wa(r.y,n.offset.y)),r}const rd=()=>({translate:0,scale:1,origin:0,originPoint:0}),Ka=()=>({x:rd(),y:rd()}),nd=()=>({min:0,max:0}),Ft=()=>({x:nd(),y:nd()}),lo={current:null},Dh={current:!1};function AN(){if(Dh.current=!0,!!Oo)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>lo.current=t.matches;t.addEventListener("change",s),s()}else lo.current=!1}const kN=new WeakMap;function TN(t,s,a){for(const r in s){const n=s[r],i=a[r];if(ts(n))t.addValue(r,n);else if(ts(i))t.addValue(r,Ja(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,Ja(o!==void 0?o:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const id=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class DN{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=tl,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=fs.now();this.renderScheduledAtthis.bindToMotionValue(n,r)),Dh.current||AN(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:lo.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),xa(this.notifyUpdate),xa(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=ir.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",o=>{this.latestValues[s]=o,this.props.onUpdate&&At.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 Qa){const a=Qa[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):Ft()}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;ra.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=Ja(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"&&(ju(r)||wu(r))?r=parseFloat(r):!Lj(r)&&ga.test(a)&&(r=rh(s,a)),this.setBaseTarget(s,ts(r)?r.get():r)),ts(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=ul(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&&!ts(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 zo),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){rl.render(this.render)}}class Rh extends DN{constructor(){super(...arguments),this.KeyframeResolver=Sj}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;ts(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function Ph(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 RN(t){return window.getComputedStyle(t)}class PN extends Rh{constructor(){super(...arguments),this.type="html",this.renderInstance=Ph}readValueFromInstance(s,a){var r;if(ir.has(a))return(r=this.projection)!=null&&r.isProjecting?qi(a):Hv(s,a);{const n=RN(s),i=(Go(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return Th(s,a)}build(s,a,r){cl(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return hl(s,a,r)}}const Eh=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 EN(t,s,a,r){Ph(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(Eh.has(n)?n:pl(n),s.attrs[n])}class IN extends Rh{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Ft}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(ir.has(a)){const r=ah(a);return r&&r.default||0}return a=Eh.has(a)?a:pl(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return jh(s,a,r)}build(s,a,r){fh(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){EN(s,a,r,n)}mount(s){this.isSVGTag=bh(s.tagName),super.mount(s)}}const MN=(t,s)=>ml(t)?new IN(s):new PN(s,{allowProjection:t!==p.Fragment});function Xa(t,s,a){const r=t.getProps();return ul(r,s,a!==void 0?a:r.custom,t)}const co=t=>Array.isArray(t);function FN(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,Ja(a))}function _N(t){return co(t)?t[t.length-1]||0:t}function LN(t,s){const a=Xa(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const o in i){const l=_N(i[o]);FN(t,o,l)}}function ON(t){return!!(ts(t)&&t.add)}function mo(t,s){const a=t.getValue("willChange");if(ON(a))return a.add(s);if(!a&&na.WillChange){const r=new na.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function Ih(t){return t.props[Nh]}const $N=t=>t!==null;function BN(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter($N),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const UN={type:"spring",stiffness:500,damping:25,restSpeed:10},VN=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),zN={type:"keyframes",duration:.8},HN={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},WN=(t,{keyframes:s})=>s.length>2?zN:ir.has(t)?t.startsWith("scale")?VN(s[1]):UN:HN;function GN({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:o,repeatDelay:l,from:c,elapsed:d,...m}){return!!Object.keys(m).length}const xl=(t,s,a,r={},n,i)=>o=>{const l=sl(r,t)||{},c=l.delay||r.delay||0;let{elapsed:d=0}=r;d=d-Vs(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...l,delay:-d,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};GN(l)||Object.assign(m,WN(t,m)),m.duration&&(m.duration=Vs(m.duration)),m.repeatDelay&&(m.repeatDelay=Vs(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let u=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(ro(m),m.delay===0&&(u=!0)),(na.instantAnimations||na.skipAnimations)&&(u=!0,ro(m),m.delay=0),m.allowFlatten=!l.type&&!l.ease,u&&!i&&s.get()!==void 0){const h=BN(m.keyframes,l);if(h!==void 0){At.update(()=>{m.onUpdate(h),m.onComplete()});return}}return l.isSync?new el(m):new hj(m)};function KN({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Mh(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:o,...l}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in l){const u=t.getValue(m,t.latestValues[m]??null),h=l[m];if(h===void 0||d&&KN(d,m))continue;const x={delay:a,...sl(i||{},m)},g=u.get();if(g!==void 0&&!u.isAnimating&&!Array.isArray(h)&&h===g&&!x.velocity)continue;let f=!1;if(window.MotionHandoffAnimation){const w=Ih(t);if(w){const b=window.MotionHandoffAnimation(w,m,At);b!==null&&(x.startTime=b,f=!0)}}mo(t,m),u.start(xl(m,u,h,t.shouldReduceMotion&&eh.has(m)?{type:!1}:x,t,f));const j=u.animation;j&&c.push(j)}return o&&Promise.all(c).then(()=>{At.update(()=>{o&&LN(t,o)})}),c}function Fh(t,s,a,r=0,n=1){const i=Array.from(t).sort((d,m)=>d.sortNodePosition(m)).indexOf(s),o=t.size,l=(o-1)*r;return typeof a=="function"?a(i,o):n===1?i*r:l-i*r}function uo(t,s,a={}){var c;const r=Xa(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(Mh(t,r,a)):()=>Promise.resolve(),o=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:u,staggerDirection:h}=n;return YN(t,s,d,m,u,h,a)}:()=>Promise.resolve(),{when:l}=n;if(l){const[d,m]=l==="beforeChildren"?[i,o]:[o,i];return d().then(()=>m())}else return Promise.all([i(),o(a.delay)])}function YN(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(uo(c,s,{...o,delay:a+(typeof r=="function"?0:r)+Fh(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(l)}function ZN(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>uo(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=uo(t,s,a);else{const n=typeof s=="function"?Xa(t,s,a.custom):s;r=Promise.all(Mh(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function _h(t,s){if(!Array.isArray(s))return!1;const a=s.length;if(a!==t.length)return!1;for(let r=0;rPromise.all(s.map(({animation:a,options:r})=>ZN(t,a,r)))}function ew(t){let s=qN(t),a=od(),r=!0;const n=c=>(d,m)=>{var h;const u=Xa(t,m,c==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(u){const{transition:x,transitionEnd:g,...f}=u;d={...d,...f,...g}}return d};function i(c){s=c(t)}function o(c){const{props:d}=t,m=Lh(t.parent)||{},u=[],h=new Set;let x={},g=1/0;for(let j=0;jg&&v,M=!1;const y=Array.isArray(C)?C:[C];let A=y.reduce(n(w),{});N===!1&&(A={});const{prevResolvedValues:L={}}=b,K={...L,...A},O=S=>{P=!0,h.has(S)&&(M=!0,h.delete(S)),b.needsAnimating[S]=!0;const D=t.getValue(S);D&&(D.liveStyle=!1)};for(const S in K){const D=A[S],I=L[S];if(x.hasOwnProperty(S))continue;let _=!1;co(D)&&co(I)?_=!_h(D,I):_=D!==I,_?D!=null?O(S):h.add(S):D!==void 0&&h.has(S)?O(S):b.protectedKeys[S]=!0}b.prevProp=C,b.prevResolvedValues=A,b.isActive&&(x={...x,...A}),r&&t.blockInitialAnimation&&(P=!1);const $=k&&E;P&&(!$||M)&&u.push(...y.map(S=>{const D={type:w};if(typeof S=="string"&&r&&!$&&t.manuallyAnimateOnMount&&t.parent){const{parent:I}=t,_=Xa(I,S);if(I.enteringChildren&&_){const{delayChildren:F}=_.transition||{};D.delay=Fh(I.enteringChildren,t,F)}}return{animation:S,options:D}}))}if(h.size){const j={};if(typeof d.initial!="boolean"){const w=Xa(t,Array.isArray(d.initial)?d.initial[0]:d.initial);w&&w.transition&&(j.transition=w.transition)}h.forEach(w=>{const b=t.getBaseTarget(w),C=t.getValue(w);C&&(C.liveStyle=!0),j[w]=b??null}),u.push({animation:j})}let f=!!u.length;return r&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(f=!1),r=!1,f?s(u):Promise.resolve()}function l(c,d){var u;if(a[c].isActive===d)return Promise.resolve();(u=t.variantChildren)==null||u.forEach(h=>{var x;return(x=h.animationState)==null?void 0:x.setActive(c,d)}),a[c].isActive=d;const m=o(c);for(const h in a)a[h].protectedKeys={};return m}return{animateChanges:o,setActive:l,setAnimateFunction:i,getState:()=>a,reset:()=>{a=od()}}}function tw(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!_h(s,t):!1}function Ca(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function od(){return{animate:Ca(!0),whileInView:Ca(),whileHover:Ca(),whileTap:Ca(),whileDrag:Ca(),whileFocus:Ca(),exit:Ca()}}class ba{constructor(s){this.isMounted=!1,this.node=s}update(){}}class sw extends ba{constructor(s){super(s),s.animationState||(s.animationState=ew(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Gn(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 aw=0;class rw extends ba{constructor(){super(...arguments),this.id=aw++}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 nw={animation:{Feature:sw},exit:{Feature:rw}};function Vr(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function Xr(t){return{point:{x:t.pageX,y:t.pageY}}}const iw=t=>s=>nl(s)&&t(s,Xr(s));function Tr(t,s,a,r){return Vr(t,s,iw(a),r)}const Oh=1e-4,ow=1-Oh,lw=1+Oh,$h=.01,cw=0-$h,dw=0+$h;function ds(t){return t.max-t.min}function mw(t,s,a){return Math.abs(t-s)<=a}function ld(t,s,a,r=.5){t.origin=r,t.originPoint=Tt(s.min,s.max,t.origin),t.scale=ds(a)/ds(s),t.translate=Tt(a.min,a.max,t.origin)-t.originPoint,(t.scale>=ow&&t.scale<=lw||isNaN(t.scale))&&(t.scale=1),(t.translate>=cw&&t.translate<=dw||isNaN(t.translate))&&(t.translate=0)}function Dr(t,s,a,r){ld(t.x,s.x,a.x,r?r.originX:void 0),ld(t.y,s.y,a.y,r?r.originY:void 0)}function cd(t,s,a){t.min=a.min+s.min,t.max=t.min+ds(s)}function uw(t,s,a){cd(t.x,s.x,a.x),cd(t.y,s.y,a.y)}function dd(t,s,a){t.min=s.min-a.min,t.max=t.min+ds(s)}function Rr(t,s,a){dd(t.x,s.x,a.x),dd(t.y,s.y,a.y)}function ks(t){return[t("x"),t("y")]}const Bh=({current:t})=>t?t.ownerDocument.defaultView:null,md=(t,s)=>Math.abs(t-s);function hw(t,s){const a=md(t.x,s.x),r=md(t.y,s.y);return Math.sqrt(a**2+r**2)}class Uh{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=ji(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,g=hw(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!g)return;const{point:f}=h,{timestamp:j}=Jt;this.history.push({...f,timestamp:j});const{onStart:w,onMove:b}=this.handlers;x||(w&&w(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),b&&b(this.lastMoveEvent,h)},this.handlePointerMove=(h,x)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=vi(x,this.transformPagePoint),At.update(this.updatePoint,!0)},this.handlePointerUp=(h,x)=>{this.end();const{onEnd:g,onSessionEnd:f,resumeAnimation:j}=this.handlers;if(this.dragSnapToOrigin&&j&&j(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=ji(h.type==="pointercancel"?this.lastMoveEventInfo:vi(x,this.transformPagePoint),this.history);this.startEvent&&g&&g(h,w),f&&f(h,w)},!nl(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=o,this.contextWindow=n||window;const l=Xr(s),c=vi(l,this.transformPagePoint),{point:d}=c,{timestamp:m}=Jt;this.history=[{...d,timestamp:m}];const{onSessionStart:u}=a;u&&u(s,ji(c,this.history)),this.removeListeners=Kr(Tr(this.contextWindow,"pointermove",this.handlePointerMove),Tr(this.contextWindow,"pointerup",this.handlePointerUp),Tr(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),xa(this.updatePoint)}}function vi(t,s){return s?{point:s(t.point)}:t}function ud(t,s){return{x:t.x-s.x,y:t.y-s.y}}function ji({point:t},s){return{point:t,delta:ud(t,Vh(s)),offset:ud(t,pw(s)),velocity:xw(s,.1)}}function pw(t){return t[0]}function Vh(t){return t[t.length-1]}function xw(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=Vh(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>Vs(s)));)a--;if(!r)return{x:0,y:0};const i=Ts(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 gw(t,{min:s,max:a},r){return s!==void 0&&ta&&(t=r?Tt(a,t,r.max):Math.min(t,a)),t}function hd(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 fw(t,{top:s,left:a,bottom:r,right:n}){return{x:hd(t.x,a,n),y:hd(t.y,s,r)}}function pd(t,s){let a=s.min-t.min,r=s.max-t.max;return s.max-s.minr?a=Lr(s.min,s.max-r,t.min):r>n&&(a=Lr(t.min,t.max-n,s.min)),ra(0,1,a)}function vw(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 ho=.35;function jw(t=ho){return t===!1?t=0:t===!0&&(t=ho),{x:xd(t,"left","right"),y:xd(t,"top","bottom")}}function xd(t,s,a){return{min:gd(t,s),max:gd(t,a)}}function gd(t,s){return typeof t=="number"?t:t[s]||0}const Nw=new WeakMap;class ww{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=Ft(),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(Xr(u).point)},o=(u,h)=>{const{drag:x,dragPropagation:g,onDragStart:f}=this.getProps();if(x&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Dj(x),!this.openDragLock))return;this.latestPointerEvent=u,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ks(w=>{let b=this.getAxisMotionValue(w).get()||0;if(zs.test(b)){const{projection:C}=this.visualElement;if(C&&C.layout){const v=C.layout.layoutBox[w];v&&(b=ds(v)*(parseFloat(b)/100))}}this.originPoint[w]=b}),f&&At.postRender(()=>f(u,h)),mo(this.visualElement,"transform");const{animationState:j}=this.visualElement;j&&j.setActive("whileDrag",!0)},l=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h;const{dragPropagation:x,dragDirectionLock:g,onDirectionLock:f,onDrag:j}=this.getProps();if(!x&&!this.openDragLock)return;const{offset:w}=h;if(g&&this.currentDirection===null){this.currentDirection=Cw(w),this.currentDirection!==null&&f&&f(this.currentDirection);return}this.updateAxis("x",h.point,w),this.updateAxis("y",h.point,w),this.visualElement.render(),j&&j(u,h)},c=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h,this.stop(u,h),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>ks(u=>{var h;return this.getAnimationState(u)==="paused"&&((h=this.getAxisMotionValue(u).animation)==null?void 0:h.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new Uh(s,{onSessionStart:i,onStart:o,onMove:l,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:Bh(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&&At.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||!dn(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let o=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(o=gw(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&&Ha(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=fw(r.layoutBox,s):this.constraints=!1,this.elastic=jw(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&ks(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=vw(r.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!Ha(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=SN(r,n.root,this.visualElement.getTransformPagePoint());let o=yw(n.layout.layoutBox,i);if(a){const l=a(NN(o));this.hasMutatedConstraints=!!l,l&&(o=Sh(l))}return o}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:o,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},d=ks(m=>{if(!dn(m,a,this.currentDirection))return;let u=c&&c[m]||{};o&&(u={min:0,max:0});const h=n?200:1e6,x=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:h,bounceDamping:x,timeConstant:750,restDelta:1,restSpeed:10,...i,...u};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(l)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return mo(this.visualElement,s),r.start(xl(s,r,0,a,this.visualElement,!1))}stopAnimation(){ks(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){ks(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){ks(a=>{const{drag:r}=this.getProps();if(!dn(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]-Tt(o,l,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!Ha(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};ks(o=>{const l=this.getAxisMotionValue(o);if(l&&this.constraints!==!1){const c=l.get();n[o]=bw({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(),ks(o=>{if(!dn(o,s,null))return;const l=this.getAxisMotionValue(o),{min:c,max:d}=this.constraints[o];l.set(Tt(c,d,n[o]))})}addListeners(){if(!this.visualElement.current)return;Nw.set(this.visualElement,this);const s=this.visualElement.current,a=Tr(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();Ha(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()),At.read(r);const o=Vr(window,"resize",()=>this.scalePositionWithinConstraints()),l=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(ks(m=>{const u=this.getAxisMotionValue(m);u&&(this.originPoint[m]+=c[m].translate,u.set(u.get()+c[m].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=ho,dragMomentum:l=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:o,dragMomentum:l}}}function dn(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function Cw(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class Sw extends ba{constructor(s){super(s),this.removeGroupControls=Ds,this.removeListeners=Ds,this.controls=new ww(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ds}unmount(){this.removeGroupControls(),this.removeListeners()}}const fd=t=>(s,a)=>{t&&At.postRender(()=>t(s,a))};class Aw extends ba{constructor(){super(...arguments),this.removePointerDownListener=Ds}onPointerDown(s){this.session=new Uh(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Bh(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:fd(s),onStart:fd(a),onMove:r,onEnd:(i,o)=>{delete this.session,n&&At.postRender(()=>n(i,o))}}}mount(){this.removePointerDownListener=Tr(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 bn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function yd(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const Nr={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(Fe.test(t))t=parseFloat(t);else return t;const a=yd(t,s.target.x),r=yd(t,s.target.y);return`${a}% ${r}%`}},kw={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=ga.parse(t);if(n.length>5)return r;const i=ga.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 d=Tt(l,c,.5);return typeof n[2+o]=="number"&&(n[2+o]/=d),typeof n[3+o]=="number"&&(n[3+o]/=d),i(n)}};let Ni=!1;class Tw extends p.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;Xj(Dw),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),Ni&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),bn.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:o}=r;return o&&(o.isPresent=i,Ni=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?o.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?o.promote():o.relegate()||At.postRender(()=>{const l=o.getStack();(!l||!l.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),rl.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;Ni=!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 zh(t){const[s,a]=mh(),r=p.useContext(_o);return e.jsx(Tw,{...t,layoutGroup:r,switchLayoutGroup:p.useContext(wh),isPresent:s,safeToRemove:a})}const Dw={borderRadius:{...Nr,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Nr,borderTopRightRadius:Nr,borderBottomLeftRadius:Nr,borderBottomRightRadius:Nr,boxShadow:kw};function Rw(t,s,a){const r=ts(t)?t:Ja(t);return r.start(xl("",r,s,a)),r.animation}const Pw=(t,s)=>t.depth-s.depth;class Ew{constructor(){this.children=[],this.isDirty=!1}add(s){$o(this.children,s),this.isDirty=!0}remove(s){Bo(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(Pw),this.isDirty=!1,this.children.forEach(s)}}function Iw(t,s){const a=fs.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(xa(r),t(i-s))};return At.setup(r,!0),()=>xa(r)}const Hh=["TopLeft","TopRight","BottomLeft","BottomRight"],Mw=Hh.length,bd=t=>typeof t=="string"?parseFloat(t):t,vd=t=>typeof t=="number"||Fe.test(t);function Fw(t,s,a,r,n,i){n?(t.opacity=Tt(0,a.opacity??1,_w(r)),t.opacityExit=Tt(s.opacity??1,0,Lw(r))):i&&(t.opacity=Tt(s.opacity??1,a.opacity??1,r));for(let o=0;ors?1:a(Lr(t,s,r))}function Nd(t,s){t.min=s.min,t.max=s.max}function As(t,s){Nd(t.x,s.x),Nd(t.y,s.y)}function wd(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function Cd(t,s,a,r,n){return t-=s,t=Tn(t,1/a,r),n!==void 0&&(t=Tn(t,1/n,r)),t}function Ow(t,s=0,a=1,r=.5,n,i=t,o=t){if(zs.test(s)&&(s=parseFloat(s),s=Tt(o.min,o.max,s/100)-o.min),typeof s!="number")return;let l=Tt(i.min,i.max,r);t===i&&(l-=s),t.min=Cd(t.min,s,a,l,n),t.max=Cd(t.max,s,a,l,n)}function Sd(t,s,[a,r,n],i,o){Ow(t,s[a],s[r],s[n],s.scale,i,o)}const $w=["x","scaleX","originX"],Bw=["y","scaleY","originY"];function Ad(t,s,a,r){Sd(t.x,s,$w,a?a.x:void 0,r?r.x:void 0),Sd(t.y,s,Bw,a?a.y:void 0,r?r.y:void 0)}function kd(t){return t.translate===0&&t.scale===1}function Gh(t){return kd(t.x)&&kd(t.y)}function Td(t,s){return t.min===s.min&&t.max===s.max}function Uw(t,s){return Td(t.x,s.x)&&Td(t.y,s.y)}function Dd(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function Kh(t,s){return Dd(t.x,s.x)&&Dd(t.y,s.y)}function Rd(t){return ds(t.x)/ds(t.y)}function Pd(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class Vw{constructor(){this.members=[]}add(s){$o(this.members,s),s.scheduleRender()}remove(s){if(Bo(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 zw(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:d,rotate:m,rotateX:u,rotateY:h,skewX:x,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),u&&(r+=`rotateX(${u}deg) `),h&&(r+=`rotateY(${h}deg) `),x&&(r+=`skewX(${x}deg) `),g&&(r+=`skewY(${g}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 wi=["","X","Y","Z"],Hw=1e3;let Ww=0;function Ci(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Yh(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=Ih(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",At,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Yh(r)}function Zh({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(o={},l=s==null?void 0:s()){this.id=Ww++,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(Yw),this.nodes.forEach(Qw),this.nodes.forEach(qw),this.nodes.forEach(Zw)},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;cthis.root.updateBlockedByResize=!1;At.read(()=>{u=window.innerWidth}),t(o,()=>{const x=window.innerWidth;x!==u&&(u=x,this.root.updateBlockedByResize=!0,m&&m(),m=Iw(h,250),bn.hasAnimatedSinceResize&&(bn.hasAnimatedSinceResize=!1,this.nodes.forEach(Md)))})}l&&this.root.registerSharedNode(l,this),this.options.animate!==!1&&d&&(l||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:u,hasRelativeLayoutChanged:h,layout:x})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||rC,{onLayoutAnimationStart:f,onLayoutAnimationComplete:j}=d.getProps(),w=!this.targetLayout||!Kh(this.targetLayout,x),b=!u&&h;if(this.options.layoutRoot||this.resumeFrom||b||u&&(w||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const C={...sl(g,"layout"),onPlay:f,onComplete:j};(d.shouldReduceMotion||this.options.layoutRoot)&&(C.delay=0,C.type=!1),this.startAnimation(C),this.setAnimationOrigin(m,b)}else u||Md(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=x})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const o=this.getStack();o&&o.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),xa(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(eC),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&&Yh(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let m=0;m{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!ds(this.snapshot.measuredBox.x)&&!ds(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{const N=v/1e3;Fd(u.x,o.x,N),Fd(u.y,o.y,N),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Rr(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),sC(this.relativeTarget,this.relativeTargetOrigin,h,N),C&&Uw(this.relativeTarget,C)&&(this.isProjectionDirty=!1),C||(C=Ft()),As(C,this.relativeTarget)),f&&(this.animationValues=m,Fw(m,d,this.latestValues,N,b,w)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=N},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){var l,c,d;this.notifyListeners("animationStart"),(l=this.currentAnimation)==null||l.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(xa(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=At.update(()=>{bn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Ja(0)),this.currentAnimation=Rw(this.motionValue,[0,1e3],{...o,velocity:0,isSync:!0,onUpdate:m=>{this.mixTargetDelta(m),o.onUpdate&&o.onUpdate(m)},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(Hw),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const o=this.getLead();let{targetWithTransforms:l,target:c,layout:d,latestValues:m}=o;if(!(!l||!c||!d)){if(this!==o&&this.layout&&d&&Xh(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Ft();const u=ds(this.layout.layoutBox.x);c.x.min=o.target.x.min,c.x.max=c.x.min+u;const h=ds(this.layout.layoutBox.y);c.y.min=o.target.y.min,c.y.max=c.y.min+h}As(l,c),Ga(l,m),Dr(this.projectionDeltaWithTransform,this.layoutCorrected,l,m)}}registerSharedNode(o,l){this.sharedNodes.has(o)||this.sharedNodes.set(o,new Vw),this.sharedNodes.get(o).add(l);const d=l.options.initialPromotionConfig;l.promote({transition:d?d.transition:void 0,preserveFollowOpacity:d&&d.shouldPreserveFollowOpacity?d.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 d=this.getStack();d&&d.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 d={};c.z&&Ci("z",o,d,this.animationValues);for(let m=0;m{var l;return(l=o.currentAnimation)==null?void 0:l.stop()}),this.root.nodes.forEach(Ed),this.root.sharedNodes.clear()}}}function Gw(t){t.updateLayout()}function Kw(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"?ks(u=>{const h=o?s.measuredBox[u]:s.layoutBox[u],x=ds(h);h.min=r[u].min,h.max=h.min+x}):Xh(i,s.layoutBox,r)&&ks(u=>{const h=o?s.measuredBox[u]:s.layoutBox[u],x=ds(r[u]);h.max=h.min+x,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+x)});const l=Ka();Dr(l,r,s.layoutBox);const c=Ka();o?Dr(c,t.applyTransform(n,!0),s.measuredBox):Dr(c,r,s.layoutBox);const d=!Gh(l);let m=!1;if(!t.resumeFrom){const u=t.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:h,layout:x}=u;if(h&&x){const g=Ft();Rr(g,s.layoutBox,h.layoutBox);const f=Ft();Rr(f,r,x.layoutBox),Kh(g,f)||(m=!0),u.options.layoutRoot&&(t.relativeTarget=f,t.relativeTargetOrigin=g,t.relativeParent=u)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:l,hasLayoutChanged:d,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function Yw(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 Zw(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Xw(t){t.clearSnapshot()}function Ed(t){t.clearMeasurements()}function Id(t){t.isLayoutDirty=!1}function Jw(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function Md(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Qw(t){t.resolveTargetDelta()}function qw(t){t.calcProjection()}function eC(t){t.resetSkewAndRotation()}function tC(t){t.removeLeadSnapshot()}function Fd(t,s,a){t.translate=Tt(s.translate,0,a),t.scale=Tt(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function _d(t,s,a,r){t.min=Tt(s.min,a.min,r),t.max=Tt(s.max,a.max,r)}function sC(t,s,a,r){_d(t.x,s.x,a.x,r),_d(t.y,s.y,a.y,r)}function aC(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const rC={duration:.45,ease:[.4,0,.1,1]},Ld=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Od=Ld("applewebkit/")&&!Ld("chrome/")?Math.round:Ds;function $d(t){t.min=Od(t.min),t.max=Od(t.max)}function nC(t){$d(t.x),$d(t.y)}function Xh(t,s,a){return t==="position"||t==="preserve-aspect"&&!mw(Rd(s),Rd(a),.2)}function iC(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const oC=Zh({attachResizeListener:(t,s)=>Vr(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Si={current:void 0},Jh=Zh({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Si.current){const t=new oC({});t.mount(window),t.setOptions({layoutScroll:!0}),Si.current=t}return Si.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),lC={pan:{Feature:Aw},drag:{Feature:Sw,ProjectionNode:Jh,MeasureLayout:zh}};function Bd(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&&At.postRender(()=>i(s,Xr(s)))}class cC extends ba{mount(){const{current:s}=this.node;s&&(this.unmount=Rj(s,(a,r)=>(Bd(this.node,r,"Start"),n=>Bd(this.node,n,"End"))))}unmount(){}}class dC extends ba{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=Kr(Vr(this.node.current,"focus",()=>this.onFocus()),Vr(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Ud(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&&At.postRender(()=>i(s,Xr(s)))}class mC extends ba{mount(){const{current:s}=this.node;s&&(this.unmount=Mj(s,(a,r)=>(Ud(this.node,r,"Start"),(n,{success:i})=>Ud(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const po=new WeakMap,Ai=new WeakMap,uC=t=>{const s=po.get(t.target);s&&s(t)},hC=t=>{t.forEach(uC)};function pC({root:t,...s}){const a=t||document;Ai.has(a)||Ai.set(a,{});const r=Ai.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(hC,{root:t,...s})),r[n]}function xC(t,s,a){const r=pC(s);return po.set(t,a),r.observe(t),()=>{po.delete(t),r.unobserve(t)}}const gC={some:0,all:1};class fC extends ba{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:gC[n]},l=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:u}=this.node.getProps(),h=d?m:u;h&&h(c)};return xC(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(yC(s,a))&&this.startObserver()}unmount(){}}function yC({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const bC={inView:{Feature:fC},tap:{Feature:mC},focus:{Feature:dC},hover:{Feature:cC}},vC={layout:{ProjectionNode:Jh,MeasureLayout:zh}},jC={...nw,...bC,...lC,...vC},Yt=jN(jC,MN),Vd=[{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:ms,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:Og,color:"from-green-500 to-emerald-600",estimatedTime:"3-5 days",steps:5,features:["PO matching","Invoice verification","Multi-level approvals","Payment scheduling"]}];function NC({open:t,onClose:s,onSelectTemplate:a}){var l;const[r,n]=p.useState(null),i=c=>{n(c)},o=()=>{r&&(a(r),s())};return e.jsx(nt,{open:t,onOpenChange:s,children:e.jsxs(tt,{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(st,{className:"sr-only",children:"Select a Template"}),e.jsx(Mt,{className:"sr-only",children:"Choose from pre-configured templates with predefined workflows and approval chains for faster processing."}),e.jsx("button",{onClick:s,className:"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(ut,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsxs("div",{className:"min-h-full flex flex-col items-center justify-center px-6 py-12",children:[e.jsxs(Yt.div,{initial:{opacity:0,y:-20},animate:{opacity:1,y:0},className:"text-center mb-12 max-w-3xl",children:[e.jsx("div",{className:"w-20 h-20 bg-gradient-to-br from-blue-500 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-6",children:e.jsx(Fn,{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:Vd.map((c,d)=>{const m=c.icon,u=r===c.id;return e.jsx(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:d*.1},whileHover:{scale:1.03},whileTap:{scale:.98},children:e.jsxs(X,{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(le,{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(m,{className:"w-7 h-7 text-white"})}),u&&e.jsx(Yt.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center shadow-md",children:e.jsx(er,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(ce,{className:"text-xl mb-2",children:c.name}),e.jsx(je,{className:"text-sm leading-relaxed",children:c.description})]})]}),e.jsxs(J,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(se,{variant:"secondary",className:"text-xs",children:c.category})}),e.jsx(It,{}),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(He,{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(Dt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[c.steps," steps"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx("p",{className:"text-xs text-gray-500 font-semibold",children:"Key Features:"}),e.jsxs("div",{className:"space-y-1.5",children:[c.features.slice(0,3).map((h,x)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(Ce,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:h})]},x)),c.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",c.features.length-3," more features"]})]})]})]})]})},c.id)})}),e.jsxs(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"flex flex-col sm:flex-row justify-center gap-4 mt-4",children:[e.jsx(R,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(R,{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(Wt,{className:"w-4 h-4"})]})]}),e.jsx(Hn,{children:r&&e.jsx(Yt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},className:"mt-6 text-center",children:e.jsxs("p",{className:"text-sm text-gray-600",children:["Selected: ",e.jsx("span",{className:"font-semibold text-blue-600",children:(l=Vd.find(c=>c.id===r))==null?void 0:l.name})]})})})]})})]})})}function gl({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:o,onClose:l}){const[c,d]=p.useState(100),[m,u]=p.useState(0),[h,x]=p.useState(null),[g,f]=p.useState(!1),[j,w]=p.useState(null),b=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),C=s.toLowerCase().includes("pdf"),v=b||C;p.useEffect(()=>{if(!o||!v||!a){x(null);return}return(async()=>{f(!0),w(null);try{let L=a;a.startsWith("/")&&!a.startsWith("//")&&(L=`${window.location.origin}${a}`);const O=await fetch(L,{headers:{Accept:C?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!O.ok){const S=await O.text().catch(()=>"");throw new Error(`Failed to load file: ${O.status} ${O.statusText}. ${S}`)}const $=await O.blob();if($.size===0)throw new Error("File is empty or could not be loaded");C&&!$.type.includes("pdf")&&$.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${$.type}`);const T=window.URL.createObjectURL($);x(T)}catch(y){console.error("Failed to load file for preview:",y),w(y instanceof Error?y.message:"Failed to load file for preview")}finally{f(!1)}})(),()=>{h&&(window.URL.revokeObjectURL(h),x(null))}},[o,a,v,C]);const N=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},k=()=>d(M=>Math.min(M+25,200)),E=()=>d(M=>Math.max(M-25,50)),P=()=>u(M=>(M+90)%360);return e.jsx(nt,{open:o,onOpenChange:l,children:e.jsx(tt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(it,{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(rs,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(st,{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:[b&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(R,{variant:"ghost",size:"sm",onClick:E,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx($g,{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(R,{variant:"ghost",size:"sm",onClick:k,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(Bg,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"sm",onClick:P,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(Ug,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(R,{variant:"outline",size:"sm",onClick:N,className:"gap-2 h-9",children:[e.jsx(ss,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})]})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:g?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[e.jsx(Je,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):j?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(ut,{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:j}),i&&n&&e.jsxs(R,{onClick:N,className:"gap-2",children:[e.jsx(ss,{className:"h-4 w-4"}),"Download ",t]})]}):v&&h?e.jsxs(e.Fragment,{children:[b&&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(${m}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),C&&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:()=>{w("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(rs,{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(R,{onClick:N,className:"gap-2",children:[e.jsx(ss,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function Qh({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(nt,{open:t,onOpenChange:s,children:e.jsxs(tt,{className:"sm:max-w-lg",children:[e.jsxs(it,{children:[e.jsxs(st,{className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Mt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following policy violations were detected:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:a.map((n,i)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:n.type}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:n.message}),n.currentValue!==void 0&&n.maxValue!==void 0&&e.jsxs("p",{className:"text-xs text-red-600 mt-1 font-semibold",children:["Current: ",n.currentValue," / Maximum: ",n.maxValue]})]},i))}),r&&e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"System Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[r.maxApprovalLevels!==void 0&&e.jsxs("li",{children:["Maximum approval levels: ",r.maxApprovalLevels]}),r.maxParticipants!==void 0&&e.jsxs("li",{children:["Maximum participants per request: ",r.maxParticipants]}),r.allowSpectators!==void 0&&e.jsxs("li",{children:["Allow adding spectators: ",r.allowSpectators?"Yes":"No"]}),r.maxSpectators!==void 0&&e.jsxs("li",{children:["Maximum spectators per request: ",r.maxSpectators]})]})]})]})})]}),e.jsx(Nt,{children:e.jsx(R,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const _a=async t=>{const s=t?{category:t}:{};return(await he.get("/users/configurations",{params:s})).data.data},Yn=async t=>{const s=t?{category:t}:{};return(await he.get("/admin/configurations",{params:s})).data.data},os=async(t,s)=>{await he.put(`/admin/configurations/${t}`,{configValue:s})},wC=async t=>{await he.post(`/admin/configurations/${t}/reset`)},CC=async t=>{const s=t?{year:t}:{};return(await he.get("/admin/holidays",{params:s})).data.data},SC=async t=>(await he.post("/admin/holidays",t)).data.data,AC=async(t,s)=>(await he.put(`/admin/holidays/${t}`,s)).data.data,kC=async t=>{await he.delete(`/admin/holidays/${t}`)},TC={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 DC(t,s,a){const[r,n]=p.useState(TC),[i,o]=p.useState(null),[l,c]=p.useState(t),[d,m]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[u,h]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[x,g]=p.useState([]);return p.useEffect(()=>{(async()=>{var w;try{const b=await _a("DOCUMENT_POLICY"),C={};b.forEach(A=>{C[A.configKey]=A.configValue});const v=parseInt(C.MAX_FILE_SIZE_MB||"10"),k=(C.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(A=>A.trim().toLowerCase());h({maxFileSizeMB:v,allowedFileTypes:k});const E=await _a("WORKFLOW_SHARING"),P=await _a("TAT_SETTINGS"),M=[...E,...P],y={};M.forEach(A=>{y[A.configKey]=A.configValue}),m({maxApprovalLevels:parseInt(y.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(y.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((w=y.ALLOW_ADD_SPECTATOR)==null?void 0:w.toLowerCase())==="true",maxSpectators:parseInt(y.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(b){console.error("Failed to load policies:",b)}})()},[]),p.useEffect(()=>{if(!t||!s)return;let j=!0;return(async()=>{try{c(!0);const w=await xs(s);if(!j||!w)return;const b=w.workflow||{},C=Array.isArray(w.approvals)?w.approvals:[],v=Array.isArray(w.participants)?w.participants:[],N=Array.isArray(w.documents)?w.documents.filter(L=>!L.isDeleted):[];g(N);const k=(b.priority||"").toString().toLowerCase(),E={standard:"standard",express:"express"},P=b.templateType==="TEMPLATE"?"existing-template":"custom",M=a.find(L=>L.id===P)||a[0]||null;o(M);const y=C.sort((L,K)=>(L.levelNumber||0)-(K.levelNumber||0)).map(L=>{const K=Number(L.tatHours||24),O=Math.floor(K/24),$=K%24;return{id:L.approverId||`temp-${L.levelNumber}`,name:L.approverName||L.approverEmail||"",email:L.approverEmail||"",role:L.levelName||`Level ${L.levelNumber}`,department:"",avatar:(L.approverName||L.approverEmail||"XX").substring(0,2).toUpperCase(),level:L.levelNumber||1,canClose:!1,tat:O>0?O:$,tatType:O>0?"days":"hours",userId:L.approverId}}),A=v.filter(L=>(L.participantType||L.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(L.userEmail||L.user_email||L.email):!1).map((L,K)=>{const O=L.userId||L.user_id||L.id,$=L.userName||L.user_name||L.name||"",T=L.userEmail||L.user_email||L.email||"",D=($||T||"XX").split(" ").map(I=>I[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:O||`spectator-${s}-${K}-${Date.now()}`,userId:O,name:$||T||"Spectator",email:T,role:"Spectator",department:L.department||"",avatar:D,level:1,canClose:!1}});n(L=>({...L,template:P,title:b.title||"",description:b.description||"",priority:E[k]||"standard",approvers:y,approverCount:y.length||1,spectators:A,maxLevel:Math.max(...y.map(K=>K.level||1),1)}))}catch(w){console.error("Failed to load draft:",w)}finally{j&&c(!1)}})(),()=>{j=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(j,w)=>{n(b=>({...b,[j]:w}))},selectedTemplate:i,setSelectedTemplate:o,loadingDraft:l,systemPolicy:d,documentPolicy:u,existingDocuments:x,setExistingDocuments:g}}const zd=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function RC(t,s,a){const[r,n]=p.useState(t?2:1),i=zd.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:zd,isStepValid:l,nextStep:()=>{l()&&(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),r{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 PC(){const[t,s]=p.useState({open:!1,type:"error",email:"",message:""}),[a,r]=p.useState({open:!1,violations:[]}),[n,i]=p.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(h,x,g="")=>{s({open:!0,type:h,email:x,message:g})},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 EC(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function IC(t,s,a){var n;const r=EC(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 MC(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return IC(a,n,n===s)})}function Hd(t,s,a){const r=new Set((t.approvers||[]).map(i=>{var o;return(o=i==null?void 0:i.email)==null?void 0:o.toLowerCase()}).filter(Boolean)),n=(t.spectators||[]).filter(i=>(i==null?void 0:i.email)&&!r.has(i.email.toLowerCase()));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=>({userId:(i==null?void 0:i.userId)||"",name:(i==null?void 0:i.name)||"",email:(i==null?void 0:i.email)||""})),ccList:[],participants:[]}}function Wd(t,s,a){const r=MC(t.approvers||[],t.approverCount||1);return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:r,participants:[],deleteDocumentIds:a.length>0?a:void 0}}function FC(t,s){const a=t.slice(0,s);if(a.some(o=>!(o!=null&&o.email)||!o.email.trim()))return{valid:!1,message:"Please provide email addresses for all approvers."};const n=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return a.some(o=>!n.test((o==null?void 0:o.email)||""))?{valid:!1,message:"Please provide valid email addresses for all approvers."}:{valid:!0}}async function qh(t,s){return{id:(await ou(t,s||[],"SUPPORTING")).id}}async function ep(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await rb(t,s,a||[],r):await ab(t,s)}async function tp(t){await uu(t)}async function _C(t,s){const a=await qh(t,s);return await tp(a.id),a}async function LC(t,s,a,r){await ep(t,s,a,r),await tp(t)}function OC({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:o,onSubmit:l}){const[c,d]=p.useState(!1),[m,u]=p.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{if(c||m)return;const g=FC(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&o){const f=Wd(t,n,r);await LC(o,f,a,r),l==null||l({...t,backendId:o,template:s})}else{const f=Hd(t,s,n),j=await _C(f,a);l==null||l({...t,backendId:j.id,template:s})}}catch(f){console.error("Failed to submit workflow:",f),d(!1)}},handleSaveDraft:async()=>{if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||m)){u(!0);try{if(i&&o){const g=Wd(t,n,r);await ep(o,g,a,r),l==null||l({...t,backendId:o,template:s})}else{const g=Hd(t,s,n),f=await qh(g,a);l==null||l({...t,backendId:f.id,template:s})}}catch(g){console.error("Failed to save draft:",g),u(!1)}}}}}async function Ys(t,s=10){return await he.get("/users/search",{params:{q:t,limit:s}})}async function ia(t){var a;const s=await he.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function $C(t,s){return await he.post("/admin/users/assign-role",{email:t,role:s})}async function BC(t,s){return await he.put(`/admin/users/${t}/role`,{role:s})}async function UC(t,s=1,a=10){return await he.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function VC(){return await he.get("/admin/users/role-statistics")}async function zC(){var s,a;return((a=(s=(await he.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const js={searchUsers:Ys,ensureUserExists:ia,assignRole:$C,updateUserRole:BC,getUsersByRole:UC,getRoleStatistics:VC,getAllUsers:zC};async function HC(t,s){var a;if(t.email.toLowerCase()===s.toLowerCase())return{success:!1,error:{type:"self-assign",email:t.email,message:""}};try{const n=((a=(await Ys(t.email,1)).data)==null?void 0:a.data)||[];if(n.length===0)return{success:!1,error:{type:"not-found",email:t.email,message:""}};const i=n[0];return i?(await ia({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 WC(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{s(N),a("template",N.id),a("category",N.category),a("priority",N.priority);const k=new Date;k.setDate(k.getDate()+N.suggestedSLA),a("slaEndDate",k),N.id==="existing-template"&&h(!0)},handleTemplateSelection:N=>{m&&m({templateType:N})},nextStep:async()=>{var N;if(i()){if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){const k=((N=c==null?void 0:c.email)==null?void 0:N.toLowerCase())||"",E=await WC(r.approvers,k);if(!E.success&&E.error){d(E.error.type,E.error.email,E.error.message);return}E.validatedApprovers&&a("approvers",E.validatedApprovers)}o()}},prevStep:()=>{l(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(N,k)=>{if(k){const E=N.documentId||N.document_id||"";g({fileName:N.originalFileName||N.fileName||"Document",fileType:N.fileType||N.file_type||"application/octet-stream",fileUrl:mu(E),fileSize:Number(N.fileSize||N.file_size||0),documentId:E})}else{const E=URL.createObjectURL(N);g({fileName:N.name,fileType:N.type||"application/octet-stream",fileUrl:E,fileSize:N.size,file:N})}},closePreview:()=>{x!=null&&x.fileUrl&&(x!=null&&x.file)&&URL.revokeObjectURL(x.fileUrl),g(null)}}}const Gd=[{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:_n,estimatedTime:"Variable",commonApprovers:[],suggestedSLA:3,priority:"medium",fields:{}},{id:"existing-template",name:"Existing Template",description:"Use a pre-configured template with predefined approval workflows, timelines, and requirements for faster processing",category:"Templates",icon:Ee,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];function KC({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+1e.jsx("span",{className:`${i+1===t?"font-semibold text-blue-600":""}`,"data-testid":`wizard-stepper-desktop-label-${i+1}`,children:n},i))})]})]})})}function YC({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:o,submitting:l,savingDraft:c,loadingDraft:d,isEditing:m}){return e.jsx("div",{className:"fixed sm:relative bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0 shadow-lg sm:shadow-none z-50","data-testid":"wizard-footer",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2 sm:gap-4 max-w-6xl mx-auto",children:[e.jsxs(R,{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(Rs,{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(R,{variant:"outline",onClick:o,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:d||l||c,"data-testid":"wizard-footer-save-draft-button",children:c?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),e.jsx("span",{children:m?"Updating...":"Saving..."})]}):e.jsx("span",{children:m?"Update Draft":"Save Draft"})}),t===s?e.jsx(R,{onClick:i,disabled:!a||d||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(Je,{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(Em,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(R,{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(Wt,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const Kd=t=>{switch(t){case"high":return e.jsx(Os,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Dt,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Zs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Dt,{className:"w-4 h-4 text-gray-600"})}};function ZC({templates:t,selectedTemplate:s,onSelectTemplate:a}){return e.jsxs(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"min-h-full flex flex-col items-center justify-center py-8","data-testid":"template-selection-step",children:[e.jsxs("div",{className:"text-center mb-12 max-w-3xl","data-testid":"template-selection-header",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4","data-testid":"template-selection-title",children:"Choose Your Request Type"}),e.jsx("p",{className:"text-lg text-gray-600","data-testid":"template-selection-description",children:"Start with a pre-built template for faster approvals, or create a custom request tailored to your needs."})]}),e.jsx("div",{className:"w-full max-w-6xl grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8","data-testid":"template-selection-grid",children:t.map(r=>e.jsx(Yt.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${r.id}`,children:e.jsxs(X,{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(le,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl flex items-center justify-center ${(s==null?void 0:s.id)===r.id?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${r.id}-icon`,children:e.jsx(r.icon,{className:`w-7 h-7 ${(s==null?void 0:s.id)===r.id?"text-blue-600":"text-gray-600"}`})}),(s==null?void 0:s.id)===r.id&&e.jsx(Yt.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},"data-testid":`template-card-${r.id}-selected-indicator`,children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center",children:e.jsx(er,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(ce,{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(se,{variant:"secondary",className:"text-xs","data-testid":`template-card-${r.id}-category`,children:r.category}),Kd(r.priority)]})]})]}),e.jsxs(J,{className:"pt-0 space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed line-clamp-2","data-testid":`template-card-${r.id}-description`,children:r.description}),e.jsx(It,{}),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(He,{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(Pt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[r.commonApprovers.length," approvers"]})]})]})]})]})},r.id))}),e.jsx(Hn,{children:s&&e.jsx(Yt.div,{initial:{opacity:0,y:20,height:0},animate:{opacity:1,y:0,height:"auto"},exit:{opacity:0,y:-20,height:0},transition:{duration:.3},className:"w-full max-w-6xl","data-testid":"template-details-card",children:e.jsxs(X,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(le,{children:e.jsxs(ce,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Hr,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-sla",children:[e.jsx(Q,{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(Q,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[Kd(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(Q,{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(Q,{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(se,{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 XC({className:t,...s}){return e.jsx($x,{"data-slot":"radio-group",className:ge("grid gap-3",t),...s})}function Yd({className:t,...s}){return e.jsx(Bx,{"data-slot":"radio-group-item",className:ge("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(Ux,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(Vg,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function JC({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"basic-information-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"basic-information-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-green-500 to-blue-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(Ee,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"basic-information-title",children:"Basic Information"}),e.jsxs("p",{className:"text-gray-600","data-testid":"basic-information-description",children:["Provide the essential details for your ",(s==null?void 0:s.name)||"request","."]})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"basic-information-form",children:[e.jsxs("div",{"data-testid":"basic-information-title-field",children:[e.jsx(Q,{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(we,{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(Q,{htmlFor:"description",className:"text-base font-semibold",children:"Detailed Description *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(gu,{value:t.description||"",onChange:r=>a("description",r),placeholder:"Provide comprehensive details about your request including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px","data-testid":"basic-information-description-textarea"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6","data-testid":"basic-information-priority-section",children:e.jsxs("div",{"data-testid":"basic-information-priority-field",children:[e.jsx(Q,{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(XC,{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(Yd,{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(wo,{className:"w-4 h-4 text-red-600"}),e.jsx(Q,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(se,{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(Yd,{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(He,{className:"w-4 h-4 text-blue-600"}),e.jsx(Q,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(se,{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(Q,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(we,{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(Q,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(Be,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Ve,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ue,{})}),e.jsxs(ze,{children:[e.jsx(W,{value:"USD",children:"USD ($)"}),e.jsx(W,{value:"EUR",children:"EUR (€)"}),e.jsx(W,{value:"GBP",children:"GBP (£)"}),e.jsx(W,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(Q,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(we,{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(Q,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(we,{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(Q,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(we,{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 QC(){const[t,s]=p.useState([]),[a,r]=p.useState(!1),n=p.useRef(null);return{searchResults:t,searchLoading:a,searchUsersDebounced:async(c,d=10)=>{if(n.current&&clearTimeout(n.current),!c||!c.startsWith("@")||c.length<2){s([]),r(!1);return}r(!0),n.current=setTimeout(async()=>{var m;try{const u=c.slice(1),x=((m=(await Ys(u,d)).data)==null?void 0:m.data)||[];s(x)}catch(u){console.error("User search failed:",u),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await ia({userId:c.userId,email:c.email,displayName:c.displayName,firstName:c.firstName,lastName:c.lastName,department:c.department,phone:c.phone,mobilePhone:c.mobilePhone,designation:c.designation,jobTitle:c.jobTitle,manager:c.manager,employeeId:c.employeeId,employeeNumber:c.employeeNumber,secondEmail:c.secondEmail,location:c.location})}catch(d){throw console.error("Failed to ensure user exists:",d),d}}}}function qC(){const[t,s]=p.useState({}),[a,r]=p.useState({}),n=p.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(l,c,d=10)=>{if(n.current[l]&&clearTimeout(n.current[l]),!c||!c.startsWith("@")||c.length<2){s(m=>({...m,[l]:[]})),r(m=>({...m,[l]:!1}));return}r(m=>({...m,[l]:!0})),n.current[l]=setTimeout(async()=>{var m;try{const u=c.slice(1),x=((m=(await Ys(u,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[l]:x}))}catch(u){console.error(`User search failed for index ${l}:`,u),s(h=>({...h,[l]:[]}))}finally{r(u=>({...u,[l]:!1}))}},300)},clearSearchForIndex:l=>{n.current[l]&&clearTimeout(n.current[l]),s(c=>({...c,[l]:[]})),r(c=>({...c,[l]:!1}))}}}function e1({formData:t,updateFormData:s,onValidationError:a}){var d;const{userSearchResults:r,userSearchLoading:n,searchUsersForIndex:i,clearSearchForIndex:o}=qC();p.useEffect(()=>{const m=t.approverCount||1,u=t.approvers||[];if(u.lengthm&&s("approvers",u.slice(0,m))},[t.approverCount,s]);const l=(m,u)=>{var f,j,w,b,C;const h=[...t.approvers],g=((f=h[m])==null?void 0:f.email)!==u;if(h[m]={...h[m],email:u,level:m+1,userId:g||(j=h[m])==null?void 0:j.userId,name:g||(w=h[m])==null?void 0:w.name,department:g||(b=h[m])==null?void 0:b.department,avatar:g||(C=h[m])==null?void 0:C.avatar},s("approvers",h),!u||!u.startsWith("@")||u.length<2){o(m);return}i(m,u,10)},c=async(m,u)=>{var h,x;try{if((h=t.approvers)==null?void 0:h.some((b,C)=>{var v,N;return C!==m&&(b.userId===u.userId||((v=b.email)==null?void 0:v.toLowerCase())===((N=u.email)==null?void 0:N.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((x=t.spectators)==null?void 0:x.some(b=>{var C,v;return b.userId===u.userId||((C=b.email)==null?void 0:C.toLowerCase())===((v=u.email)==null?void 0:v.toLowerCase())})){a({type:"error",email:u.email,message:"This user is already added as a spectator. A user cannot be both an approver and a spectator."});return}const j=await ia({userId:u.userId,email:u.email,displayName:u.displayName,firstName:u.firstName,lastName:u.lastName,department:u.department,phone:u.phone,mobilePhone:u.mobilePhone,designation:u.designation,jobTitle:u.jobTitle,manager:u.manager,employeeId:u.employeeId,employeeNumber:u.employeeNumber,secondEmail:u.secondEmail,location:u.location}),w=[...t.approvers];w[m]={...w[m],email:u.email,name:u.displayName||[u.firstName,u.lastName].filter(Boolean).join(" "),userId:j.userId,level:m+1},s("approvers",w),o(m)}catch(g){console.error("Failed to ensure user exists:",g),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"approval-workflow-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"approval-workflow-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-orange-500 to-red-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(Pt,{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(X,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(ua,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(je,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(J,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(Q,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{const m=t.approverCount||1,u=Math.max(1,m-1);s("approverCount",u),t.approvers.length>u&&s("approvers",t.approvers.slice(0,u))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(zg,{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(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{const m=t.approverCount||1,u=Math.min(10,m+1);s("approverCount",u)},disabled:(t.approverCount||1)>=10,"data-testid":"approval-workflow-increase-count",children:e.jsx(Ws,{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(X,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(ls,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(je,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsx("div",{className:"p-4 rounded-lg border-2 border-blue-200 bg-blue-50","data-testid":"approval-workflow-initiator-card",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center",children:e.jsx(St,{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(se,{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,u)=>{var f,j;const h=u+1,x=h===(t.approverCount||1),g=t.approvers[u]||{email:"",tat:""};return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${h}`,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:h})}),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 ",h]}),x&&e.jsx(se,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${h}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(Q,{htmlFor:`approver-${h}`,className:"text-sm font-medium",children:"Email Address *"}),g.email&&g.userId&&e.jsxs(se,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(we,{id:`approver-${h}`,type:"email",placeholder:"approver@royalenfield.com",value:g.email||"",onChange:w=>l(u,w.target.value),className:"h-10 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full","data-testid":`approval-workflow-approver-${h}-email-input`}),(n[u]||(((f=r[u])==null?void 0:f.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[u]?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:(j=r[u])==null?void 0:j.map(w=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>c(u,w),"data-testid":`approval-workflow-approver-${h}-search-result-${w.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:w.displayName||w.email}),e.jsx("div",{className:"text-xs text-gray-600",children:w.email})]},w.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${h}-tat-field`,children:[e.jsx(Q,{htmlFor:`tat-${h}`,className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(we,{id:`tat-${h}`,type:"number",placeholder:g.tatType==="days"?"7":"24",min:"1",max:g.tatType==="days"?"30":"720",value:g.tat||"",onChange:w=>{const b=[...t.approvers];b[u]={...b[u],tat:parseInt(w.target.value)||"",level:h,tatType:g.tatType||"hours"},s("approvers",b)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${h}-tat-input`}),e.jsxs(Be,{value:g.tatType||"hours",onValueChange:w=>{const b=[...t.approvers];b[u]={...b[u],tatType:w,level:h,tat:""},s("approvers",b)},"data-testid":`approval-workflow-approver-${h}-tat-type-select`,children:[e.jsx(Ve,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ue,{})}),e.jsxs(ze,{children:[e.jsx(W,{value:"hours",children:"Hours"}),e.jsx(W,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},h)})]})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Hr,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900 mb-1",children:"Approval Flow Summary"}),e.jsxs("p",{className:"text-sm text-blue-700",children:["Your request will follow this sequence: ",e.jsx("strong",{children:"You (Initiator)"})," → ",Array.from({length:t.approverCount||1},(m,u)=>`Level ${u+1} Approver`).join(" → "),". The final approver can close the request."]})]})]})}),e.jsx("div",{className:"p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-lg border border-emerald-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(He,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{var h;const m=((h=t.approvers)==null?void 0:h.reduce((x,g)=>{const f=Number(g.tat||0);return(g.tatType||"hours")==="days"?x+f:x+f/24},0))||0,u=Math.ceil(m);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[u," ",u===1?"Day":"Days"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Duration"})]})})()})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:(d=t.approvers)==null?void 0:d.map((m,u)=>{const h=Number(m.tat||0),g=(m.tatType||"hours")==="days"?h*24:h;return h?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",u+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[g," ",g===1?"hour":"hours"]})]})},u):null})}),(()=>{var h;const m=((h=t.approvers)==null?void 0:h.reduce((x,g)=>{const f=Number(g.tat||0);return(g.tatType||"hours")==="days"?x+f*24:x+f},0))||0,u=Math.ceil(m/8);return m===0?null:e.jsxs("div",{className:"bg-white/80 p-3 rounded border border-emerald-200",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[m,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children:u}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Working Days*"})]})]}),e.jsx("p",{className:"text-xs text-emerald-600 mt-2 text-center",children:"*Based on 8-hour working days"})]})})()]})]})]})})]})]})]})}function t1({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=p.useState(""),{searchResults:o,searchLoading:l,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=QC(),u=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},h=async g=>{var f,j;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const w=t.spectators.some(C=>{var v,N;return C.userId===g.userId||((v=C.email)==null?void 0:v.toLowerCase())===((N=g.email)==null?void 0:N.toLowerCase())}),b=(f=t.approvers)==null?void 0:f.some(C=>{var v,N;return C.userId===g.userId||((v=C.email)==null?void 0:v.toLowerCase())===((N=g.email)==null?void 0:N.toLowerCase())});if(w){a({type:"error",email:g.email,message:"This user is already added as a spectator."});return}if(b){a({type:"error",email:g.email,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}try{const C=await m(g),v={id:C.userId,userId:C.userId,name:C.displayName||g.email.split("@")[0],email:C.email,avatar:(C.displayName||C.email).substring(0,2).toUpperCase(),role:"Spectator",department:C.department||"",level:1,canClose:!1},N=[...t.spectators,v];s("spectators",N),i(""),d()}catch{a({type:"error",email:g.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const w=t.spectators.some(C=>{var v;return((v=C.email)==null?void 0:v.toLowerCase())===n.toLowerCase()}),b=(j=t.approvers)==null?void 0:j.some(C=>{var v;return((v=C.email)==null?void 0:v.toLowerCase())===n.toLowerCase()});if(w){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(b){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}}},x=g=>{const f=t.spectators.filter(j=>j.id!==g);s("spectators",f)};return e.jsxs(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"participants-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"participants-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-teal-500 to-green-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(rs,{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(X,{"data-testid":"participants-spectators-card",children:[e.jsxs(le,{children:[e.jsxs(ce,{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(rs,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(se,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(je,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2","data-testid":"participants-spectators-add-section",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-full",children:[e.jsx(we,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>u(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.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(g=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>h(g),"data-testid":`participants-spectators-search-result-${g.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:g.displayName||g.email}),e.jsx("div",{className:"text-xs text-gray-600",children:g.email})]},g.userId))})})]}),e.jsx(R,{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(Hr,{className:"w-3 h-3 flex-shrink-0"}),e.jsxs("span",{children:["Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users, or type email directly (will be validated against organization directory)"]})]})]}),e.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto","data-testid":"participants-spectators-list",children:t.spectators.map(g=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-teal-50 rounded-lg","data-testid":`participants-spectator-${g.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"h-6 w-6",children:e.jsx(Ut,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>x(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(ut,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function s1({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:o,onDocumentsToDeleteChange:l,onPreviewDocument:c,onDocumentErrors:d,fileInputRef:m}){const u=f=>{const j=Array.from(f.target.files||[]);if(j.length===0)return;const w=t.maxFileSizeMB*1024*1024,b=[],C=[];j.forEach(v=>{if(v.size>w){b.push({fileName:v.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(v.size/1048576).toFixed(2)}MB`});return}const N=v.name.toLowerCase(),k=N.substring(N.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(k)){b.push({fileName:v.name,reason:`File type "${k}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}C.push(v)}),C.length>0&&i([...a,...C]),b.length>0&&d&&d(b),f.target&&(f.target.value="")},h=f=>{const j=a.filter((w,b)=>b!==f);i(j)},x=f=>{l([...n,f])},g=(f,j=!1)=>{if(j){const w=(f.fileType||f.file_type||"").toLowerCase(),b=(f.originalFileName||f.fileName||"").toLowerCase();return w.includes("image")||w.includes("pdf")||b.endsWith(".jpg")||b.endsWith(".jpeg")||b.endsWith(".png")||b.endsWith(".gif")||b.endsWith(".pdf")}else{const w=(f.type||"").toLowerCase(),b=(f.name||"").toLowerCase();return w.includes("image")||w.includes("pdf")||b.endsWith(".jpg")||b.endsWith(".jpeg")||b.endsWith(".png")||b.endsWith(".gif")||b.endsWith(".pdf")}};return e.jsxs(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"documents-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"documents-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(ys,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"documents-title",children:"Documents & Attachments"}),e.jsx("p",{className:"text-gray-600","data-testid":"documents-description",children:"Upload supporting documents, files, and any additional materials for your request."})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"documents-content",children:[e.jsxs(X,{"data-testid":"documents-upload-card",children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Ee,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(je,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(J,{children:e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-gray-400 transition-colors","data-testid":"documents-upload-area",children:[e.jsx(ys,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"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:m,"data-testid":"documents-file-input"}),e.jsxs(R,{variant:"outline",size:"lg",type:"button",onClick:()=>{var f;return(f=m.current)==null?void 0:f.click()},"data-testid":"documents-browse-button",children:[e.jsx(Ws,{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(X,{"data-testid":"documents-existing-card",children:[e.jsx(le,{children:e.jsxs(ce,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(se,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(f=>!n.includes(f.documentId||f.document_id||"")).length," file",r.filter(f=>!n.includes(f.documentId||f.document_id||"")).length!==1?"s":""]})]})}),e.jsx(J,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(f=>{const j=f.documentId||f.document_id||"";return n.includes(j)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${j}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Ee,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:f.originalFileName||f.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:f.fileSize?(Number(f.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(f,!0)&&e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>c(f,!0),"data-testid":`documents-existing-${j}-preview`,children:e.jsx(rs,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>x(j),"data-testid":`documents-existing-${j}-delete`,children:e.jsx(ut,{className:"h-4 w-4 text-red-600"})})]})]},j)})})})]}),a.length>0&&e.jsxs(X,{"data-testid":"documents-new-card",children:[e.jsx(le,{children:e.jsxs(ce,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(se,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(J,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((f,j)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${j}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Ee,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:f.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(f.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(f,!1)&&e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>c(f,!1),"data-testid":`documents-new-${j}-preview`,children:e.jsx(rs,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>h(j),"data-testid":`documents-new-${j}-remove`,children:e.jsx(ut,{className:"h-4 w-4"})})]})]},j))})})]})]})]})}const a1=t=>{switch(t){case"high":return e.jsx(Os,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Dt,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Zs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Dt,{className:"w-4 h-4 text-gray-600"})}};function r1({formData:t,selectedTemplate:s}){return e.jsxs(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"review-submit-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"review-submit-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-green-500 to-teal-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(Ce,{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(X,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(le,{children:e.jsxs(ce,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(Em,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6","data-testid":"review-submit-overview-grid",children:[e.jsxs("div",{"data-testid":"review-submit-overview-type",children:[e.jsx(Q,{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(se,{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(Q,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[a1(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(Q,{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(Q,{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(X,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(le,{children:e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Ee,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(Q,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(ma,{content:t.description||""})})]}),t.amount&&e.jsxs("div",{className:"p-3 bg-blue-50 rounded-lg border border-blue-200","data-testid":"review-submit-basic-info-financial",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(_s,{className:"w-4 h-4 text-blue-600"}),e.jsx(Q,{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(X,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(Pt,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(je,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(J,{className:"space-y-6",children:e.jsx("div",{className:"space-y-4","data-testid":"review-submit-approval-levels",children:Array.from({length:t.approverCount||1},(a,r)=>{const n=r+1,i=n===(t.approverCount||1),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(se,{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(X,{"data-testid":"review-submit-participants-card",children:[e.jsx(le,{children:e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(rs,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(J,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(Q,{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(se,{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(X,{"data-testid":"review-submit-documents-card",children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(ys,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(je,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(J,{children:e.jsx("div",{className:"space-y-3","data-testid":"review-submit-documents-list",children:t.documents.map((a,r)=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-gray-50 rounded-lg border","data-testid":`review-submit-document-${r}`,children:[e.jsx(Ee,{className:"w-5 h-5 text-gray-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.name}),e.jsx("div",{className:"flex items-center gap-3 text-xs text-gray-500 mt-1",children:e.jsxs("span",{children:[(a.size/(1024*1024)).toFixed(2)," MB"]})})]})]},r))})})]}),e.jsx(X,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(J,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Ce,{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 n1({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(R,{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(Rs,{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 i1({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(Hn,{mode:"wait",children:t})})})}function o1({modal:t,onClose:s}){return e.jsx(nt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(tt,{className:"sm:max-w-md",children:[e.jsxs(it,{children:[e.jsxs(st,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Mt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["You cannot add yourself (",e.jsx("strong",{children:t.email}),") as an approver."]}),e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-amber-800",children:[e.jsx("strong",{children:"Why?"})," The initiator creates the request and cannot approve their own request. Please select a different user."]})})]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:t.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(_n,{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(Nt,{children:e.jsx(R,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function l1({modal:t,documentPolicy:s,onClose:a}){return e.jsx(nt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(tt,{className:"sm:max-w-lg",children:[e.jsxs(it,{children:[e.jsxs(st,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(Ie,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Mt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:t.errors.map((r,n)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3","data-testid":`document-error-${n}`,children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:r.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:r.reason})]},n))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",s.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types:"," ",s.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Nt,{children:e.jsx(R,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function Zd({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Oa(),i=ya(),o=n.requestId||a||"",l=r&&!!o,{user:c}=Gt(),{formData:d,updateFormData:m,selectedTemplate:u,setSelectedTemplate:h,loadingDraft:x,systemPolicy:g,documentPolicy:f,existingDocuments:j,setExistingDocuments:w}=DC(l,o,Gd),{currentStep:b,totalSteps:C,stepNames:v,isStepValid:N,nextStep:k,prevStep:E}=RC(l,u,d),[P,M]=p.useState([]),[y,A]=p.useState([]),L=p.useRef(null),{validationModal:K,policyViolationModal:O,documentErrorModal:$,openValidationModal:T,closeValidationModal:S,closePolicyViolationModal:D,openDocumentErrorModal:I,closeDocumentErrorModal:_}=PC(),{submitting:F,savingDraft:G,handleSubmit:B,handleSaveDraft:re}=OC({formData:d,selectedTemplate:u,documents:P,documentsToDelete:y,user:c,isEditing:l,editRequestId:o,onSubmit:s}),{showTemplateModal:ae,setShowTemplateModal:V,previewDocument:Y,selectTemplate:Z,handleTemplateSelection:U,nextStep:ee,prevStep:ie,handlePreviewDocument:de,closePreview:Ae}=GC({selectedTemplate:u,setSelectedTemplate:h,updateFormData:m,formData:d,currentStep:b,isStepValid:N,wizardNextStep:k,wizardPrevStep:E,user:c,openValidationModal:T,onSubmit:s}),We=p.useCallback(()=>{b===1||b===3||b===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):ie()},[b,t,i,ie]),Se=p.useRef(!0),Ye=p.useRef(!1);p.useEffect(()=>{Se.current&&d.documents&&d.documents.length>0&&!Ye.current&&(M(d.documents),Ye.current=!0),Se.current=!1},[d.documents]);const Ge=p.useRef(!1),Oe=p.useRef(P);p.useEffect(()=>{if(Ge.current){Ge.current=!1,Oe.current=P;return}Oe.current!==P&&(m("documents",P),Oe.current=P)},[P]);const ct=()=>{switch(b){case 1:return e.jsx(ZC,{templates:Gd,selectedTemplate:u,onSelectTemplate:Z});case 2:return e.jsx(JC,{formData:d,selectedTemplate:u,updateFormData:m});case 3:return e.jsx(e1,{formData:d,updateFormData:m,onValidationError:te=>T(te.type,te.email,te.message)});case 4:return e.jsx(t1,{formData:d,updateFormData:m,onValidationError:te=>T(te.type,te.email,te.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(s1,{documentPolicy:f,isEditing:l,documents:P,existingDocuments:j,documentsToDelete:y,onDocumentsChange:M,onExistingDocumentsChange:w,onDocumentsToDeleteChange:A,onPreviewDocument:de,onDocumentErrors:te=>I(te),fileInputRef:L});case 6:return e.jsx(r1,{formData:d,selectedTemplate:u});default:return null}};return x?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center","data-testid":"create-request-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading draft..."})]})}):e.jsxs("div",{className:"h-full flex flex-col bg-gradient-to-br from-gray-50 to-white","data-testid":"create-request",children:[e.jsx(n1,{isEditing:l,currentStep:b,totalSteps:C,stepNames:v,onBack:We}),e.jsx(KC,{currentStep:b,totalSteps:C,stepNames:v}),e.jsx(i1,{children:ct()}),e.jsx(YC,{currentStep:b,totalSteps:C,isStepValid:N(),onPrev:ie,onNext:ee,onSubmit:B,onSaveDraft:re,submitting:F,savingDraft:G,loadingDraft:x,isEditing:l}),e.jsx(NC,{open:ae,onClose:()=>V(!1),onSelectTemplate:U}),Y&&e.jsx(gl,{fileName:Y.fileName,fileType:Y.fileType,fileUrl:Y.fileUrl,fileSize:Y.fileSize,open:!!Y,onClose:Ae,onDownload:async()=>{if(Y.file){const te=document.createElement("a");te.href=Y.fileUrl,te.download=Y.fileName,document.body.appendChild(te),te.click(),document.body.removeChild(te)}else Y.documentId&&await _r(Y.documentId)},attachmentId:Y.documentId}),e.jsx(o1,{modal:K,onClose:S}),e.jsx(l1,{modal:$,documentPolicy:f,onClose:_}),e.jsx(Qh,{open:O.open,onClose:D,violations:O.violations,policyDetails:{maxApprovalLevels:g.maxApprovalLevels,maxParticipants:g.maxParticipants,allowSpectators:g.allowSpectators,maxSpectators:g.maxSpectators}})]})}function Jr({className:t,...s}){return e.jsx(Vx,{"data-slot":"tabs",className:ge("flex flex-col gap-2",t),...s})}function Qr({className:t,...s}){return e.jsx(zx,{"data-slot":"tabs-list",className:ge("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function gt({className:t,...s}){return e.jsx(Hx,{"data-slot":"tabs-trigger",className:ge("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 ft({className:t,...s}){return e.jsx(Wx,{"data-slot":"tabs-content",className:ge("flex-1 outline-none",t),...s})}function sp(t,s,a,r){const[n,i]=p.useState([]),[o,l]=p.useState(0),[c,d]=p.useState([]);return p.useEffect(()=>{if(!t){console.warn("[useRequestSocket] No requestIdentifier, cannot join socket room");return}let m=!0,u=t;return(async()=>{var f;try{const j=await hs.getWorkflowDetails(t);(f=j==null?void 0:j.workflow)!=null&&f.requestId&&m&&(u=j.workflow.requestId)}catch(j){console.error("[useRequestSocket] Failed to resolve UUID:",j)}if(!m)return;const h=Fr();if(!h){console.error("[useRequestSocket] Socket not available");return}const x=r==null?void 0:r.userId,g=()=>{Hi(h,u,x)};return h.connected?g():h.on("connect",g),()=>{m&&(h.off("connect",g),au(h,u))}})(),()=>{m=!1}},[t,r]),p.useEffect(()=>{!t||!s||(async()=>{try{const m=await Za(t),u=s.auditTrail||[],h=[...m,...u];h.sort((x,g)=>{const f=new Date(x.createdAt||x.created_at||x.timestamp||0).getTime(),j=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return f-j}),i(h)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),p.useEffect(()=>{if(!t)return;const m=Fr();if(!m)return;const u=x=>{a!=="worknotes"&&l(g=>g+1),(async()=>{try{const g=await Za(t),f=(s==null?void 0:s.auditTrail)||[],j=[...g,...f].sort((w,b)=>{const C=new Date(w.createdAt||w.created_at||w.timestamp||0).getTime(),v=new Date(b.createdAt||b.created_at||b.timestamp||0).getTime();return C-v});i(j)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},h=x=>{const g=x.type==="breach"?"⏰":x.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const f=await hs.getWorkflowDetails(t);f&&(Array.isArray(f.tatAlerts)&&f.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:x.message,icon:"/favicon.ico",tag:`tat-${x.requestId}-${x.type}`,requireInteraction:!1}))}catch(f){console.error("[useRequestSocket] Failed to refresh after TAT alert:",f)}})()};return m.on("noteHandler",u),m.on("worknote:new",u),m.on("tat:alert",h),()=>{m.off("noteHandler",u),m.off("worknote:new",u),m.off("tat:alert",h)}},[t,a,s]),p.useEffect(()=>{a==="worknotes"&&l(0)},[a]),{mergedMessages:n,unreadWorkNotes:o,workNoteAttachments:c,setWorkNoteAttachments:d}}async function Sr(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 he.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}}function ap(t,s){const[a,r]=p.useState(!1),[n,i]=p.useState(null),[o,l]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=p.useState({show:!1,errors:[]});p.useEffect(()=>{(async()=>{try{const g=await _a("DOCUMENT_POLICY"),f={};g.forEach(C=>{f[C.configKey]=C.configValue});const j=parseInt(f.MAX_FILE_SIZE_MB||"10"),b=(f.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(C=>C.trim().toLowerCase());l({maxFileSizeMB:j,allowedFileTypes:b})}catch(g){console.error("Failed to load document policy:",g)}})()},[]);const m=x=>{const g=o.maxFileSizeMB*1024*1024;if(x.size>g)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${o.maxFileSizeMB}MB. Current size: ${(x.size/(1024*1024)).toFixed(2)}MB`};const f=x.name.toLowerCase(),j=f.substring(f.lastIndexOf(".")+1);return o.allowedFileTypes.includes(j)?{valid:!0}:{valid:!1,reason:`File type "${j}" is not allowed. Allowed types: ${o.allowedFileTypes.join(", ")}`}},u=async x=>{var b,C;const g=x.target.files;if(!g||g.length===0)return;const f=Array.from(g),j=[],w=[];if(f.forEach(v=>{const N=m(v);N.valid?w.push(v):j.push({fileName:v.name,reason:N.reason||"Unknown validation error"})}),j.length>0&&d({show:!0,errors:j}),w.length===0){x.target&&(x.target.value="");return}r(!0);try{const v=w[0],N=t==null?void 0:t.requestId;if(!N){ne.error("Request ID not found");return}v&&await Sr(v,N,"SUPPORTING"),await s(),w.length{const x=document.createElement("input");x.type="file",x.accept=o.allowedFileTypes.map(g=>`.${g}`).join(","),x.onchange=u,x.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:o,documentError:c,setDocumentError:d}}function c1(t,s,a,r,n,i,o){const[l,c]=p.useState(""),[d,m]=p.useState(!1),[u,h]=p.useState(!1),[x,g]=p.useState(!1),f=async()=>{try{const{getConclusion:b}=await pn(async()=>{const{getConclusion:v}=await import("./conclusionApi-Dx0VmMvk.js");return{getConclusion:v}},__vite__mapDeps([0,1,2,3,4,5,6,7])),C=await b(t.requestId||s);C&&C.aiGeneratedRemark&&(c(C.finalRemark||C.aiGeneratedRemark),g(!!C.aiGeneratedRemark))}catch{}},j=async()=>{try{m(!0);const{generateConclusion:b}=await pn(async()=>{const{generateConclusion:v}=await import("./conclusionApi-Dx0VmMvk.js");return{generateConclusion:v}},__vite__mapDeps([0,1,2,3,4,5,6,7])),C=await b(t.requestId||s);c(C.aiGeneratedRemark),g(!0)}catch(b){console.error("[useConclusionRemark] AI generation failed:",b),c(""),g(!1)}finally{m(!1)}},w=async()=>{var C,v;const b=l.replace(/<[^>]*>/g,"").trim();if(!b){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),o==null||o(!0);return}if(b.length>2e3){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark exceeds 2000 characters limit"}),o==null||o(!0);return}try{h(!0);const{finalizeConclusion:N}=await pn(async()=>{const{finalizeConclusion:k}=await import("./conclusionApi-Dx0VmMvk.js");return{finalizeConclusion:k}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await N(t.requestId||s,l),i==null||i({success:!0,title:"Request Closed with Successful Completion",message:"The request has been finalized and moved to Closed Requests."}),o==null||o(!0),await r(),setTimeout(()=>{n?(n(),setTimeout(()=>{window.location.hash="#/closed-requests"},100)):window.location.hash="#/closed-requests"},2e3)}catch(N){i==null||i({success:!1,title:"Error",message:((v=(C=N.response)==null?void 0:C.data)==null?void 0:v.error)||"Failed to finalize conclusion"}),o==null||o(!0)}finally{h(!1)}};return p.useEffect(()=>{((t==null?void 0:t.status)==="approved"||(t==null?void 0:t.status)==="rejected")&&a&&!l&&f()},[t==null?void 0:t.status,a]),{conclusionRemark:l,setConclusionRemark:c,conclusionLoading:d,conclusionSubmitting:u,aiGenerated:x,handleGenerateConclusion:j,handleFinalizeConclusion:w}}function rp(t,s,a){const[r,n]=p.useState(!1),[i,o]=p.useState(!1),[l,c]=p.useState(!1),[d,m]=p.useState(!1),[u,h]=p.useState(!1),[x,g]=p.useState(!1),[f,j]=p.useState(null),[w,b]=p.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:o,showAddApproverModal:l,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:u,setShowSkipApproverModal:h,showActionStatusModal:x,setShowActionStatusModal:g,skipApproverData:f,setSkipApproverData:j,actionStatus:w,setActionStatus:b,handleApproveConfirm:async P=>{var y,A;const M=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!M){alert("Approval level not found");return}await Wi(t,M,P||""),await a(),(y=window==null?void 0:window.closeModal)==null||y.call(window),(A=window==null?void 0:window.toast)==null||A.call(window,"Approved successfully")},handleRejectConfirm:async P=>{var y,A;if(!(P!=null&&P.trim())){alert("Comments & remarks are required");return}const M=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!M){alert("Approval level not found");return}await Gi(t,M,P.trim(),P.trim()),await a(),(y=window==null?void 0:window.closeModal)==null||y.call(window),(A=window==null?void 0:window.toast)==null||A.call(window,"Rejected successfully")},handleAddApprover:async(P,M,y)=>{var A,L;try{await cu(t,P,M,y),await a(),c(!1),b==null||b({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${y} with ${M}h TAT`}),g==null||g(!0)}catch(K){throw b==null||b({success:!1,title:"Failed to Add Approver",message:((L=(A=K==null?void 0:K.response)==null?void 0:A.data)==null?void 0:L.error)||"Failed to add approver. Please try again."}),g==null||g(!0),K}},handleSkipApprover:async P=>{var M,y;if(f)try{await Qy(t,f.levelId,P),await a(),h(!1),j(null),b==null||b({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),g==null||g(!0)}catch(A){throw b==null||b({success:!1,title:"Failed to Skip Approver",message:((y=(M=A==null?void 0:A.response)==null?void 0:M.data)==null?void 0:y.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),A}},handleAddSpectator:async P=>{var M,y;try{await du(t,P),await a(),m(!1),b==null||b({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),g==null||g(!0)}catch(A){throw b==null||b({success:!1,title:"Failed to Add Spectator",message:((y=(M=A==null?void 0:A.response)==null?void 0:M.data)==null?void 0:y.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),A}}}}const d1=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 Xd({document:t,onPreview:s,onDownload:a,showPreview:r=!0,testId:n="document-card"}){return e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors","data-testid":`${n}-${t.documentId}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Ee,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900","data-testid":`${n}-name`,children:t.name}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${n}-metadata`,children:[t.size," • Uploaded by ",t.uploadedBy," on ",Qt(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&d1(t.fileType)&&s&&e.jsx(R,{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(rs,{className:"w-4 h-4"})}),a&&e.jsx(R,{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(ss,{className:"w-4 h-4"})})]})]})}function m1({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(X,{children:[e.jsx(le,{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(ce,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ee,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx(je,{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(R,{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(ys,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a?"Uploading...":t.status==="closed"?"Closed":"Upload",e.jsx("span",{className:"hidden sm:inline",children:t.status==="closed"?"":"Document"})]}),e.jsxs("p",{className:"text-xs text-gray-500 whitespace-nowrap",children:["Max ",r.maxFileSizeMB,"MB"]})]})]})}),e.jsx(J,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((l,c)=>e.jsx(Xd,{document:l,onPreview:d=>i(d),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(X,{children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ps,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(je,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(J,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((l,c)=>e.jsx(Xd,{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:d=>i(d),onDownload:async d=>{const{downloadWorkNoteAttachment:m}=require("@/services/workflowApi");await m(d)},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"})})]})]})}const u1=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"}}},h1=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending"};case"paused":return{color:"bg-gray-400 text-gray-100 border-gray-500",label:"paused"};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}}},p1=t=>{switch(t){case"approval":case"approved":return e.jsx(Ce,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(yt,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(Ps,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(Zt,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(Ln,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Ee,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(He,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(In,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(as,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(Vt,{className:"w-5 h-5 text-gray-600"})}};function x1({request:t}){return e.jsxs(X,{children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Vt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(je,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(J,{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:p1(s.type)})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4 shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-gray-900",children:s.action}),e.jsx("span",{className:"text-xs text-gray-500 whitespace-nowrap ml-4",children:Qt(s.timestamp)})]}),e.jsx("div",{className:"text-sm text-gray-600 leading-relaxed",children:e.jsx("p",{className:"whitespace-pre-line break-words",children:s.details})})]})})]},a)):e.jsxs("div",{className:"text-center py-12","data-testid":"no-activity",children:[e.jsx(Vt,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No activity recorded yet"}),e.jsx("p",{className:"text-xs text-gray-400 mt-2",children:"Actions and updates will appear here"})]})})})]})}function np({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(nt,{open:t,onOpenChange:s,children:e.jsxs(tt,{className:"sm:max-w-md",children:[e.jsx(it,{children:e.jsxs(st,{className:"flex items-center gap-2",children:[a?e.jsx(Ce,{className:"w-5 h-5 text-green-600"}):e.jsx(Ie,{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(Ce,{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(yt,{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(Nt,{children:e.jsx(R,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function ip({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=p.useState(""),[o,l]=p.useState(!1),[c,d]=p.useState([]),[m,u]=p.useState(!1),[h,x]=p.useState(null),g=p.useRef(null),f=p.useRef(null),[j,w]=p.useState({open:!1,type:"error",email:"",message:""}),[b,C]=p.useState({open:!1,violations:[]}),[v,N]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});p.useEffect(()=>{t&&(async()=>{var A;try{const L=await _a("WORKFLOW_SHARING"),K=await _a("TAT_SETTINGS"),O=[...L,...K],$={};O.forEach(T=>{$[T.configKey]=T.configValue}),N({maxApprovalLevels:parseInt($.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt($.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((A=$.ALLOW_ADD_SPECTATOR)==null?void 0:A.toLowerCase())==="true",maxSpectators:parseInt($.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(L){console.error("Failed to load system policy:",L)}})()},[t]);const k=async()=>{var S,D;const y=n.trim().toLowerCase();if(!y){w({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(y)){w({open:!0,type:"error",email:y,message:"Please enter a valid email address"});return}const L=r.find(I=>(I.email||"").toLowerCase()===y);if(L){const I=((S=L.participantType)==null?void 0:S.toUpperCase())||"PARTICIPANT",_=L.name||y;if(I==="INITIATOR"){w({open:!0,type:"error",email:y,message:`${_} is the request initiator and cannot be added as a spectator.`});return}else if(I==="APPROVER"){w({open:!0,type:"error",email:y,message:`${_} is already an approver on this request and cannot be added as a spectator.`});return}else if(I==="SPECTATOR"){w({open:!0,type:"error",email:y,message:`${_} is already a spectator on this request.`});return}else{w({open:!0,type:"error",email:y,message:`${_} is already a participant on this request.`});return}}const K=[];v.allowSpectators||K.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const $=r.filter(I=>(I.participantType||"").toUpperCase()==="SPECTATOR").length;$>=v.maxSpectators&&K.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:$,maxValue:v.maxSpectators});const T=r.length+1;if(T>v.maxParticipants&&K.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:T,maxValue:v.maxParticipants}),K.length>0){C({open:!0,violations:K});return}if(!h||h.email.toLowerCase()!==y)try{const _=((D=(await Ys(y,1)).data)==null?void 0:D.data)||[];if(_.length===0){w({open:!0,type:"not-found",email:y,message:""});return}const F=_[0];await ia({userId:F.userId,email:F.email,displayName:F.displayName,firstName:F.firstName,lastName:F.lastName,department:F.department,phone:F.phone,mobilePhone:F.mobilePhone,designation:F.designation,jobTitle:F.jobTitle,manager:F.manager,employeeId:F.employeeId,employeeNumber:F.employeeNumber,secondEmail:F.secondEmail,location:F.location})}catch(I){console.error("Failed to validate spectator:",I),w({open:!0,type:"error",email:y,message:"Failed to validate user. Please try again."});return}try{l(!0),await a(y),i(""),x(null),s()}catch(I){console.error("Failed to add spectator:",I)}finally{l(!1)}},E=()=>{o||(i(""),x(null),d([]),u(!1),s())};p.useEffect(()=>{c.length>0&&f.current&&f.current.scrollTo({top:f.current.scrollHeight,behavior:"smooth"})},[c.length]),p.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const P=y=>{if(i(y),h&&h.email.toLowerCase()!==y.toLowerCase()&&x(null),g.current&&clearTimeout(g.current),!y||!y.startsWith("@")||y.length<2){d([]),u(!1);return}u(!0),g.current=setTimeout(async()=>{var A;try{const L=y.slice(1),O=((A=(await Ys(L,10)).data)==null?void 0:A.data)||[];d(O)}catch(L){console.error("Search failed:",L),d([])}finally{u(!1)}},300)},M=async y=>{try{await ia({userId:y.userId,email:y.email,displayName:y.displayName,firstName:y.firstName,lastName:y.lastName,department:y.department,phone:y.phone,mobilePhone:y.mobilePhone,designation:y.designation,jobTitle:y.jobTitle,manager:y.manager,employeeId:y.employeeId,employeeNumber:y.employeeNumber,secondEmail:y.secondEmail,location:y.location}),i(y.email),x(y),d([]),u(!1)}catch(A){console.error("Failed to ensure user exists:",A),w({open:!0,type:"error",email:y.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(nt,{open:t,onOpenChange:E,children:[e.jsxs(tt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:E,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:o,children:[e.jsx(ut,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(it,{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(rs,{className:"w-5 h-5 text-purple-600"})}),e.jsx(st,{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(Co,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(we,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:y=>P(y.target.value),className:"pl-10 h-11 border-gray-300",disabled:o,autoFocus:!0}),(m||c.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:m?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):c.length>0?e.jsx("ul",{className:"divide-y",children:c.map(y=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>M(y),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Bt,{className:"h-8 w-8",children:e.jsx(Ut,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(y.displayName||y.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:y.displayName||[y.firstName,y.lastName].filter(Boolean).join(" ")||y.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:y.email}),y.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:y.designation})]})]})},y.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(R,{type:"button",variant:"outline",onClick:E,className:"flex-1 h-11 border-gray-300",disabled:o,children:"Cancel"}),e.jsxs(R,{type:"button",onClick:k,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:o||!n.trim(),children:[e.jsx(rs,{className:"w-4 h-4 mr-2"}),o?"Adding...":"Add Spectator"]})]})]}),e.jsx(nt,{open:j.open,onOpenChange:y=>w(A=>({...A,open:y})),children:e.jsxs(tt,{className:"sm:max-w-md",children:[e.jsxs(it,{children:[e.jsx(st,{className:"flex items-center gap-2",children:j.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Mt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[j.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:j.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(_n,{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."]})})]}),j.type==="error"&&e.jsxs(e.Fragment,{children:[j.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:j.email}),"."]}),j.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:j.message})})]})]})})]}),e.jsx(Nt,{children:e.jsx(R,{onClick:()=>w(y=>({...y,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(Qh,{open:b.open,onClose:()=>C({open:!1,violations:[]}),violations:b.violations,policyDetails:{maxApprovalLevels:v.maxApprovalLevels,maxParticipants:v.maxParticipants,allowSpectators:v.allowSpectators,maxSpectators:v.maxSpectators}})]})}function op({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[]}){const[i,o]=p.useState(""),[l,c]=p.useState(24),[d,m]=p.useState(null),[u,h]=p.useState(!1),[x,g]=p.useState([]),[f,j]=p.useState(!1),[w,b]=p.useState(null),C=p.useRef(null),v=p.useRef(null),[N,k]=p.useState({open:!1,type:"error",email:"",message:""}),E=n.filter(T=>T&&(T.status==="approved"||T.status==="rejected"||T.status==="skipped")),P=Math.max(1,E.length+1),M=Math.max(1,n.length+1),y=M>=P?Array.from({length:M-P+1},(T,S)=>P+S):[P];p.useEffect(()=>{y.length>0&&d===null&&m(y[0]||null)},[y.length,d]);const A=async()=>{var I,_;const T=i.trim().toLowerCase();if(!T){k({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(T)){k({open:!0,type:"error",email:T,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(!d){k({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(d(F.email||"").toLowerCase()===T);if(D){const F=((I=D.participantType)==null?void 0:I.toUpperCase())||"PARTICIPANT",G=D.name||T;if(F==="INITIATOR"){k({open:!0,type:"error",email:T,message:`${G} is the request initiator and cannot be added as an approver.`});return}else if(F==="APPROVER"){k({open:!0,type:"error",email:T,message:`${G} is already an approver on this request.`});return}else if(F==="SPECTATOR"){k({open:!0,type:"error",email:T,message:`${G} 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:T,message:`${G} is already a participant on this request.`});return}}if(!w||w.email.toLowerCase()!==T)try{const G=((_=(await Ys(T,1)).data)==null?void 0:_.data)||[];if(G.length===0){k({open:!0,type:"not-found",email:T,message:""});return}const B=G[0];await ia({userId:B.userId,email:B.email,displayName:B.displayName,firstName:B.firstName,lastName:B.lastName,department:B.department,phone:B.phone,mobilePhone:B.mobilePhone,designation:B.designation,jobTitle:B.jobTitle,manager:B.manager,employeeId:B.employeeId,employeeNumber:B.employeeNumber,secondEmail:B.secondEmail,location:B.location})}catch(F){console.error("Failed to validate approver:",F),k({open:!0,type:"error",email:T,message:"Failed to validate user. Please try again."});return}try{h(!0),await a(T,l,d),o(""),c(24),m(null),b(null),s()}catch(F){console.error("Failed to add approver:",F)}finally{h(!1)}},L=()=>{u||(o(""),c(24),m(null),b(null),g([]),j(!1),s())},K=T=>{const S=T.toLowerCase();return S==="approved"?e.jsx(Ce,{className:"w-4 h-4 text-green-600"}):S==="rejected"?e.jsx(yt,{className:"w-4 h-4 text-red-600"}):S==="skipped"?e.jsx(Ie,{className:"w-4 h-4 text-orange-600"}):S==="in-review"||S==="pending"?e.jsx(He,{className:"w-4 h-4 text-blue-600"}):e.jsx(He,{className:"w-4 h-4 text-gray-400"})};p.useEffect(()=>{x.length>0&&v.current&&v.current.scrollTo({top:v.current.scrollHeight,behavior:"smooth"})},[x.length]),p.useEffect(()=>()=>{C.current&&clearTimeout(C.current)},[]);const O=T=>{if(o(T),w&&w.email.toLowerCase()!==T.toLowerCase()&&b(null),C.current&&clearTimeout(C.current),!T||!T.startsWith("@")||T.length<2){g([]),j(!1);return}j(!0),C.current=setTimeout(async()=>{var S;try{const D=T.slice(1),_=((S=(await Ys(D,10)).data)==null?void 0:S.data)||[];g(_)}catch(D){console.error("Search failed:",D),g([])}finally{j(!1)}},300)},$=async T=>{try{await ia({userId:T.userId,email:T.email,displayName:T.displayName,firstName:T.firstName,lastName:T.lastName,department:T.department,phone:T.phone,mobilePhone:T.mobilePhone,designation:T.designation,jobTitle:T.jobTitle,manager:T.manager,employeeId:T.employeeId,employeeNumber:T.employeeNumber,secondEmail:T.secondEmail,location:T.location}),o(T.email),b(T),g([]),j(!1)}catch(S){console.error("Failed to ensure user exists:",S),k({open:!0,type:"error",email:T.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(nt,{open:t,onOpenChange:L,children:[e.jsxs(tt,{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:u,children:[e.jsx(ut,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(it,{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(Pt,{className:"w-5 h-5 text-blue-600"})}),e.jsx(st,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:v,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(Q,{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(T=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${T.status==="approved"?"bg-green-100 border border-green-200":T.status==="rejected"?"bg-red-100 border border-red-200":T.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:T.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:T.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[T.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[K(T.status),e.jsx(se,{variant:"outline",className:`text-xs ${T.status==="approved"?"bg-green-50 text-green-700 border-green-300":T.status==="rejected"?"bg-red-50 text-red-700 border-red-300":T.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:T.status})]})]},T.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:["ℹ️ New approver can only be added at level ",P," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(Be,{value:(d==null?void 0:d.toString())||"",onValueChange:T=>m(Number(T)),disabled:u,children:[e.jsx(Ve,{className:"h-11 border-gray-300",children:e.jsx(Ue,{placeholder:"Select level"})}),e.jsx(ze,{children:y.map(T=>e.jsx(W,{value:T.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",T]}),T<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",T,")"]})]})},T))})]}),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(Q,{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(we,{type:"number",min:"1",max:"720",value:l,onChange:T=>c(Number(T.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(He,{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(Co,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(we,{type:"text",placeholder:"@username or user@example.com",value:i,onChange:T=>O(T.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(f||x.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:f?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):x.length>0?e.jsx("ul",{className:"divide-y",children:x.map(T=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>$(T),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Bt,{className:"h-8 w-8",children:e.jsx(Ut,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(T.displayName||T.email).split(" ").map(S=>S[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:T.displayName||[T.firstName,T.lastName].filter(Boolean).join(" ")||T.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:T.email}),T.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:T.designation})]})]})},T.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(R,{type:"button",variant:"outline",onClick:L,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(R,{type:"button",onClick:A,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!i.trim()||!d||!l,children:[e.jsx(Pt,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${d||"?"}`]})]})]}),e.jsx(nt,{open:N.open,onOpenChange:T=>k(S=>({...S,open:T})),children:e.jsxs(tt,{className:"sm:max-w-md",children:[e.jsxs(it,{children:[e.jsx(st,{className:"flex items-center gap-2",children:N.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Mt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[N.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:N.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(_n,{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."]})})]}),N.type==="error"&&e.jsxs(e.Fragment,{children:[N.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:N.email}),"."]}),N.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:N.message})})]})]})})]}),e.jsx(Nt,{children:e.jsx(R,{onClick:()=>k(T=>({...T,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const g1=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"}},f1=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},y1=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)?'@'+a+"":s}).replace(/\n/g,"
"),b1=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",Jd=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Ee,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(Gg,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Ee,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Ee,{className:`${s} text-blue-600`}):a.includes("image")||a.includes("png")||a.includes("jpg")||a.includes("jpeg")||a.includes("gif")||a.includes("webp")?e.jsx(Bi,{className:`${s} text-purple-600`}):e.jsx(In,{className:`${s} text-gray-600`})};function lp({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:o=!1,isSpectator:l=!1,currentLevels:c=[],onAddApprover:d}){const m=Oa(),u=t||m.requestId||"",[h,x]=p.useState(""),[g,f]=p.useState(""),[j,w]=p.useState(!1),[b,C]=p.useState([]),[v,N]=p.useState(!1),[k,E]=p.useState([]),[P,M]=p.useState(null),[y,A]=p.useState(null),[L,K]=p.useState(!1),[O,$]=p.useState(!1),[T,S]=p.useState(!1),[D,I]=p.useState({success:!0,title:"",message:""}),_=p.useRef(null),F=p.useRef(null),G=p.useRef(null),B=p.useRef(!1),[re,ae]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[V,Y]=p.useState({open:!1,errors:[]}),Z=p.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[U,ee]=p.useState([]),ie=U.filter(H=>H.status==="online"),de=b.filter(H=>H.content.toLowerCase().includes(g.toLowerCase())||H.user.name.toLowerCase().includes(g.toLowerCase())),Ae=p.useMemo(()=>l!==void 0?l:!P||U.length===0?!1:U.some(H=>{const me=H.userId||H.user_id,z=(H.role||"").toString().toUpperCase(),fe=(H.participantType||H.participant_type||"").toString().toUpperCase();return me===P&&(z==="SPECTATOR"||fe==="SPECTATOR")}),[l,P,U]);p.useEffect(()=>{},[U]),p.useEffect(()=>{!u||!P||s||(async()=>{try{const H=await Za(u),me=Array.isArray(H)?H.map(z=>{const fe=z.userId||z.user_id;return{id:z.noteId||z.id||String(Math.random()),user:{name:z.userName||"User",avatar:(z.userName||"U").slice(0,2).toUpperCase(),role:z.userRole||"Participant"},content:z.message||"",timestamp:z.createdAt||new Date().toISOString(),isCurrentUser:fe===P,attachments:Array.isArray(z.attachments)?z.attachments.map(ye=>({attachmentId:ye.attachmentId||ye.attachment_id,name:ye.fileName||ye.file_name||ye.name,fileName:ye.fileName||ye.file_name||ye.name,url:ye.storageUrl||ye.storage_url||ye.url||"#",type:ye.fileType||ye.file_type||ye.type||"file",fileType:ye.fileType||ye.file_type||ye.type||"file",fileSize:ye.fileSize||ye.file_size})):void 0}}):[];C(me)}catch(H){console.error("[WorkNoteChat] Failed to load messages:",H)}})()},[u,P,s]);const We=p.useMemo(()=>{const H=[];return b.forEach(me=>{me.attachments&&me.attachments.length>0&&me.attachments.forEach(z=>{H.push({attachmentId:z.attachmentId||z.attachment_id,name:z.fileName||z.file_name||z.name||"Untitled",fileName:z.fileName||z.file_name||z.name||"Untitled",size:z.fileSize||z.file_size,type:z.fileType||z.file_type||z.type||"file",uploadedBy:me.user.name,uploadedAt:me.timestamp,url:z.storageUrl||z.storage_url||z.url||"#"})})}),H},[b]);p.useEffect(()=>{i&&We.length>=0&&i(We)},[We,i]);const Se=p.useMemo(()=>U.map(H=>({email:(H.email||"").toLowerCase(),participantType:H.role==="Initiator"?"INITIATOR":H.role==="Approver"?"APPROVER":H.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:H.name})),[U]),Ye=H=>{if(!H)return"Participant";switch(H.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return H.charAt(0).toUpperCase()+H.slice(1).toLowerCase()}},Ge=()=>{var H;(H=_.current)==null||H.scrollIntoView({behavior:"smooth"})};p.useEffect(()=>{Ge()},[b]);const Oe=H=>{switch(H.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return H.charAt(0).toUpperCase()+H.slice(1).toLowerCase()}};p.useEffect(()=>{B.current||u&&(async()=>{try{const H=await xs(u),me=Array.isArray(H==null?void 0:H.participants)?H.participants:[];if(me.length===0)return;const z=me.map(be=>{const Me=be.participantType||be.participant_type||"participant",ke=be.userId||be.user_id||"";return{name:be.userName||be.user_name||be.user_email||be.userEmail||"User",avatar:(be.userName||be.user_name||be.user_email||"U").toString().split(" ").map(Le=>Le[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Oe(Me.toString()),status:"offline",email:be.userEmail||be.user_email||"",permissions:["read","write","mention"],userId:ke}});B.current=!0,ee(z);let fe=0;const ye=3,Re=()=>{G.current&&G.current.connected?(G.current.emit("request:online-users",{requestId:u}),fe++,fe()=>{u&&(B.current=!1)},[u]),p.useEffect(()=>{const H=localStorage.getItem("userData");if(H)try{const me=JSON.parse(H),z=(me==null?void 0:me.id)||(me==null?void 0:me.userId)||(me==null?void 0:me.user_id)||null;M(z)}catch(me){console.error("[WorkNoteChat] Failed to parse userData:",me)}},[]),p.useEffect(()=>{(async()=>{try{const me=await _a("DOCUMENT_POLICY"),z={};me.forEach(be=>{z[be.configKey]=be.configValue});const fe=parseInt(z.MAX_FILE_SIZE_MB||"10"),Re=(z.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(be=>be.trim().toLowerCase());ae({maxFileSizeMB:fe,allowedFileTypes:Re})}catch(me){console.error("Failed to load document policy:",me)}})()},[]),p.useEffect(()=>{if(!P)return;let H=u;return(async()=>{var me;try{const z=await xs(u);(me=z==null?void 0:z.workflow)!=null&&me.requestId&&(H=z.workflow.requestId)}catch{}try{const z=Fr();r?ee(Ke=>Ke.map(at=>at.userId===P?{...at,status:"online"}:at)):(Hi(z,H,P),ee(Ke=>Ke.map(at=>at.userId===P?{...at,status:"online"}:at)));const fe=Ke=>{const $e=(Ke==null?void 0:Ke.note)||Ke;if(!$e)return;const at=$e.noteId||$e.id;C(zt=>{if(zt.some(ot=>ot.id===at))return zt;const vt=$e.userName||$e.user_name||"User",Cs=$e.userRole||$e.user_role,Is=Ye(Cs),Js=$e.userId||$e.user_id,Qs={id:at||String(Date.now()),user:{name:vt,avatar:vt.split(" ").map(ot=>ot[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Is},content:$e.message||"",timestamp:$e.createdAt||new Date().toISOString(),isCurrentUser:Js===P,attachments:Array.isArray($e.attachments)?$e.attachments.map(ot=>({attachmentId:ot.attachmentId||ot.attachment_id,name:ot.fileName||ot.file_name||ot.name,fileName:ot.fileName||ot.file_name||ot.name,url:ot.storageUrl||ot.storage_url||ot.url||"#",type:ot.fileType||ot.file_type||ot.type||"file",fileType:ot.fileType||ot.file_type||ot.type||"file",fileSize:ot.fileSize||ot.file_size})):void 0};return[...zt,Qs]})},ye=Ke=>{ee($e=>$e.length===0||!$e.find(vt=>vt.userId===Ke.userId)?$e:$e.map(vt=>vt.userId===Ke.userId?{...vt,status:"online"}:vt))},Re=Ke=>{Ke.userId!==P&&ee($e=>$e.length===0||!$e.find(vt=>vt.userId===Ke.userId)?$e:$e.map(vt=>vt.userId===Ke.userId?{...vt,status:"offline"}:vt))},be=Ke=>{ee($e=>$e.length===0?$e:$e.map(zt=>{const vt=zt.userId||"";if(vt===P)return{...zt,status:"online"};const Is=Ke.userIds.includes(vt);return{...zt,status:Is?"online":"offline"}}))},Me=()=>{ee(Ke=>Ke.map(at=>at.userId===P?{...at,status:"online"}:at)),r||Hi(z,H,P),B.current&&(z.emit("request:online-users",{requestId:H}),setTimeout(()=>z.emit("request:online-users",{requestId:H}),300),setTimeout(()=>z.emit("request:online-users",{requestId:H}),800))},ke=Ke=>{console.error("[WorkNoteChat] ❌ Socket error:",Ke)},Le=Ke=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",Ke),ee($e=>$e.map(at=>at.userId===P?at:{...at,status:"offline"}))},Xt=Ke=>{Ke.includes("presence")||Ke.includes("worknote")||Ke.includes("request")};z.on("connect",Me),z.on("disconnect",Le),z.on("error",ke),z.on("worknote:new",fe),z.on("presence:join",ye),z.on("presence:leave",Re),z.on("presence:online",be),z.onAny(Xt),G.current=z,z.connected&&B.current&&(z.emit("request:online-users",{requestId:H}),setTimeout(()=>{z.emit("request:online-users",{requestId:H})},300),setTimeout(()=>{z.emit("request:online-users",{requestId:H})},800),setTimeout(()=>{z.emit("request:online-users",{requestId:H})},1500));const wt=()=>{z.off("connect",Me),z.off("disconnect",Le),z.off("error",ke),z.off("worknote:new",fe),z.off("presence:join",ye),z.off("presence:leave",Re),z.off("presence:online",be),z.offAny(Xt),r||au(z,H),G.current=null};window.__wn_cleanup=wt}catch{}})(),()=>{var me;try{(me=window.__wn_cleanup)==null||me.call(window)}catch{}}},[u,P,r]);const ct=async()=>{if(h.trim()||k.length>0){const H=qt(h),me=H.map(ye=>{const Re=U.find(be=>be.name.toLowerCase().includes(ye.toLowerCase()));return Re==null?void 0:Re.userId}).filter(Boolean),z=k.map(ye=>({name:ye.name,url:URL.createObjectURL(ye),type:ye.type.split("/")[1]||"file"})),fe={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:H,isHighPriority:h.includes("!important")||h.includes("urgent"),attachments:z.length>0?z:void 0,isCurrentUser:!0};if(a)try{await a(h,k)}catch{}else try{await lu(u,{message:h,mentions:me},k);const ye=await Za(u),Re=Array.isArray(ye)?ye.map(be=>{const Me=be.userId||be.user_id;return{id:be.noteId||be.id||String(Math.random()),user:{name:be.userName||"User",avatar:(be.userName||"U").slice(0,2).toUpperCase(),role:be.userRole||"Participant"},content:be.message||"",timestamp:be.createdAt||new Date().toISOString(),isCurrentUser:Me===P,attachments:Array.isArray(be.attachments)?be.attachments.map(ke=>({attachmentId:ke.attachmentId||ke.attachment_id,name:ke.fileName||ke.file_name||ke.name,fileName:ke.fileName||ke.file_name||ke.name,url:ke.storageUrl||ke.storage_url||ke.url||"#",type:ke.fileType||ke.file_type||ke.type||"file",fileType:ke.fileType||ke.file_type||ke.type||"file",fileSize:ke.fileSize||ke.file_size})):void 0}}):[];C(Re)}catch{C(ye=>[...ye,fe])}x(""),E([])}};p.useEffect(()=>{if(s&&Array.isArray(s))try{const me=s.filter(z=>(z.type||"").toLowerCase()!=="sla_warning").map(z=>{var ye;if(z.type||z.activityType||z.isSystem)return{id:z.id||`activity-${z.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:z.details||z.action||z.content||"",timestamp:z.timestamp||z.createdAt||z.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const Re=z.userName||z.user_name||((ye=z.user)==null?void 0:ye.name)||"User",be=z.userRole||z.user_role,Me=Ye(be),ke=z.userId||z.user_id;return{id:z.noteId||z.note_id||z.id||String(Math.random()),user:{name:Re,avatar:Re.split(" ").map(Le=>Le[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Me},content:z.message||z.content||"",timestamp:z.createdAt||z.created_at||z.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(z.attachments)?z.attachments.map(Le=>({attachmentId:Le.attachmentId||Le.attachment_id,name:Le.fileName||Le.file_name||Le.name,fileName:Le.fileName||Le.file_name||Le.name,url:Le.storageUrl||Le.storage_url||Le.url||"#",type:Le.fileType||Le.file_type||Le.type||"file",fileType:Le.fileType||Le.file_type||Le.type||"file",fileSize:Le.fileSize||Le.file_size})):void 0,isCurrentUser:ke===P}}}).sort((z,fe)=>new Date(z.timestamp).getTime()-new Date(fe.timestamp).getTime());C(me)}catch(H){console.error("[WorkNoteChat] Error mapping messages:",H)}else(async()=>{try{const H=await Za(u),me=Array.isArray(H)?H.map(z=>{const fe=z.userName||z.user_name||"User",ye=z.userRole||z.user_role,Re=Ye(ye),be=z.userId||z.user_id;return{id:z.noteId||z.note_id||z.id||String(Math.random()),user:{name:fe,avatar:fe.split(" ").map(Me=>Me[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Re},content:z.message||"",timestamp:z.createdAt||z.created_at||new Date().toISOString(),attachments:Array.isArray(z.attachments)?z.attachments.map(Me=>({attachmentId:Me.attachmentId||Me.attachment_id,name:Me.fileName||Me.file_name||Me.name,fileName:Me.fileName||Me.file_name||Me.name,url:Me.storageUrl||Me.storage_url||Me.url||"#",type:Me.fileType||Me.file_type||Me.type||"file",fileType:Me.fileType||Me.file_type||Me.type||"file",fileSize:Me.fileSize||Me.file_size})):void 0,isCurrentUser:be===P}}):[];C(me)}catch(H){console.error("[WorkNoteChat] Error loading work notes:",H)}})()},[s,u,U]);const te=H=>{const me=re.maxFileSizeMB*1024*1024;if(H.size>me)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${re.maxFileSizeMB}MB. Current size: ${(H.size/(1024*1024)).toFixed(2)}MB`};const z=H.name.toLowerCase(),fe=z.substring(z.lastIndexOf(".")+1);return re.allowedFileTypes.includes(fe)?{valid:!0}:{valid:!1,reason:`File type "${fe}" is not allowed. Allowed types: ${re.allowedFileTypes.join(", ")}`}},xe=H=>{if(!H.target.files||H.target.files.length===0)return;const me=Array.from(H.target.files),z=[],fe=[];me.forEach(ye=>{const Re=te(ye);Re.valid?fe.push(ye):z.push({fileName:ye.name,reason:Re.reason||"Unknown validation error"})}),z.length>0&&Y({open:!0,errors:z}),fe.length>0&&(E(ye=>[...ye,...fe]),fe.length{E(me=>me.filter((z,fe)=>fe!==H)),F.current&&(F.current.value="")},ue=H=>{x(me=>me+H),w(!1)},Te=()=>{var H;(H=F.current)==null||H.click()},Qe=async H=>{var me,z;try{await du(u,H);const fe=await xs(u),ye=Array.isArray(fe==null?void 0:fe.participants)?fe.participants:[];if(ye.length){const Re=ye.map(be=>{const Me=be.participantType||be.participant_type||"participant",ke=be.userId||be.user_id||"",Le=be.userName||be.user_name||be.userEmail||be.user_email||"User",Xt=be.userEmail||be.user_email||"",wt=Le.split(" ").map(Ke=>Ke[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Le,avatar:wt,role:Oe(Me),status:"offline",email:Xt,lastSeen:void 0,permissions:["read"],userId:ke}});ee(Re),G.current&&G.current.connected&&G.current.emit("request:online-users",{requestId:u})}K(!1),I({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),S(!0)}catch(fe){throw console.error("Failed to add spectator:",fe),I({success:!1,title:"Failed to Add Spectator",message:((z=(me=fe==null?void 0:fe.response)==null?void 0:me.data)==null?void 0:z.error)||"Failed to add spectator. Please try again."}),S(!0),fe}},ht=async(H,me,z)=>{var fe,ye;if(d)await d(H,me,z),$(!1);else try{await cu(u,H,me,z);const Re=await xs(u),be=Array.isArray(Re==null?void 0:Re.participants)?Re.participants:[];if(be.length){const Me=be.map(ke=>{const Le=ke.participantType||ke.participant_type||"participant",Xt=ke.userId||ke.user_id||"",wt=ke.userName||ke.user_name||ke.userEmail||ke.user_email||"User",Ke=ke.userEmail||ke.user_email||"",$e=wt.split(" ").map(at=>at[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:wt,avatar:$e,role:Oe(Le),status:"offline",email:Ke,lastSeen:void 0,permissions:["read"],userId:Xt}});ee(Me),G.current&&G.current.connected&&G.current.emit("request:online-users",{requestId:u})}$(!1),I({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${z} with ${me}h TAT`}),S(!0)}catch(Re){throw console.error("Failed to add approver:",Re),I({success:!1,title:"Failed to Add Approver",message:((ye=(fe=Re==null?void 0:Re.response)==null?void 0:fe.data)==null?void 0:ye.error)||"Failed to add approver. Please try again."}),S(!0),Re}},et=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],qt=H=>{const me=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,z=[];let fe;for(;(fe=me.exec(H))!==null;)if(fe[1]){const ye=fe.index+fe[0].length,Re=H.slice(ye),be=H[ye];(Re.startsWith("@")||!be||/\s|[.,!?;:]|@/.test(be))&&z.push(fe[1].trim())}return z},Es=H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),ct())},Xs=(H,me)=>{C(z=>z.map(fe=>{if(fe.id===H){const ye=fe.reactions||[],Re=ye.find(be=>be.emoji===me);if(Re)if(Re.users.includes("You")){if(Re.users=Re.users.filter(be=>be!=="You"),Re.users.length===0)return{...fe,reactions:ye.filter(be=>be.emoji!==me)}}else Re.users.push("You");else ye.push({emoji:me,users:["You"]});return{...fe,reactions:ye}}return fe}))};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(Ps,{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:Z.title}),e.jsx(se,{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:[ie.slice(0,3).map((H,me)=>e.jsx(Bt,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(Ut,{className:"bg-blue-500 text-white text-xs font-semibold",children:H.avatar})},me)),ie.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:["+",ie.length-3]})]})}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>N(!v),className:"lg:hidden",children:e.jsx(Pt,{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(ws,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(we,{placeholder:"Search messages...",value:g,onChange:H=>f(H.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:[de.map(H=>{const me=H.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${H.isSystem?"justify-center":me?"justify-end":""}`,children:[!H.isSystem&&!me&&e.jsx(Bt,{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(Ut,{className:`text-white font-semibold text-xs sm:text-sm ${H.user.role==="Initiator"?"bg-green-600":H.user.role==="Current User"?"bg-blue-500":H.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:H.user.avatar})}),e.jsx("div",{className:`${me?"max-w-[70%]":"flex-1"} min-w-0 ${H.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:H.isSystem?e.jsxs("div",{className:"inline-flex items-center gap-2 sm:gap-3 px-3 sm:px-4 py-1.5 sm:py-2 bg-gray-100 rounded-full",children:[e.jsx(Vt,{className:"w-3 h-3 sm:w-4 sm:h-4 text-gray-500 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm text-gray-700",children:H.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:Qt(H.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${me?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[H.user.name," ",me&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(se,{variant:"outline",className:"text-xs flex-shrink-0",children:H.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(He,{className:"w-3 h-3"}),Qt(H.timestamp)]}),H.isHighPriority&&e.jsxs(se,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(Hg,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${me?"bg-blue-50 border-blue-200":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:"text-gray-800 leading-relaxed text-sm sm:text-base",dangerouslySetInnerHTML:{__html:y1(H.content)}}),H.attachments&&H.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:H.attachments.map((z,fe)=>{const ye=z.fileSize||z.file_size,Re=z.fileName||z.file_name||z.name,be=z.fileType||z.file_type||z.type||"",Me=z.attachmentId||z.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(Jd,{type:be})}),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:Re}),ye&&e.jsx("p",{className:"text-xs text-gray-500",children:b1(ye)})]}),Me&&(()=>{const ke=(be||"").toLowerCase();return ke.includes("image")||ke.includes("pdf")||ke.includes("jpg")||ke.includes("jpeg")||ke.includes("png")||ke.includes("gif")})()&&e.jsx(R,{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:ke=>{ke.preventDefault(),ke.stopPropagation();const Le=sb(Me);A({fileName:Re,fileType:be,fileUrl:Le,fileSize:ye,attachmentId:Me})},title:"Preview file",children:e.jsx(rs,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(R,{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 ke=>{if(ke.preventDefault(),ke.stopPropagation(),!Me){ne.error("Cannot download: Attachment ID missing");return}try{await kc(Me)}catch{ne.error("Failed to download file")}},title:"Download file",children:e.jsx(ss,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},fe)})})}),H.reactions&&H.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:[H.reactions.map((z,fe)=>e.jsxs("button",{onClick:()=>Xs(H.id,z.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${z.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:z.emoji}),e.jsx("span",{className:"text-xs font-medium",children:z.users.length})]},fe)),e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>w(!j),children:e.jsx(Ws,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!H.isSystem&&me&&e.jsx(Bt,{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(Ut,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:H.user.avatar})})]},H.id)}),e.jsx("div",{ref:_})]})}),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:F,onChange:xe,className:"hidden",multiple:!0,accept:re.allowedFileTypes.map(H=>`.${H}`).join(",")}),k.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:k.map((H,me)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-blue-50 rounded-lg border border-blue-200",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx(Jd,{type:H.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:H.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(H.size/1024).toFixed(1)," KB"]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>dt(me),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(ut,{className:"h-3 w-3 text-red-600"})})]},me))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const H=h.lastIndexOf("@"),me=H>=0;if(!me)return null;const z=h.slice(H+1),fe=z.trim(),ye=z.endsWith(" "),Re=fe.length>0,be=fe.includes(" ")&&!ye,Me=ye&ℜif(!(me&&z.length<=20&&!be&&!Me))return null;const Le=fe.toLowerCase(),Xt=U.filter(wt=>wt.userId===P?!1:Le?wt.name.toLowerCase().includes(Le):!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:Xt.length>0?Xt.map((wt,Ke)=>e.jsxs("button",{type:"button",onClick:$e=>{$e.preventDefault(),$e.stopPropagation();const at=h.lastIndexOf("@"),zt=h.slice(0,at);x(zt+"@"+wt.name+" ")},className:"w-full flex items-center gap-3 p-3 hover:bg-blue-50 rounded-lg text-left transition-colors border border-transparent hover:border-blue-200",children:[e.jsx(Bt,{className:"h-10 w-10",children:e.jsx(Ut,{className:`text-white text-sm font-semibold ${wt.role==="Initiator"?"bg-green-600":wt.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:wt.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:wt.name}),e.jsx("p",{className:"text-xs text-gray-600",children:wt.role})]})]},Ke)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:Le?`No participants found matching "${Le}"`:"No other participants available"})})]})})(),e.jsx(ns,{placeholder:"Type your message... Use @username to mention someone",value:h,onChange:H=>x(H.target.value),onKeyPress:Es,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}),j&&e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border border-gray-200 rounded-lg shadow-xl p-3 z-50 w-full sm:w-96 max-h-80 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 sticky top-0 bg-white pb-2 border-b",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-700",children:"Pick an emoji"}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>w(!1),className:"h-6 w-6 p-0",children:e.jsx(ut,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:et.map((H,me)=>e.jsx("button",{onClick:()=>ue(H),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:H,children:H},me))})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-shrink-0",children:[e.jsx(R,{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:Te,title:"Attach file",children:e.jsx(In,{className:"h-4 w-4"})}),e.jsx(R,{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:()=>w(!j),title:"Add emoji",children:e.jsx(Wg,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>x(H=>H+"@"),title:"Mention someone",children:e.jsx(Co,{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(R,{onClick:ct,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(Im,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),v&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>N(!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 ${v?"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(R,{variant:"ghost",size:"sm",onClick:()=>N(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(ut,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:U.map((H,me)=>{const z=H.userId===P;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Bt,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(Ut,{className:`text-white font-semibold text-sm ${H.role==="Initiator"?"bg-green-600":z?"bg-blue-500":"bg-slate-600"}`,children:H.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${g1(H.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:[H.name," ",z&&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:H.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:f1(H.status)})]}),H.lastSeen&&H.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:H.lastSeen})]})]},me)})})]}),!Ae&&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(R,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>$(!0),children:[e.jsx(Ln,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(R,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>K(!0),children:[e.jsx(rs,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),y&&e.jsx(gl,{fileName:y.fileName,fileType:y.fileType,fileUrl:y.fileUrl,fileSize:y.fileSize,attachmentId:y.attachmentId,onDownload:kc,open:!!y,onClose:()=>A(null)}),!Ae&&e.jsx(ip,{open:L,onClose:()=>K(!1),onConfirm:Qe,requestIdDisplay:u,requestTitle:Z.title,existingParticipants:Se}),!Ae&&o&&e.jsx(op,{open:O,onClose:()=>$(!1),onConfirm:ht,requestIdDisplay:u,requestTitle:Z.title,existingParticipants:Se,currentLevels:c}),e.jsx(nt,{open:V.open,onOpenChange:H=>Y(me=>({...me,open:H})),children:e.jsxs(tt,{className:"sm:max-w-lg",children:[e.jsxs(it,{children:[e.jsxs(st,{className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Mt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:V.errors.map((H,me)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:H.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:H.reason})]},me))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",re.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",re.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Nt,{children:e.jsx(R,{onClick:()=>Y({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(np,{open:T,onClose:()=>S(!1),success:D.success,title:D.title,message:D.message})]})}function v1({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(lp,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:o,onAddApprover:l})})}function j1({summary:t,loading:s,onShare:a,isInitiator:r}){const n=l=>{const c=l.toLowerCase();return c==="approved"?e.jsx(Ce,{className:"h-4 w-4 text-green-600"}):c==="rejected"?e.jsx(yt,{className:"h-4 w-4 text-red-600"}):c==="pending"||c==="in progress"?e.jsx(He,{className:"h-4 w-4 text-orange-600"}):e.jsx(Ee,{className:"h-4 w-4 text-gray-600"})},i=l=>{const c=l.toLowerCase();return c==="approved"?"bg-green-100 text-green-700 border-green-300":c==="rejected"?"bg-red-100 text-red-700 border-red-300":c==="pending"||c==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},o=(l,c)=>l&&l.trim()&&l.trim().toUpperCase()!=="N/A"?l:c&&c.trim()&&c.trim().toUpperCase()!=="N/A"?c:"N/A";return s?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Je,{className:"h-12 w-12 animate-spin text-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading summary..."})]})}):t?e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200",children:[e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:t.title}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Request #",t.requestNumber]})]}),r&&a?e.jsxs(R,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(qa,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(se,{className:i(t.workflow.status),children:[n(t.workflow.status),e.jsx("span",{className:"ml-1 capitalize",children:t.workflow.status})]})]}),t.description&&e.jsx("div",{className:"mb-4",children:e.jsx(ma,{content:t.description,className:"text-gray-700"})})]}),e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Initiator"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.status})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:Ne(new Date(t.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),t.approvers&&t.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),t.approvers.map((l,c)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsx("h4",{className:"text-md font-semibold text-gray-800 mb-3",children:l.levelName||`Approver ${l.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:l.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:o(l.designation,l.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1",children:[n(l.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l.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:Ne(new Date(l.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:l.remarks||"—"})]})]},c))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),t.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(se,{variant:"outline",className:"text-xs",children:"AI Generated"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),t.closingRemarks?e.jsx(ma,{content:t.closingRemarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]})]})]})}):e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ee,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-bold text-gray-900 mb-2",children:"Summary Not Available"}),e.jsx("p",{className:"text-gray-600",children:"Summary has not been generated for this request yet."})]})})}function N1({sla:t,requestStatus:s,isPaused:a=!1,testId:r="sla-progress"}){if(!t||s==="approved"||s==="rejected"||s==="closed")return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${r}-status-only`,children:[s==="closed"?e.jsx(Ir,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(Ce,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(yt,{className:"h-4 w-4 text-red-600"}):e.jsx(He,{className:"h-4 w-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-medium text-gray-700",children:s==="closed"?"Request Closed":s==="approved"?"Request Approved":s==="rejected"?"Request Rejected":"SLA Not Available"})]});const n=t.percentageUsed||0,i=t.status||"on_track",l=a?{badge:"bg-gray-500 text-white",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-500"}:n>=100?{badge:"bg-red-600 text-white animate-pulse",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:n>=75?{badge:"bg-orange-500 text-white",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:n>=50?{badge:"bg-amber-500 text-white",progress:"bg-amber-500",text:"text-amber-600",icon:"text-blue-600"}:{badge:"bg-green-600 text-white",progress:"bg-green-600",text:"text-gray-700",icon:"text-blue-600"},c=i==="on_track"||i==="normal"?"normal":i;return e.jsxs("div",{"data-testid":r,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[a?e.jsx(Ir,{className:`h-4 w-4 ${l.icon}`}):e.jsx(He,{className:`h-4 w-4 ${l.icon}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:a?"SLA Progress (Paused)":"SLA Progress"})]}),e.jsxs(se,{className:`text-xs ${l.badge}`,"data-testid":`${r}-badge`,children:[t.percentageUsed||0,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(Gs,{value:t.percentageUsed||0,className:"h-3 mb-2",indicatorClassName:l.progress,"data-testid":`${r}-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsxs("span",{className:"text-gray-600","data-testid":`${r}-elapsed`,children:[t.elapsedText||Et(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${c==="breached"||c==="critical"?l.text:"text-gray-700"}`,"data-testid":`${r}-remaining`,children:[Et(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${r}-deadline`,children:["Due: ",Ks(t.deadline,!0)," • ",t.percentageUsed||0,"% elapsed"]}),c==="critical"&&e.jsxs("p",{className:"text-xs text-orange-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-critical`,children:[e.jsx(as,{className:"h-3.5 w-3.5"}),"Approaching Deadline"]}),c==="breached"&&e.jsxs("p",{className:"text-xs text-red-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-breached`,children:[e.jsx($i,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function w1({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i}){var d,m,u;const o=u1((t==null?void 0:t.priority)||"standard"),l=h1((t==null?void 0:t.status)||"pending"),c=((d=t==null?void 0:t.pauseInfo)==null?void 0:d.isPaused)||!1;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(R,{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(Rs,{className:"h-4 w-4 sm:h-5 sm:h-5"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(Ee,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 min-w-0 flex-1",children:[e.jsx("h1",{className:"text-sm sm:text-base md:text-lg font-bold text-gray-900 truncate","data-testid":"request-id",children:t.id||"N/A"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2",children:[e.jsx(se,{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(se,{className:`${l.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:l.label}),(()=>{const h=(t==null?void 0:t.workflowType)||(t==null?void 0:t.workflow_type),x=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type),g=h==="CLAIM_MANAGEMENT"||x==="claim-management",f=g?"Claim Management":"Custom",j=g?"bg-blue-100 !text-blue-700 border-blue-200":"bg-purple-100 !text-purple-600 border-purple-200";return e.jsx(se,{className:`${j} rounded-full px-2 sm:px-3 text-xs shrink-0`,variant:"outline","data-testid":"template-type-badge",children:f})})()]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&i&&((m=t==null?void 0:t.status)==null?void 0:m.toLowerCase())==="closed"&&e.jsxs(R,{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(qa,{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(R,{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(Zt,{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 border-b border-gray-200 ${c?"bg-gradient-to-r from-gray-100 to-gray-200":"bg-gradient-to-r from-blue-50 to-indigo-50"}`,"data-testid":"sla-section",children:e.jsx(N1,{sla:((u=t.summary)==null?void 0:u.sla)||t.sla,requestStatus:t.status,isPaused:c,testId:"request-sla"})})]})}async function fl(t){return(await he.get(`/summaries/${t}`)).data.data}async function C1(t,s){return(await he.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function S1(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await he.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 cp(t){await he.patch(`/summaries/shared/${t}/view`)}async function dp(t){var s;try{return(await he.get(`/summaries/request/${t}`)).data.data}catch(a){return((s=a==null?void 0:a.response)==null?void 0:s.status)===404,null}}async function A1(t){return(await he.get(`/summaries/${t}/recipients`)).data.data||[]}function k1({activityInfo:t,className:s}){if(!t)return console.warn("[ActivityInformationCard] activityInfo is missing"),e.jsx(X,{className:s,children:e.jsx(J,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Activity information not available"})})});const a=n=>{const i=typeof n=="string"?parseFloat(n):n;return isNaN(i)?"N/A":`₹${i.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`},r=n=>{if(!n)return"N/A";try{return Ne(new Date(n),"MMM d, yyyy")}catch{return n}};return e.jsxs(X,{className:s,children:[e.jsx(le,{children:e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx(qe,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.activityName})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Type"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.activityType})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Location"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(So,{className:"w-4 h-4 text-gray-400"}),t.location]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Requested Date"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:r(t.requestedDate)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Estimated Budget"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(_s,{className:"w-4 h-4 text-green-600"}),t.estimatedBudget?a(t.estimatedBudget):"TBD"]})]}),t.closedExpenses!==void 0&&t.closedExpenses!==null&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Closed Expenses"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(ms,{className:"w-4 h-4 text-blue-600"}),a(t.closedExpenses)]})]}),t.period&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Period"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1",children:[r(t.period.startDate)," - ",r(t.period.endDate)]})]})]}),t.closedExpensesBreakdown&&t.closedExpensesBreakdown.length>0&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Closed Expenses Breakdown"}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-2",children:[t.closedExpensesBreakdown.map((n,i)=>e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsx("span",{className:"text-gray-700",children:n.description}),e.jsx("span",{className:"font-medium text-gray-900",children:a(n.amount)})]},i)),e.jsxs("div",{className:"pt-2 border-t border-blue-300 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900",children:"Total"}),e.jsx("span",{className:"font-bold text-blue-600",children:a(t.closedExpensesBreakdown.reduce((n,i)=>n+i.amount,0))})]})]})]}),t.description&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Description"}),e.jsx("p",{className:"text-sm text-gray-700 mt-2 bg-gray-50 p-3 rounded-lg whitespace-pre-line",children:t.description})]})]})]})}function T1({dealerInfo:t,className:s}){return t?!t.dealerCode&&!t.dealerName?(console.warn("[DealerInformationCard] Dealer info missing essential fields:",t),e.jsx(X,{className:s,children:e.jsx(J,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information incomplete"})})})):e.jsxs(X,{className:s,children:[e.jsx(le,{children:e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx(On,{className:"w-5 h-5 text-purple-600"}),"Dealer Information"]})}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Code"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.dealerCode})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.dealerName})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Contact Information"}),e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx(aa,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{children:t.email})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx(Mn,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{children:t.phone})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-gray-700",children:[e.jsx(So,{className:"w-4 h-4 text-gray-400 mt-0.5"}),e.jsx("span",{children:t.address})]})]})]})]})]}):(console.warn("[DealerInformationCard] dealerInfo is missing"),e.jsx(X,{className:s,children:e.jsx(J,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information not available"})})}))}function D1({ioDetails:t,dmsDetails:s,claimAmount:a,estimatedBudgetBreakdown:r,closedExpensesBreakdown:n,visibility:i,onEditClaimAmount:o,className:l}){const c=h=>h==null||Number.isNaN(h)?"₹0.00":`₹${h.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,d=h=>{if(!h)return"";try{return Ne(new Date(h),"MMM d, yyyy, h:mm a")}catch{return h||""}},m=h=>!h||h.length===0?0:h.reduce((x,g)=>x+(g.amount??0),0);return i.showIODetails&&t||i.showDMSDetails&&s||i.showClaimAmount&&a&&a.amount!==void 0&&a.amount!==null||r&&r.length>0||n&&n.length>0?e.jsxs(X,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${l}`,children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"text-base flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-blue-600"}),"Process Details"]}),e.jsx(je,{children:"Workflow reference numbers"})]}),e.jsxs(J,{className:"space-y-3",children:[i.showIODetails&&t&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-blue-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ms,{className:"w-4 h-4 text-blue-600"}),e.jsx(Q,{className:"text-xs font-semibold text-blue-900 uppercase tracking-wide",children:"IO Number"})]}),e.jsx("p",{className:"font-bold text-gray-900 mb-2",children:t.ioNumber}),t.remarks&&e.jsxs("div",{className:"pt-2 border-t border-blue-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Remark:"}),e.jsx("p",{className:"text-xs text-gray-900",children:t.remarks})]}),(t.availableBalance!==void 0||t.blockedAmount!==void 0)&&e.jsxs("div",{className:"pt-2 border-t border-blue-100 mt-2 space-y-1",children:[t.availableBalance!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Available Balance:"}),e.jsx("span",{className:"font-medium text-gray-900",children:c(t.availableBalance)})]}),t.blockedAmount!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Blocked Amount:"}),e.jsx("span",{className:"font-medium text-blue-700",children:c(t.blockedAmount)})]}),t.remainingBalance!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Remaining Balance:"}),e.jsx("span",{className:"font-medium text-green-700",children:c(t.remainingBalance)})]})]}),e.jsxs("div",{className:"pt-2 border-t border-blue-100 mt-2",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["By ",t.blockedByName]}),e.jsx("p",{className:"text-xs text-gray-500",children:d(t.blockedAt)})]})]}),i.showDMSDetails&&s&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-purple-600"}),e.jsx(Q,{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"DMS Number"})]}),e.jsx("p",{className:"font-bold text-gray-900 mb-2",children:s.dmsNumber}),s.remarks&&e.jsxs("div",{className:"pt-2 border-t border-purple-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Remarks:"}),e.jsx("p",{className:"text-xs text-gray-900",children:s.remarks})]}),e.jsxs("div",{className:"pt-2 border-t border-purple-100 mt-2",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["By ",s.createdByName]}),e.jsx("p",{className:"text-xs text-gray-500",children:d(s.createdAt)})]})]}),i.showClaimAmount&&a&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"w-4 h-4 text-green-600"}),e.jsx(Q,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),i.canEditClaimAmount&&o&&e.jsxs(R,{variant:"outline",size:"sm",onClick:o,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(Mm,{className:"w-3 h-3 mr-1 text-green-700"}),"Edit"]})]}),e.jsx("p",{className:"text-2xl font-bold text-green-700",children:c(a.amount)}),a.lastUpdatedBy&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-green-100",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["Last updated by ",a.lastUpdatedBy]}),a.lastUpdatedAt&&e.jsx("p",{className:"text-xs text-gray-500",children:d(a.lastUpdatedAt)})]})]}),r&&r.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-amber-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ms,{className:"w-4 h-4 text-amber-600"}),e.jsx(Q,{className:"text-xs font-semibold text-amber-900 uppercase tracking-wide",children:"Estimated Budget Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[r.map((h,x)=>e.jsxs("div",{className:"flex justify-between items-center text-xs",children:[e.jsx("span",{className:"text-gray-700",children:h.description}),e.jsx("span",{className:"font-medium text-gray-900",children:c(h.amount)})]},x)),e.jsxs("div",{className:"pt-2 border-t border-amber-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-amber-700",children:c(m(r))})]})]})]}),n&&n.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-indigo-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ms,{className:"w-4 h-4 text-indigo-600"}),e.jsx(Q,{className:"text-xs font-semibold text-indigo-900 uppercase tracking-wide",children:"Closed Expenses Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[n.map((h,x)=>e.jsxs("div",{className:"flex justify-between items-center text-xs",children:[e.jsx("span",{className:"text-gray-700",children:h.description}),e.jsx("span",{className:"font-medium text-gray-900",children:c(h.amount)})]},x)),e.jsxs("div",{className:"pt-2 border-t border-indigo-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-indigo-700",children:c(m(n))})]})]})]})]})]}):null}function R1({proposalDetails:t,className:s}){const r=t.estimatedBudgetTotal!==void 0&&t.estimatedBudgetTotal!==null?t.estimatedBudgetTotal:t.costBreakup&&t.costBreakup.length>0?t.costBreakup.reduce((c,d)=>{const m=d.amount||0;return c+(Number.isNaN(m)?0:m)},0):0,n=l=>l==null||Number.isNaN(l)?"₹0.00":`₹${l.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,i=l=>{if(!l)return"";try{return Ne(new Date(l),"MMM d, yyyy, h:mm a")}catch{return l||""}},o=l=>{if(!l)return"-";try{return Ne(new Date(l),"MMM d, yyyy")}catch{return l||"-"}};return e.jsxs(X,{className:s,children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx(ms,{className:"w-5 h-5 text-green-600"}),"Proposal Details"]}),t.submittedOn&&e.jsxs(je,{children:["Submitted on ",i(t.submittedOn)]})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Cost Breakup"}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-gray-50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-left text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Item Description"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-200",children:[(t.costBreakup||[]).map((l,c)=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900",children:l.description}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right font-medium",children:n(l.amount)})]},c)),e.jsxs("tr",{className:"bg-green-50 font-semibold",children:[e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900",children:"Estimated Budget (Total)"}),e.jsx("td",{className:"px-4 py-3 text-sm text-green-700 text-right",children:n(r)})]})]})]})})]}),e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Timeline for Closure"}),e.jsx("div",{className:"mt-2 bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{className:"text-sm font-medium text-gray-900",children:["Expected completion by: ",o(t.timelineForClosure)]})]})})]}),t.dealerComments&&e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Comments"}),e.jsx("p",{className:"text-sm text-gray-700 mt-2 bg-gray-50 p-3 rounded-lg whitespace-pre-line",children:t.dealerComments})]})]})]})}function P1({initiatorInfo:t,className:s}){const a=r=>r.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2);return e.jsxs(X,{className:s,children:[e.jsx(le,{children:e.jsx(ce,{className:"text-base",children:"Request Initiator"})}),e.jsx(J,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Bt,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(Ut,{className:"bg-gray-700 text-white font-semibold text-lg",children:a(t.name)})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:t.name}),t.role&&e.jsx("p",{className:"text-sm text-gray-600",children:t.role}),t.department&&e.jsx("p",{className:"text-sm text-gray-500",children:t.department}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[e.jsx(aa,{className:"w-4 h-4"}),e.jsx("span",{children:t.email})]}),t.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[e.jsx(Mn,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function yl(t){return t?t.workflowType==="CLAIM_MANAGEMENT"||t.templateType==="claim-management"||t.template==="claim-management"||t.templateName==="Claim Management"||t.templateCode==="CLAIM_MANAGEMENT":!1}function mp(t,s){var a,r;try{if(!yl(t))return null;const n=t.claimDetails||{},i=t.proposalDetails||{},o=t.completionDetails||{},l=t.internalOrder||t.internal_order||{},c=t.budgetTracking||t.budget_tracking||{},d=t.invoice||{},m=t.creditNote||t.credit_note||{},u=t.completionExpenses||t.completion_expenses||[];console.debug("[claimDataMapper] Raw claimDetails:",n),console.debug("[claimDataMapper] Raw apiRequest:",{hasClaimDetails:!!t.claimDetails,hasProposalDetails:!!t.proposalDetails,hasCompletionDetails:!!t.completionDetails,hasBudgetTracking:!!c,hasInvoice:!!d,hasCreditNote:!!m,hasCompletionExpenses:Array.isArray(u)&&u.length>0,workflowType:t.workflowType});const h=n.periodStartDate||n.period_start_date,x=n.periodEndDate||n.period_end_date,g=n.activityName||n.activity_name||"",f=n.activityType||n.activity_type||"",j=n.location||"";console.debug("[claimDataMapper] Mapped activity fields:",{activityName:g,activityType:f,location:j,hasActivityName:!!g,hasActivityType:!!f,hasLocation:!!j});const w=c.proposalEstimatedBudget||c.proposal_estimated_budget||c.initialEstimatedBudget||c.initial_estimated_budget||n.estimatedBudget||n.estimated_budget,b=(c==null?void 0:c.closedExpenses)||(c==null?void 0:c.closed_expenses)||(o==null?void 0:o.totalClosedExpenses)||(o==null?void 0:o.total_closed_expenses)||(n==null?void 0:n.closedExpenses)||(n==null?void 0:n.closed_expenses),C=b!=null?Number(b):void 0,v=Array.isArray(u)&&u.length>0?u.map(L=>({description:L.description||L.itemDescription||"",amount:Number(L.amount)||0})):(o==null?void 0:o.closedExpenses)||(o==null?void 0:o.closed_expenses)||(o==null?void 0:o.closedExpensesBreakdown)||[],N={activityName:g,activityType:f,requestedDate:n.activityDate||n.activity_date||t.createdAt,location:j,period:h&&x?{startDate:h,endDate:x}:void 0,estimatedBudget:w,closedExpenses:C,closedExpensesBreakdown:v,description:t.description||""},k={dealerCode:(n==null?void 0:n.dealerCode)||(n==null?void 0:n.dealer_code)||(n==null?void 0:n.DealerCode)||"",dealerName:(n==null?void 0:n.dealerName)||(n==null?void 0:n.dealer_name)||(n==null?void 0:n.DealerName)||"",email:(n==null?void 0:n.dealerEmail)||(n==null?void 0:n.dealer_email)||(n==null?void 0:n.DealerEmail)||"",phone:(n==null?void 0:n.dealerPhone)||(n==null?void 0:n.dealer_phone)||(n==null?void 0:n.DealerPhone)||"",address:(n==null?void 0:n.dealerAddress)||(n==null?void 0:n.dealer_address)||(n==null?void 0:n.DealerAddress)||""};(!k.dealerCode||!k.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!n,dealerCode:k.dealerCode,dealerName:k.dealerName,rawClaimDetails:n,availableKeys:n?Object.keys(n):[]});const E=(i==null?void 0:i.expectedCompletionDate)||(i==null?void 0:i.expected_completion_date),P=i?{proposalDocumentUrl:i.proposalDocumentUrl||i.proposal_document_url,costBreakup:i.costBreakup||i.cost_breakup||[],totalEstimatedBudget:i.totalEstimatedBudget||i.total_estimated_budget||0,timelineMode:i.timelineMode||i.timeline_mode,expectedCompletionDate:E,expectedCompletionDays:i.expectedCompletionDays||i.expected_completion_days,timelineForClosure:E,dealerComments:i.dealerComments||i.dealer_comments,submittedOn:i.submittedAt||i.submitted_at||i.submittedOn}:void 0,M={ioNumber:l.ioNumber||l.io_number||n.ioNumber||n.io_number,ioRemark:l.ioRemark||l.io_remark||"",availableBalance:l.ioAvailableBalance||l.io_available_balance||n.ioAvailableBalance||n.io_available_balance,blockedAmount:l.ioBlockedAmount||l.io_blocked_amount||n.ioBlockedAmount||n.io_blocked_amount,remainingBalance:l.ioRemainingBalance||l.io_remaining_balance||n.ioRemainingBalance||n.io_remaining_balance,organizedBy:((a=l.organizer)==null?void 0:a.displayName)||((r=l.organizer)==null?void 0:r.name)||l.organizedBy||"",organizedAt:l.organizedAt||l.organized_at||""},y={eInvoiceNumber:d.invoiceNumber||d.invoice_number||n.eInvoiceNumber||n.e_invoice_number,eInvoiceDate:d.invoiceDate||d.invoice_date||n.eInvoiceDate||n.e_invoice_date,dmsNumber:d.dmsNumber||d.dms_number||n.dmsNumber||n.dms_number,creditNoteNumber:m.creditNoteNumber||m.credit_note_number||n.creditNoteNumber||n.credit_note_number,creditNoteDate:m.creditNoteDate||m.credit_note_date||n.creditNoteDate||n.credit_note_date,creditNoteAmount:m.creditNoteAmount?Number(m.creditNoteAmount):m.credit_note_amount?Number(m.credit_note_amount):m.creditNoteAmount?Number(m.creditNoteAmount):n.creditNoteAmount?Number(n.creditNoteAmount):n.credit_note_amount?Number(n.credit_note_amount):void 0},A={estimated:N.estimatedBudget||0,closed:N.closedExpenses||0};return{activityInfo:N,dealerInfo:k,proposalDetails:P,ioDetails:Object.keys(M).some(L=>M[L])?M:void 0,dmsDetails:Object.keys(y).some(L=>y[L])?y:void 0,claimAmount:A}}catch(n){return console.error("[claimDataMapper] Error mapping claim data:",n),null}}function up(t,s){var a,r;try{if(t.initiatorId===s||((a=t.initiator)==null?void 0:a.userId)===s||((r=t.requestedBy)==null?void 0:r.userId)===s)return"INITIATOR";if((t.participants||[]).find(d=>{var m;return(d.userId===s||((m=d.user)==null?void 0:m.userId)===s)&&(d.participantType==="DEALER"||d.type==="DEALER")}))return"DEALER";const o=t.approvalLevels||[];return o.find(d=>{var m;return d.levelNumber===3&&(d.approverId===s||((m=d.approver)==null?void 0:m.userId)===s)})?"DEPARTMENT_LEAD":o.find(d=>{var m;return(d.approverId===s||((m=d.approver)==null?void 0:m.userId)===s)&&d.status==="PENDING"})?"APPROVER":"SPECTATOR"}catch(n){return console.error("[claimDataMapper] Error determining user role:",n),"SPECTATOR"}}function hp(t){switch(t){case"INITIATOR":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!0,showDMSDetails:!0,showClaimAmount:!0,canEditClaimAmount:!1};case"DEALER":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!1,showDMSDetails:!1,showClaimAmount:!0,canEditClaimAmount:!1};case"DEPARTMENT_LEAD":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!0,showDMSDetails:!0,showClaimAmount:!0,canEditClaimAmount:!1};case"APPROVER":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!0,showDMSDetails:!0,showClaimAmount:!0,canEditClaimAmount:!1};case"SPECTATOR":default:return{showDealerInfo:!1,showProposalDetails:!1,showIODetails:!1,showDMSDetails:!1,showClaimAmount:!1,canEditClaimAmount:!1}}}function E1({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:o,onReject:l,onPause:c,onResume:d,onRetrigger:m,summaryId:u,refreshTrigger:h,pausedByUserId:x,currentUserId:g,apiRequest:f,onEditClaimAmount:j}){var T,S,D,I,_;const{user:w}=Gt(),[b,C]=p.useState([]),[v,N]=p.useState(!1),[k,E]=p.useState(!1),P=(t==null?void 0:t.status)==="closed",M=((T=t==null?void 0:t.pauseInfo)==null?void 0:T.isPaused)||!1,y=x||((D=(S=t==null?void 0:t.pauseInfo)==null?void 0:S.pausedBy)==null?void 0:D.userId),A=g||(w==null?void 0:w.userId)||"",L=!M&&!P&&(r||s),K=M&&d&&(r||s),O=M&&s&&y&&y!==A&&m;p.useEffect(()=>{if(!M||!r||!(t!=null&&t.requestId)){E(!1);return}(async()=>{var G;try{const ae=(((G=(await da.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:G.notifications)||[]).some(V=>V.requestId===t.requestId&&V.notificationType==="pause_retrigger_request");E(ae)}catch(B){console.error("Failed to check retrigger notifications:",B),E(!1)}})()},[M,r,t==null?void 0:t.requestId,h]),p.useEffect(()=>{(async()=>{if(!P||!u||!s){C([]);return}try{N(!0);const G=await A1(u);C(G)}catch(G){console.error("Failed to fetch shared recipients:",G),C([])}finally{N(!1)}})()},[P,u,s,h]);const $=p.useMemo(()=>{if(!f||!yl(f))return null;const F=mp(f);if(!F)return null;const G=up(f,A),B=hp(G);return{claimRequest:F,visibility:B}},[f,A]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(X,{"data-testid":"quick-actions-card",children:[e.jsx(le,{className:"pb-2",children:e.jsx(ce,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(J,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(R,{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(Ln,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(R,{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(rs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),L&&c&&e.jsxs(R,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:c,"data-testid":"pause-workflow-button",children:[e.jsx(ha,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),K&&e.jsxs(R,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-green-700 border-green-300 hover:bg-green-50 hover:text-green-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:d,"data-testid":"resume-workflow-button",children:[e.jsx(Nn,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),O&&e.jsxs(R,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:m,"data-testid":"request-resume-button",children:[e.jsx(Ie,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Request Resume"]}),e.jsxs("div",{className:"pt-3 sm:pt-4 space-y-2",children:[r&&!M&&e.jsxs(e.Fragment,{children:[e.jsxs(R,{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(Ce,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Approve Request"]}),e.jsxs(R,{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(yt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Reject Request"]})]}),M&&e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children:y===A?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-orange-800 font-medium flex items-center justify-center gap-1.5",children:[k&&e.jsx(Ie,{className:"w-3.5 h-3.5"}),k?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:k?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&y!==A&&k?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-orange-800 font-medium flex items-center justify-center gap-1.5",children:[e.jsx(Ie,{className:"w-3.5 h-3.5"}),"Initiator has requested resume"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"Please review and resume if appropriate"})]}):r&&y!==A?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Workflow is paused"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"You can resume to continue approval"})]}):s&&y&&y!==A?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Approver has paused this workflow"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:O?'Click "Request Resume" to notify approver':"Resume request sent - Waiting for approver"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Workflow is paused"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"Actions are disabled until resumed"})]})})]})]})]}),e.jsxs(X,{"data-testid":"spectators-card",children:[e.jsx(le,{className:"pb-2",children:e.jsx(ce,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(J,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((F,G)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${G}`,children:[e.jsx(Bt,{className:"h-8 w-8",children:e.jsx(Ut,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:F.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:F.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:F.role})]})]},G)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),P&&s&&e.jsxs(X,{"data-testid":"shared-recipients-card",children:[e.jsx(le,{className:"pb-2",children:e.jsxs(ce,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(qa,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(J,{className:"space-y-3",children:v?e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Loading..."})}):b.length>0?b.map((F,G)=>{const B=(F.displayName||"NA").split(" ").map(re=>re[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${G}`,children:[e.jsx(Bt,{className:"h-8 w-8",children:e.jsx(Ut,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:B})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:F.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:F.email}),F.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},F.userId||G)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),$&&e.jsx(D1,{ioDetails:$.claimRequest.ioDetails,dmsDetails:$.claimRequest.dmsDetails,claimAmount:{amount:$.claimRequest.claimAmount.closed||$.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:(I=$.claimRequest.proposalDetails)==null?void 0:I.costBreakup,closedExpensesBreakdown:(_=$.claimRequest.activityInfo)==null?void 0:_.closedExpensesBreakdown,visibility:$.visibility,onEditClaimAmount:j})]})}function I1({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:o}){const[l,c]=p.useState(r),[d,m]=p.useState(!1),u=(l==null?void 0:l.length)||0,h=p.useMemo(()=>l.slice(0,500),[l]),x=async()=>{try{m(!0),await a(h),s()}finally{m(!1)}};return e.jsx(nt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(tt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(it,{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(Ce,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(st,{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(se,{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(ns,{value:h,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter your approval comments and any conditions or notes...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(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(Ce,{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(Nt,{className:"mt-4",children:[e.jsx(R,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(R,{onClick:x,disabled:d,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),d?"Approving...":"Approve Request"]})]})]})})}function M1({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:o}){const[l,c]=p.useState(r),[d,m]=p.useState(!1),u=(l==null?void 0:l.length)||0,h=p.useMemo(()=>l.slice(0,500),[l]),x=async()=>{if(!h.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(h),s()}finally{m(!1)}};return e.jsx(nt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(tt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(it,{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(yt,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(st,{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(se,{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(ns,{value:h,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter detailed reasons for rejection and any suggestions for improvement...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(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(Ie,{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(Nt,{className:"mt-4",children:[e.jsx(R,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(R,{variant:"destructive",onClick:x,disabled:d,children:[e.jsx(yt,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function F1({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:o}){const[l,c]=p.useState(""),[d,m]=p.useState(!1),u=async()=>{if(l.trim())try{m(!0),await a(l.trim()),c(""),s()}catch(x){console.error("Failed to skip approver:",x)}finally{m(!1)}},h=()=>{d||(c(""),s())};return e.jsx(nt,{open:t,onOpenChange:h,children:e.jsxs(tt,{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:d,children:[e.jsx(ut,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(it,{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(Ie,{className:"w-5 h-5 text-orange-600"})}),e.jsx(st,{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(Ie,{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(Q,{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(Q,{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(Q,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(ns,{id:"skip-reason",placeholder:"Please provide a detailed reason for skipping this approver (e.g., 'Approver is on leave until [date]', 'Approver unavailable - escalating to next level')",value:l,onChange:x=>c(x.target.value),className:"min-h-[100px] border-2 border-gray-300 focus:border-orange-500",disabled:d,autoFocus:!0}),e.jsx("p",{className:"text-xs text-gray-500",children:"This reason will be recorded in the activity log and all participants will be notified."})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(R,{type:"button",variant:"outline",onClick:h,className:"flex-1 h-11 border-gray-300",disabled:d,children:"Cancel"}),e.jsxs(R,{type:"button",onClick:u,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:d||!l.trim(),children:[e.jsx(Ie,{className:"w-4 h-4 mr-2"}),d?"Skipping...":"Skip Approver"]})]})]})})}function _1({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:o,documentError:l,request:c,skipApproverData:d,actionStatus:m,existingParticipants:u,currentLevels:h,setShowApproveModal:x,setShowRejectModal:g,setShowAddApproverModal:f,setShowAddSpectatorModal:j,setShowSkipApproverModal:w,setShowActionStatusModal:b,setPreviewDocument:C,setDocumentError:v,setSkipApproverData:N,setActionStatus:k,handleApproveConfirm:E,handleRejectConfirm:P,handleAddApprover:M,handleAddSpectator:y,handleSkipApprover:A,downloadDocument:L,documentPolicy:K}){return e.jsxs(e.Fragment,{children:[e.jsx(I1,{open:t,onClose:()=>x(!1),onConfirm:E,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(M1,{open:s,onClose:()=>g(!1),onConfirm:P,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(op,{open:a,onClose:()=>f(!1),onConfirm:M,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u,currentLevels:h}),e.jsx(ip,{open:r,onClose:()=>j(!1),onConfirm:y,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:u}),e.jsx(F1,{open:n,onClose:()=>{w(!1),N(null)},onConfirm:A,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),o&&e.jsx(gl,{fileName:o.fileName,fileType:o.fileType,fileUrl:mu(o.documentId),fileSize:o.fileSize,attachmentId:o.documentId,onDownload:L,open:!!o,onClose:()=>C(null)}),m&&e.jsx(np,{open:i,onClose:()=>{b(!1),k(null)},success:m.success,title:m.title,message:m.message}),e.jsx(nt,{open:l.show,onOpenChange:O=>v($=>({...$,show:O})),children:e.jsxs(tt,{className:"sm:max-w-lg",children:[e.jsxs(it,{children:[e.jsxs(st,{className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Mt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:l.errors.map((O,$)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:O.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:O.reason})]},$))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",K.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",K.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Nt,{children:e.jsx(R,{onClick:()=>v({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const pp={DocumentsTab:m1,ActivityTab:x1,WorkNotesTab:v1,SummaryTab:j1,RequestDetailHeader:w1,QuickActionsSidebar:E1,RequestDetailModals:_1};function bl({className:t,...s}){return e.jsx(Gx,{"data-slot":"checkbox",className:ge("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(Kx,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(er,{className:"size-3.5"})})})}function xp({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,o]=p.useState(""),[l,c]=p.useState([]),[d,m]=p.useState(new Set),[u,h]=p.useState(!1),[x,g]=p.useState(!1);p.useEffect(()=>{if(!t){c([]);return}if(!i||!i.startsWith("@")||i.length<2){c([]),h(!1);return}const b=setTimeout(async()=>{var C;try{h(!0);const v=i.slice(1),N=await Ys(v,10),k=((C=N==null?void 0:N.data)==null?void 0:C.data)||(N==null?void 0:N.data)||[];c(Array.isArray(k)?k:[])}catch(v){console.error("Failed to search users:",v),ne.error("Failed to search users")}finally{h(!1)}},300);return()=>clearTimeout(b)},[i,t]);const f=b=>{m(C=>{const v=new Set(C);return v.has(b)?v.delete(b):v.add(b),v})},j=async()=>{var b,C;if(d.size===0){ne.error("Please select at least one user to share with");return}try{g(!0),await C1(a,Array.from(d)),ne.success(`Summary shared with ${d.size} user(s)`),m(new Set),o(""),c([]),n==null||n(),s()}catch(v){console.error("Failed to share summary:",v),ne.error(((C=(b=v==null?void 0:v.response)==null?void 0:b.data)==null?void 0:C.message)||"Failed to share summary")}finally{g(!1)}},w=()=>{m(new Set),o(""),c([]),s()};return e.jsx(nt,{open:t,onOpenChange:w,children:e.jsxs(tt,{className:"sm:max-w-[500px]",children:[e.jsx(it,{children:e.jsx(st,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(Q,{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(Q,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(ws,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(we,{id:"user-search",placeholder:"Type @ to search users...",value:i,onChange:b=>o(b.target.value),className:"pl-10"})]}),i&&!i.startsWith("@")&&e.jsx("p",{className:"text-xs text-gray-500 mt-1 ml-1",children:"Start with @ to search users (e.g., @john)"})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Je,{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(b=>{const C=d.has(b.userId);return e.jsxs("div",{className:"flex items-center gap-3 p-3 hover:bg-gray-50 border-b last:border-b-0 cursor-pointer",onClick:()=>f(b.userId),children:[e.jsx("div",{onClick:v=>v.stopPropagation(),onMouseDown:v=>v.stopPropagation(),className:"flex items-center",children:e.jsx(bl,{checked:C,onCheckedChange:()=>f(b.userId)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:b.displayName||b.email})]}),(b.designation||b.department)&&e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:b.designation||b.department}),e.jsx("p",{className:"text-xs text-gray-400 truncate",children:b.email})]})]},b.userId)})}),!u&&i&&i.startsWith("@")&&l.length===0&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No users found"}),!u&&i&&!i.startsWith("@")&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"Start typing with @ to search users"}),d.size>0&&e.jsxs("div",{className:"border rounded-lg p-3 bg-blue-50",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-700 mb-2",children:["Selected (",d.size,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(d).map(b=>{const C=l.find(v=>v.userId===b);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:(C==null?void 0:C.displayName)||(C==null?void 0:C.email)||b}),e.jsx("button",{onClick:()=>f(b),className:"ml-1 hover:text-red-600",children:e.jsx(ut,{className:"h-3 w-3"})})]},b)})})]})]}),e.jsxs(Nt,{children:[e.jsx(R,{variant:"outline",onClick:w,disabled:x,children:"Cancel"}),e.jsx(R,{onClick:j,disabled:x||d.size===0,children:x?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${d.size} user(s)`})]})]})})}function gp({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,o]=p.useState(""),[l,c]=p.useState(""),[d,m]=p.useState(!1),u=()=>kt().add(1,"month").format("YYYY-MM-DD"),h=()=>kt().add(1,"month").format("YYYY-MM-DD"),x=()=>kt().add(1,"day").format("YYYY-MM-DD");p.useEffect(()=>{t&&!l&&c(u())},[t]);const g=async()=>{var C,v,N,k;if(!i.trim()){ne.error("Please provide a reason for pausing");return}if(!l){ne.error("Please select a resume date");return}const j=kt(l),w=kt().add(1,"month"),b=kt().add(1,"day");if(j.isAfter(w)){ne.error("Resume date cannot be more than 1 month from now");return}if(j.isBefore(b,"day")){ne.error("Resume date must be at least 1 day from now");return}try{m(!0),await qy(a,r,i.trim(),j.toDate()),ne.success("Workflow paused successfully"),n&&await n(),o(""),c(u()),s()}catch(E){console.error("Failed to pause workflow:",E),ne.error(((v=(C=E==null?void 0:E.response)==null?void 0:C.data)==null?void 0:v.error)||((k=(N=E==null?void 0:E.response)==null?void 0:N.data)==null?void 0:k.message)||"Failed to pause workflow")}finally{m(!1)}},f=()=>{d||(o(""),c(u()),s())};return e.jsx(nt,{open:t,onOpenChange:f,children:e.jsxs(tt,{className:"sm:max-w-[500px]",children:[e.jsx(it,{children:e.jsxs(st,{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"w-5 h-5 text-orange-600"}),"Pause Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-orange-800",children:[e.jsx("strong",{children:"Note:"})," Pausing will temporarily halt TAT calculations and notifications. The workflow will automatically resume on the selected date."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ns,{id:"pause-reason",value:i,onChange:j=>o(j.target.value),placeholder:"Enter the reason for pausing this workflow...",className:"min-h-[100px] text-sm",disabled:d}),e.jsxs("p",{className:"text-xs text-gray-500",children:[i.length," / 1000 characters"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(we,{id:"resume-date",type:"date",value:l,onChange:j=>c(j.target.value),min:x(),max:h(),className:"text-sm",disabled:d}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum 1 month from today. The workflow will automatically resume on this date."})]})]}),e.jsxs(Nt,{children:[e.jsx(R,{variant:"outline",onClick:f,disabled:d,children:"Cancel"}),e.jsx(R,{onClick:g,disabled:d||!i.trim()||!l,className:"bg-orange-600 hover:bg-orange-700 text-white",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ha,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function fp({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=p.useState(""),[o,l]=p.useState(!1),c=async()=>{var m,u,h,x;try{l(!0),await eb(a,n.trim()||void 0),ne.success("Workflow resumed successfully"),r&&await r(),i(""),s()}catch(g){console.error("Failed to resume workflow:",g),ne.error(((u=(m=g==null?void 0:g.response)==null?void 0:m.data)==null?void 0:u.error)||((x=(h=g==null?void 0:g.response)==null?void 0:h.data)==null?void 0:x.message)||"Failed to resume workflow")}finally{l(!1)}},d=()=>{o||(i(""),s())};return e.jsx(nt,{open:t,onOpenChange:d,children:e.jsxs(tt,{className:"sm:max-w-[500px]",children:[e.jsx(it,{children:e.jsxs(st,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"w-5 h-5 text-green-600"}),"Resume Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-green-50 border border-green-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-green-800",children:[e.jsx("strong",{children:"Note:"})," Resuming will restart TAT calculations and notifications. The workflow will continue from where it was paused."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(ns,{id:"resume-notes",value:n,onChange:m=>i(m.target.value),placeholder:"Add any notes about why you're resuming this workflow...",className:"min-h-[100px] text-sm",disabled:o}),e.jsxs("p",{className:"text-xs text-gray-500",children:[n.length," / 1000 characters"]})]})]}),e.jsxs(Nt,{children:[e.jsx(R,{variant:"outline",onClick:d,disabled:o,children:"Cancel"}),e.jsx(R,{onClick:c,disabled:o,className:"bg-green-600 hover:bg-green-700 text-white",children:o?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Nn,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function yp({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,o]=p.useState(!1),l=async()=>{var c,d,m,u;try{o(!0),await tb(a),ne.success("Retrigger request sent to approver"),n&&await n(),s()}catch(h){console.error("Failed to retrigger pause:",h),ne.error(((d=(c=h==null?void 0:h.response)==null?void 0:c.data)==null?void 0:d.error)||((u=(m=h==null?void 0:h.response)==null?void 0:m.data)==null?void 0:u.message)||"Failed to send retrigger request")}finally{o(!1)}};return e.jsx(nt,{open:t,onOpenChange:s,children:e.jsxs(tt,{className:"sm:max-w-[450px]",children:[e.jsx(it,{children:e.jsxs(st,{className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"w-5 h-5 text-orange-600"}),"Request Resume"]})}),e.jsxs("div",{className:"py-4",children:[e.jsxs("p",{className:"text-sm text-gray-700 mb-4",children:["You are requesting the approver",r?` (${r})`:""," to cancel the pause and resume work on this request."]}),e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-orange-800",children:"A notification will be sent to the approver who paused this workflow, requesting them to resume it."})})]}),e.jsxs(Nt,{children:[e.jsx(R,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(R,{onClick:l,disabled:i,className:"bg-orange-600 hover:bg-orange-700 text-white",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:L1,ActivityTab:O1,WorkNotesTab:$1,SummaryTab:B1,RequestDetailHeader:U1,QuickActionsSidebar:V1,RequestDetailModals:z1}=pp;let H1=class extends p.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("Custom RequestDetail Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(as,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(R,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(R,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function W1({requestId:t,onBack:s,dynamicRequests:a=[]}){var Js,Qs,ot,va,ja,Na;const n=Oa().requestId||t||"",o=new URLSearchParams(window.location.search).get("tab")||"overview",[l,c]=p.useState(o),[d,m]=p.useState(!1),[u,h]=p.useState(null),[x,g]=p.useState(null),[f,j]=p.useState(!1),[w,b]=p.useState(0),[C,v]=p.useState(!1),[N,k]=p.useState(!1),[E,P]=p.useState(!1),{user:M}=Gt(),{request:y,apiRequest:A,loading:L,refreshing:K,refreshDetails:O,currentApprovalLevel:$,isSpectator:T,isInitiator:S,existingParticipants:D,accessDenied:I}=Fo(n,a,M),{mergedMessages:_,unreadWorkNotes:F,workNoteAttachments:G,setWorkNoteAttachments:B}=sp(n,A,l,M),{uploadingDocument:re,triggerFileInput:ae,previewDocument:V,setPreviewDocument:Y,documentPolicy:Z,documentError:U,setDocumentError:ee}=ap(A,O),{showApproveModal:ie,setShowApproveModal:de,showRejectModal:Ae,setShowRejectModal:We,showAddApproverModal:Se,setShowAddApproverModal:Ye,showAddSpectatorModal:Ge,setShowAddSpectatorModal:Oe,showSkipApproverModal:ct,setShowSkipApproverModal:te,showActionStatusModal:xe,setShowActionStatusModal:dt,skipApproverData:ue,setSkipApproverData:Te,actionStatus:Qe,setActionStatus:ht,handleApproveConfirm:et,handleRejectConfirm:qt,handleAddApprover:Es,handleSkipApprover:Xs,handleAddSpectator:H}=rp(n,$,O),{conclusionRemark:me,setConclusionRemark:z,conclusionLoading:fe,conclusionSubmitting:ye,aiGenerated:Re,handleGenerateConclusion:be,handleFinalizeConclusion:Me}=c1(y,n,S,O,s,ht,dt);p.useEffect(()=>{const is=new URLSearchParams(window.location.search).get("tab");is&&c(is)},[n]);const ke=()=>{O()},Le=()=>{v(!0)},Xt=()=>{k(!0)},wt=async()=>{await O()},Ke=()=>{P(!0)},$e=async()=>{await O()},at=async()=>{await O()},zt=async()=>{if(!(A!=null&&A.requestId)){ne.error("Request ID not found");return}if(!u){ne.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},vt=((y==null?void 0:y.status)==="approved"||(y==null?void 0:y.status)==="rejected")&&S,Cs=(y==null?void 0:y.status)==="closed"||(y==null?void 0:y.status)==="approved"&&!S||(y==null?void 0:y.status)==="rejected"&&!S;p.useEffect(()=>{(async()=>{if(!Cs||!(A!=null&&A.requestId)){g(null),h(null);return}try{j(!0);const is=await dp(A.requestId);if(is!=null&&is.summaryId){h(is.summaryId);try{const Ms=await fl(is.summaryId);g(Ms)}catch(Ms){console.error("Failed to fetch summary details:",Ms),g(null),h(null)}}else g(null),h(null)}catch{g(null),h(null)}finally{j(!1)}})()},[Cs,A==null?void 0:A.requestId]);const Is=((y==null?void 0:y.approvalFlow)||[]).filter(Ht=>Ht&&typeof Ht.step=="number").map(Ht=>({levelNumber:Ht.step||0,approverName:Ht.approver||"Unknown",status:Ht.status||"pending",tatHours:Ht.tatHours||24}));return L&&!y&&!A?e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Zt,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading custom request details..."})]})}):I!=null&&I.denied?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"access-denied-state",children:e.jsxs("div",{className:"max-w-lg w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(Fm,{className:"w-10 h-10 text-red-500"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Access Denied"}),e.jsx("p",{className:"text-gray-600 mb-6 leading-relaxed",children:I.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(R,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Rs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(R,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):y?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"custom-request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx(U1,{request:y,refreshing:K,onBack:s||(()=>window.history.back()),onRefresh:ke,onShareSummary:zt,isInitiator:S}),e.jsxs(Jr,{value:l,onValueChange:c,className:"w-full","data-testid":"custom-request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(Qr,{className:"grid grid-cols-3 sm:grid-cols-6 lg:flex lg:flex-row h-auto bg-gray-100 p-1.5 sm:p-1 rounded-lg gap-1.5 sm:gap-1",children:[e.jsxs(gt,{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(_m,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),Cs&&x&&e.jsxs(gt,{value:"summary",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-summary",children:[e.jsx(Ao,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Summary"})]}),e.jsxs(gt,{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(Zs,{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(gt,{value:"documents",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-documents",children:[e.jsx(Ee,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Docs"})]}),e.jsxs(gt,{value:"activity",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 col-span-1 sm:col-span-1","data-testid":"tab-activity",children:[e.jsx(Vt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Activity"})]}),e.jsxs(gt,{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(Ps,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),F>0&&e.jsx(se,{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:F>9?"9+":F})]})]})}),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(ft,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(Lb,{request:y,isInitiator:S,needsClosure:vt,conclusionRemark:me,setConclusionRemark:z,conclusionLoading:fe,conclusionSubmitting:ye,aiGenerated:Re,handleGenerateConclusion:be,handleFinalizeConclusion:Me,onPause:Le,onResume:Xt,onRetrigger:Ke,currentUserIsApprover:!!$,pausedByUserId:(Qs=(Js=y==null?void 0:y.pauseInfo)==null?void 0:Js.pausedBy)==null?void 0:Qs.userId,currentUserId:M==null?void 0:M.userId})}),Cs&&e.jsx(ft,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(B1,{summary:x,loading:f,onShare:zt,isInitiator:S})}),e.jsx(ft,{value:"workflow",className:"mt-0",children:e.jsx(Ub,{request:y,user:M,isInitiator:S,onSkipApprover:Ht=>{if(!Ht.levelId){alert("Level ID not available");return}Te(Ht),te(!0)},onRefresh:O})}),e.jsx(ft,{value:"documents",className:"mt-0",children:e.jsx(L1,{request:y,workNoteAttachments:G,uploadingDocument:re,documentPolicy:Z,triggerFileInput:ae,setPreviewDocument:Y,downloadDocument:_r})}),e.jsx(ft,{value:"activity",className:"mt-0",children:e.jsx(O1,{request:y})}),e.jsx(ft,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:l!=="worknotes",children:e.jsx($1,{requestId:n,requestTitle:y.title,mergedMessages:_,setWorkNoteAttachments:B,isInitiator:S,isSpectator:T,currentLevels:Is,onAddApprover:Es})})]}),l!=="worknotes"&&e.jsx(V1,{request:y,isInitiator:S,isSpectator:T,currentApprovalLevel:$,onAddApprover:()=>Ye(!0),onAddSpectator:()=>Oe(!0),onApprove:()=>de(!0),onReject:()=>We(!0),onPause:Le,onResume:Xt,onRetrigger:Ke,summaryId:u,refreshTrigger:w,pausedByUserId:(va=(ot=y==null?void 0:y.pauseInfo)==null?void 0:ot.pausedBy)==null?void 0:va.userId,currentUserId:M==null?void 0:M.userId,apiRequest:A})]})]})]})}),d&&u&&e.jsx(xp,{isOpen:d,onClose:()=>m(!1),summaryId:u,requestTitle:(y==null?void 0:y.title)||"N/A",onSuccess:()=>{O(),b(Ht=>Ht+1)}}),C&&(A==null?void 0:A.requestId)&&e.jsx(gp,{isOpen:C,onClose:()=>v(!1),requestId:A.requestId,levelId:($==null?void 0:$.levelId)||null,onSuccess:$e}),N&&(A==null?void 0:A.requestId)&&e.jsx(fp,{isOpen:N,onClose:()=>k(!1),requestId:A.requestId,onSuccess:wt}),E&&(A==null?void 0:A.requestId)&&e.jsx(yp,{isOpen:E,onClose:()=>P(!1),requestId:A.requestId,approverName:(Na=(ja=y==null?void 0:y.pauseInfo)==null?void 0:ja.pausedBy)==null?void 0:Na.name,onSuccess:at}),e.jsx(z1,{showApproveModal:ie,showRejectModal:Ae,showAddApproverModal:Se,showAddSpectatorModal:Ge,showSkipApproverModal:ct,showActionStatusModal:xe,previewDocument:V,documentError:U,request:y,skipApproverData:ue,actionStatus:Qe,existingParticipants:D,currentLevels:Is,setShowApproveModal:de,setShowRejectModal:We,setShowAddApproverModal:Ye,setShowAddSpectatorModal:Oe,setShowSkipApproverModal:te,setShowActionStatusModal:dt,setPreviewDocument:Y,setDocumentError:ee,setSkipApproverData:Te,setActionStatus:ht,handleApproveConfirm:et,handleRejectConfirm:qt,handleAddApprover:Es,handleAddSpectator:H,handleSkipApprover:Xs,downloadDocument:_r,documentPolicy:Z})]}):e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"not-found-state",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(Ee,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Custom Request Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The custom request you're looking for doesn't exist or may have been deleted."}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(R,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Rs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(R,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function G1(t){return e.jsx(H1,{children:e.jsx(W1,{...t})})}function K1({request:t,apiRequest:s,currentUserId:a,isInitiator:r,onEditClaimAmount:n,className:i=""}){var m,u,h,x,g,f,j,w,b,C,v,N,k,E,P;if(!yl(s))return e.jsx("div",{className:"text-center py-8 text-gray-500",children:e.jsx("p",{children:"This is not a claim management request."})});const o=mp(s);if(!o)return console.warn("[ClaimManagementOverviewTab] Failed to map claim data:",{apiRequest:s,hasClaimDetails:!!(s!=null&&s.claimDetails),hasProposalDetails:!!(s!=null&&s.proposalDetails),hasCompletionDetails:!!(s!=null&&s.completionDetails)}),e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx("p",{children:"Unable to load claim management data."}),e.jsx("p",{className:"text-xs mt-2",children:"Please ensure the request has been properly initialized."})]});console.debug("[ClaimManagementOverviewTab] Mapped claim data:",{activityInfo:o.activityInfo,dealerInfo:o.dealerInfo,hasProposalDetails:!!o.proposalDetails,closedExpenses:(m=o.activityInfo)==null?void 0:m.closedExpenses,closedExpensesBreakdown:(u=o.activityInfo)==null?void 0:u.closedExpensesBreakdown,hasDealerCode:!!((h=o.dealerInfo)!=null&&h.dealerCode),hasDealerName:!!((x=o.dealerInfo)!=null&&x.dealerName)});const l=up(s,a),c=hp(l);console.debug("[ClaimManagementOverviewTab] User role and visibility:",{userRole:l,visibility:c,currentUserId:a,showDealerInfo:c.showDealerInfo,dealerInfoPresent:!!((g=o.dealerInfo)!=null&&g.dealerCode||(f=o.dealerInfo)!=null&&f.dealerName)});const d={name:((j=s.initiator)==null?void 0:j.name)||((w=s.initiator)==null?void 0:w.displayName)||((b=s.initiator)==null?void 0:b.email)||"Unknown",role:((C=s.initiator)==null?void 0:C.role)||((v=s.initiator)==null?void 0:v.designation)||"Initiator",department:((N=s.initiator)==null?void 0:N.department)||s.department||"",email:((k=s.initiator)==null?void 0:k.email)||"N/A",phone:((E=s.initiator)==null?void 0:E.phone)||((P=s.initiator)==null?void 0:P.mobile)};return e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx(k1,{activityInfo:o.activityInfo}),e.jsx(T1,{dealerInfo:o.dealerInfo}),c.showProposalDetails&&o.proposalDetails&&e.jsx(R1,{proposalDetails:o.proposalDetails}),e.jsx(P1,{initiatorInfo:d})]})}function Y1({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:o,requestNumber:l,requestId:c,dueDate:d}){const[m,u]=p.useState(!1),[h,x]=p.useState(!1),g=(n==null?void 0:n.creditNoteNumber)||"CN-RE-REQ-2024-CM-101-312580",f=n!=null&&n.creditNoteDate?Qt(n.creditNoteDate,{includeTime:!1,format:"short"}):"Dec 5, 2025",j=(n==null?void 0:n.creditNoteAmount)||800,w=(n==null?void 0:n.status)||"APPROVED",b=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",C=(i==null?void 0:i.dealerCode)||"RE-JP-009",v=o||"Activity",N=l||"RE-REQ-2024-CM-101",k=d?Qt(d,{includeTime:!1,format:"short"}):"Jan 4, 2026",E=async()=>{if(a)try{u(!0),await a(),ne.success("Credit note downloaded successfully")}catch(y){console.error("Failed to download credit note:",y),ne.error("Failed to download credit note. Please try again.")}finally{u(!1)}else ne.info("Credit note will be automatically saved to Documents tab")},P=async()=>{if(r)try{x(!0),await r(),ne.success("Credit note sent to dealer successfully"),s()}catch(y){console.error("Failed to send credit note to dealer:",y),ne.error("Failed to send credit note. Please try again.")}finally{x(!1)}else ne.info("Email notification will be sent to dealer with credit note attachment")},M=y=>`₹${y.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(nt,{open:t,onOpenChange:s,children:e.jsxs(tt,{className:"sm:max-w-lg max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(it,{children:[e.jsxs(st,{className:"font-semibold flex items-center gap-2 text-2xl",children:[e.jsx(ms,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note from SAP"]}),e.jsx(Mt,{className:"text-base",children:"Review and send credit note to dealer"})]}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-200 rounded-lg p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-green-900 text-xl mb-1",children:"Royal Enfield"}),e.jsx("p",{className:"text-sm text-green-700",children:"Credit Note Document"})]}),e.jsxs(se,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),w==="APPROVED"?"Approved":w==="ISSUED"?"Issued":w==="SENT"?"Sent":"Pending"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100",children:[e.jsxs(Q,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Kg,{className:"w-3 h-3"}),"Credit Note Number"]}),e.jsx("p",{className:"font-bold text-gray-900 mt-1 text-lg",children:g})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100",children:[e.jsxs(Q,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(qe,{className:"w-3 h-3"}),"Issue Date"]}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:f})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-5",children:[e.jsxs(Q,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-3",children:[e.jsx(_s,{className:"w-4 h-4"}),"Credit Note Amount"]}),e.jsx("p",{className:"text-4xl font-bold text-blue-700",children:M(j)})]}),e.jsxs("div",{className:"bg-purple-50 border-2 border-purple-200 rounded-lg p-5",children:[e.jsxs("h3",{className:"font-semibold text-purple-900 mb-4 flex items-center gap-2",children:[e.jsx(On,{className:"w-5 h-5"}),"Dealer Information"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(Q,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:b})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(Q,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:C})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(Q,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Activity"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:v})]})]})]}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:[e.jsxs("h3",{className:"font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(Ee,{className:"w-4 h-4"}),"Reference Details"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx(Q,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Request ID"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:N})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Due Date"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:k})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Ee,{className:"w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-blue-800",children:[e.jsx("p",{className:"font-semibold mb-2",children:"Available Actions"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-xs",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Download:"})," Credit note will be automatically saved to Documents tab"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Send to Dealer:"})," Email notification will be sent to dealer with credit note attachment"]}),e.jsx("li",{children:"All actions will be recorded in activity trail for audit purposes"})]})]})]})]}),e.jsxs(Nt,{className:"flex-col-reverse gap-2 sm:flex-row flex items-center justify-between sm:justify-between",children:[e.jsx(R,{variant:"outline",onClick:s,disabled:m||h,className:"border-2",children:"Close"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{variant:"outline",onClick:E,disabled:m||h,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(ss,{className:"w-4 h-4 mr-2"}),m?"Downloading...":"Download"]}),e.jsxs(R,{onClick:P,disabled:m||h,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(Im,{className:"w-4 h-4 mr-2"}),h?"Sending...":"Send to Dealer"]})]})]})]})})}function Z1({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",activityName:n="Activity",requestId:i}){const[o,l]=p.useState(""),[c,d]=p.useState(""),[m,u]=p.useState([]),[h,x]=p.useState([]),[g,f]=p.useState([]),[j,w]=p.useState([]),[b,C]=p.useState(null),[v,N]=p.useState(""),[k,E]=p.useState(!1),P=p.useRef(null),M=p.useRef(null),y=p.useRef(null),A=p.useRef(null),L=p.useMemo(()=>m.reduce((Z,U)=>Z+(U.amount||0),0),[m]),K=p.useMemo(()=>{const Z=o!=="",U=h.length>0,ee=g.length>0,ie=v.trim().length>0;return Z&&U&&ee&&ie},[o,h,g,v]),O=new Date().toISOString().split("T")[0],$=()=>{u([...m,{id:Date.now().toString(),description:"",amount:0}])},T=(Z,U,ee)=>{u(m.map(ie=>ie.id===Z?{...ie,[U]:ee}:ie))},S=Z=>{u(m.filter(U=>U.id!==Z))},D=Z=>{const U=Array.from(Z.target.files||[]);if(U.length>0){const ee=[".pdf",".doc",".docx",".zip",".rar"];if(U.filter(de=>!ee.some(Ae=>de.name.toLowerCase().endsWith(Ae))).length>0){ne.error("Please upload PDF, DOC, DOCX, ZIP, or RAR files only");return}x([...h,...U])}},I=Z=>{x(h.filter((U,ee)=>ee!==Z))},_=Z=>{const U=Array.from(Z.target.files||[]);if(U.length>0){if(U.filter(ie=>!ie.type.startsWith("image/")).length>0){ne.error("Please upload image files only (JPG, PNG, etc.)");return}f([...g,...U])}},F=Z=>{f(g.filter((U,ee)=>ee!==Z))},G=Z=>{const U=Array.from(Z.target.files||[]);if(U.length>0){const ee=[".pdf",".jpg",".jpeg",".png"];if(U.filter(de=>!ee.some(Ae=>de.name.toLowerCase().endsWith(Ae))).length>0){ne.error("Please upload PDF, JPG, or PNG files only");return}w([...j,...U])}},B=Z=>{w(j.filter((U,ee)=>ee!==Z))},re=Z=>{var ee,ie;const U=(ee=Z.target.files)==null?void 0:ee[0];if(U){const de=[".pdf",".xlsx",".xls",".csv"],Ae="."+((ie=U.name.split(".").pop())==null?void 0:ie.toLowerCase());if(!de.includes(Ae)){ne.error("Please upload PDF, Excel, or CSV files only");return}C(U)}},ae=async()=>{if(!K){ne.error("Please fill all required fields");return}const Z=m.filter(U=>U.description.trim()!==""&&U.amount>0);try{E(!0),await a({activityCompletionDate:o,numberOfParticipants:c?parseInt(c):void 0,closedExpenses:Z,totalClosedExpenses:L,completionDocuments:h,activityPhotos:g,invoicesReceipts:j.length>0?j:void 0,attendanceSheet:b||void 0,completionDescription:v}),V(),s()}catch(U){console.error("Failed to submit completion documents:",U),ne.error("Failed to submit completion documents. Please try again.")}finally{E(!1)}},V=()=>{l(""),d(""),u([]),x([]),f([]),w([]),C(null),N(""),P.current&&(P.current.value=""),M.current&&(M.current.value=""),y.current&&(y.current.value=""),A.current&&(A.current.value="")},Y=()=>{k||(V(),s())};return e.jsx(nt,{open:t,onOpenChange:Y,children:e.jsxs(tt,{className:"sm:max-w-lg max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(it,{children:[e.jsxs(st,{className:"font-semibold flex items-center gap-2 text-2xl",children:[e.jsx(ys,{className:"w-6 h-6 text-[--re-green]"}),"Activity Completion Documents"]}),e.jsx(Mt,{className:"text-base",children:"Step 5: Upload completion proof and final documents"}),e.jsxs("div",{className:"space-y-1 mt-2 text-sm text-gray-600",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",r]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",n]}),e.jsx("div",{className:"mt-2",children:"Please upload completion documents, photos, and provide details about the completed activity."})]})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{className:"text-base font-semibold flex items-center gap-2",htmlFor:"completionDate",children:[e.jsx(qe,{className:"w-4 h-4"}),"Activity Completion Date *"]}),e.jsx(we,{type:"date",id:"completionDate",max:O,value:o,onChange:Z=>l(Z.target.value)})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Closed Expenses"}),e.jsx(se,{className:"bg-secondary text-secondary-foreground text-xs",children:"Optional"})]}),e.jsxs(R,{type:"button",onClick:$,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(Ws,{className:"w-4 h-4 mr-1"}),"Add Expense"]})]}),e.jsxs("div",{className:"space-y-3",children:[m.map(Z=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx("div",{className:"flex-1",children:e.jsx(we,{placeholder:"Item name (e.g., Venue rental, Refreshments, Printing)",value:Z.description,onChange:U=>T(Z.id,"description",U.target.value)})}),e.jsx("div",{className:"w-40",children:e.jsx(we,{type:"number",placeholder:"Amount",min:"0",step:"0.01",value:Z.amount||"",onChange:U=>T(Z.id,"amount",parseFloat(U.target.value)||0)})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"mt-0.5 hover:bg-red-100 hover:text-red-700",onClick:()=>S(Z.id),children:e.jsx(ut,{className:"w-4 h-4"})})]},Z.id)),m.length===0&&e.jsx("p",{className:"text-sm text-gray-500 italic",children:'No expenses added. Click "Add Expense" to add expense items.'}),m.length>0&&L>0&&e.jsx("div",{className:"pt-2 border-t",children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold",children:"Total Closed Expenses:"}),e.jsxs("span",{className:"font-semibold text-lg",children:["₹",L.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Completion Evidence"}),e.jsx(se,{className:"bg-destructive text-white text-xs",children:"Required"})]}),e.jsxs("div",{children:[e.jsxs(Q,{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(Ee,{className:"w-4 h-4"}),"Completion Documents *"]}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Upload documents proving activity completion (reports, certificates, etc.) - Can upload multiple files or ZIP folder"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-4 hover:border-blue-500 transition-colors",children:[e.jsx("input",{ref:P,type:"file",multiple:!0,accept:".pdf,.doc,.docx,.zip,.rar",className:"hidden",id:"completionDocs",onChange:D}),e.jsxs("label",{htmlFor:"completionDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(ys,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload documents (PDF, DOC, ZIP - multiple files allowed)"})]})]}),h.length>0&&e.jsx("div",{className:"mt-2 space-y-1",children:h.map((Z,U)=>e.jsxs("div",{className:"flex items-center justify-between bg-gray-50 p-2 rounded text-sm",children:[e.jsx("span",{className:"truncate flex-1",children:Z.name}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>I(U),children:e.jsx(ut,{className:"w-3 h-3"})})]},U))})]}),e.jsxs("div",{children:[e.jsxs(Q,{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(Bi,{className:"w-4 h-4"}),"Activity Photos *"]}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Upload photos from the completed activity (event photos, installations, etc.)"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-4 hover:border-blue-500 transition-colors",children:[e.jsx("input",{ref:M,type:"file",multiple:!0,accept:"image/*",className:"hidden",id:"completionPhotos",onChange:_}),e.jsxs("label",{htmlFor:"completionPhotos",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(Bi,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload photos (JPG, PNG - multiple files allowed)"})]})]}),g.length>0&&e.jsx("div",{className:"mt-2 space-y-1",children:g.map((Z,U)=>e.jsxs("div",{className:"flex items-center justify-between bg-gray-50 p-2 rounded text-sm",children:[e.jsx("span",{className:"truncate flex-1",children:Z.name}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>F(U),children:e.jsx(ut,{className:"w-3 h-3"})})]},U))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Supporting Documents"}),e.jsx(se,{className:"bg-secondary text-secondary-foreground text-xs",children:"Optional"})]}),e.jsxs("div",{children:[e.jsxs(Q,{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(ms,{className:"w-4 h-4"}),"Invoices / Receipts"]}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Upload invoices and receipts for expenses incurred"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-4 hover:border-blue-500 transition-colors",children:[e.jsx("input",{ref:y,type:"file",multiple:!0,accept:".pdf,.jpg,.jpeg,.png",className:"hidden",id:"invoiceReceipts",onChange:G}),e.jsxs("label",{htmlFor:"invoiceReceipts",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(ms,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload invoices/receipts (PDF, JPG, PNG)"})]})]}),j.length>0&&e.jsx("div",{className:"mt-2 space-y-1",children:j.map((Z,U)=>e.jsxs("div",{className:"flex items-center justify-between bg-gray-50 p-2 rounded text-sm",children:[e.jsx("span",{className:"truncate flex-1",children:Z.name}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>B(U),children:e.jsx(ut,{className:"w-3 h-3"})})]},U))})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-base font-semibold",children:"Attendance Sheet / Participant List"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Upload attendance records or participant lists (if applicable)"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-4 hover:border-blue-500 transition-colors",children:[e.jsx("input",{ref:A,type:"file",accept:".pdf,.xlsx,.xls,.csv",className:"hidden",id:"attendanceDoc",onChange:re}),e.jsxs("label",{htmlFor:"attendanceDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(ys,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload attendance sheet (Excel, PDF, CSV)"})]})]}),b&&e.jsxs("div",{className:"mt-2 flex items-center justify-between bg-gray-50 p-2 rounded text-sm",children:[e.jsx("span",{className:"truncate flex-1",children:b.name}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>{C(null),A.current&&(A.current.value="")},children:e.jsx(ut,{className:"w-3 h-3"})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{className:"text-base font-semibold flex items-center gap-2",htmlFor:"completionDescription",children:"Brief Description of Completion *"}),e.jsx(ns,{id:"completionDescription",placeholder:"Provide a brief description of the completed activity, including key highlights, outcomes, challenges faced, and any relevant observations...",value:v,onChange:Z=>N(Z.target.value),className:"min-h-[120px]"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[v.length," characters"]})]}),!K&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Ie,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-amber-800",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Missing Required Information"}),e.jsx("p",{children:"Please ensure completion date, at least one document/photo, and description are provided before submitting."})]})]})]}),e.jsxs(Nt,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",children:[e.jsx(R,{variant:"outline",onClick:Y,disabled:k,className:"border-2",children:"Cancel"}),e.jsx(R,{onClick:ae,disabled:k||!K,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:k?"Submitting...":"Submit Documents"})]})]})})}function X1({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",activityName:n="Activity",requestId:i}){const[o,l]=p.useState(null),[c,d]=p.useState([{id:"1",description:"",amount:0}]),[m,u]=p.useState("date"),[h,x]=p.useState(""),[g,f]=p.useState(""),[j,w]=p.useState([]),[b,C]=p.useState(""),[v,N]=p.useState(!1),k=p.useRef(null),E=p.useRef(null),P=p.useMemo(()=>c.reduce((_,F)=>_+(F.amount||0),0),[c]),M=p.useMemo(()=>{const _=o!==null,F=c.length>0&&c.every(re=>re.description.trim()!==""&&re.amount>0),G=m==="date"?h!=="":g!==""&&parseInt(g)>0,B=b.trim().length>0;return _&&F&&G&&B},[o,c,m,h,g,b]),y=_=>{var G,B;const F=(G=_.target.files)==null?void 0:G[0];if(F){const re=[".pdf",".doc",".docx"],ae="."+((B=F.name.split(".").pop())==null?void 0:B.toLowerCase());if(!re.includes(ae)){ne.error("Please upload a PDF, DOC, or DOCX file");return}l(F)}},A=_=>{const F=Array.from(_.target.files||[]);w(G=>[...G,...F])},L=()=>{d(_=>[..._,{id:Date.now().toString(),description:"",amount:0}])},K=_=>{c.length>1&&d(F=>F.filter(G=>G.id!==_))},O=(_,F,G)=>{d(B=>B.map(re=>re.id===_?{...re,[F]:F==="amount"?parseFloat(G.toString())||0:G}:re))},$=_=>{w(F=>F.filter((G,B)=>B!==_))},T=async()=>{if(!M){ne.error("Please fill all required fields");return}let _=h||"";if(m==="days"&&g){const F=parseInt(g),G=new Date;G.setDate(G.getDate()+F),_=G.toISOString().split("T")[0]}try{N(!0),await a({proposalDocument:o,costBreakup:c.filter(F=>F.description.trim()!==""&&F.amount>0),expectedCompletionDate:_,otherDocuments:j,dealerComments:b}),S(),s()}catch(F){console.error("Failed to submit proposal:",F),ne.error("Failed to submit proposal. Please try again.")}finally{N(!1)}},S=()=>{l(null),d([{id:"1",description:"",amount:0}]),u("date"),x(""),f(""),w([]),C(""),k.current&&(k.current.value=""),E.current&&(E.current.value="")},D=()=>{v||(S(),s())},I=new Date().toISOString().split("T")[0];return e.jsx(nt,{open:t,onOpenChange:D,children:e.jsxs(tt,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(it,{children:[e.jsxs(st,{className:"flex items-center gap-2 text-2xl",children:[e.jsx(ys,{className:"w-6 h-6 text-[--re-green]"}),"Dealer Proposal Submission"]}),e.jsx(Mt,{className:"text-base",children:"Step 1: Upload proposal and planning details"}),e.jsxs("div",{className:"space-y-1 mt-2 text-sm text-gray-600",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",r]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",n]}),e.jsx("div",{className:"mt-2",children:"Please upload proposal document, provide cost breakdown, timeline, and detailed comments."})]})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Proposal Document"}),e.jsx(se,{className:"bg-red-500 text-white text-xs",children:"Required"})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-base font-semibold flex items-center gap-2",children:"Proposal Document *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Detailed proposal with activity details and requested information"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-4 hover:border-blue-500 transition-colors",children:[e.jsx("input",{ref:k,type:"file",accept:".pdf,.doc,.docx",className:"hidden",id:"proposalDoc",onChange:y}),e.jsxs("label",{htmlFor:"proposalDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(ys,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:o?o.name:"Click to upload proposal (PDF, DOC, DOCX)"})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Cost Breakup"}),e.jsx(se,{className:"bg-red-500 text-white text-xs",children:"Required"})]}),e.jsxs(R,{type:"button",onClick:L,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(Ws,{className:"w-4 h-4 mr-1"}),"Add Item"]})]}),e.jsx("div",{className:"space-y-3",children:c.map(_=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx("div",{className:"flex-1",children:e.jsx(we,{placeholder:"Item description (e.g., Banner printing, Event setup)",value:_.description,onChange:F=>O(_.id,"description",F.target.value)})}),e.jsx("div",{className:"w-40",children:e.jsx(we,{type:"number",placeholder:"Amount",min:"0",step:"0.01",value:_.amount||"",onChange:F=>O(_.id,"amount",F.target.value)})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"mt-0.5 hover:bg-red-100 hover:text-red-700",onClick:()=>K(_.id),disabled:c.length===1,children:e.jsx(ut,{className:"w-4 h-4"})})]},_.id))}),e.jsx("div",{className:"border-2 border-gray-300 rounded-lg p-4 bg-white",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"w-5 h-5 text-gray-700"}),e.jsx("span",{className:"font-semibold text-gray-900",children:"Estimated Budget"})]}),e.jsxs("div",{className:"text-2xl font-bold text-gray-900",children:["₹",P.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Timeline for Closure"}),e.jsx(se,{className:"bg-red-500 text-white text-xs",children:"Required"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{type:"button",onClick:()=>u("date"),className:m==="date"?"bg-[#2d4a3e] hover:bg-[#1f3329] text-white":"border-2 hover:bg-gray-50",size:"sm",children:[e.jsx(qe,{className:"w-4 h-4 mr-1"}),"Specific Date"]}),e.jsx(R,{type:"button",onClick:()=>u("days"),className:m==="days"?"bg-[#2d4a3e] hover:bg-[#1f3329] text-white":"border-2 hover:bg-gray-50",size:"sm",children:"Number of Days"})]}),m==="date"?e.jsxs("div",{children:[e.jsx(Q,{className:"text-sm font-medium mb-2 block",children:"Expected Completion Date"}),e.jsx(we,{type:"date",min:I,value:h,onChange:_=>x(_.target.value)})]}):e.jsxs("div",{children:[e.jsx(Q,{className:"text-sm font-medium mb-2 block",children:"Number of Days"}),e.jsx(we,{type:"number",placeholder:"Enter number of days",min:"1",value:g,onChange:_=>f(_.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Other Supporting Documents"}),e.jsx(se,{variant:"secondary",className:"text-xs",children:"Optional"})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"flex items-center gap-2 text-base font-semibold",children:"Additional Documents"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Any other supporting documents (invoices, receipts, photos, etc.)"}),e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-4 hover:border-blue-500 transition-colors",children:[e.jsx("input",{ref:E,type:"file",multiple:!0,className:"hidden",id:"otherDocs",onChange:A}),e.jsxs("label",{htmlFor:"otherDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:[e.jsx(ys,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload additional documents (multiple files allowed)"})]})]}),j.length>0&&e.jsx("div",{className:"mt-2 space-y-1",children:j.map((_,F)=>e.jsxs("div",{className:"flex items-center justify-between bg-gray-50 p-2 rounded text-sm",children:[e.jsx("span",{className:"text-gray-700",children:_.name}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-red-100",onClick:()=>$(F),children:e.jsx(ut,{className:"w-3 h-3"})})]},F))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"dealerComments",className:"text-base font-semibold flex items-center gap-2",children:"Dealer Comments / Details *"}),e.jsx(ns,{id:"dealerComments",placeholder:"Provide detailed comments about this claim request, including any special considerations, execution details, or additional information...",value:b,onChange:_=>C(_.target.value),className:"min-h-[120px]"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[b.length," characters"]})]}),!M&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Ie,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-amber-800",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Missing Required Information"}),e.jsx("p",{children:"Please ensure proposal document, cost breakup, timeline, and dealer comments are provided before submitting."})]})]})]}),e.jsxs(Nt,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",children:[e.jsx(R,{variant:"outline",onClick:D,disabled:v,className:"border-2",children:"Cancel"}),e.jsx(R,{onClick:T,disabled:!M||v,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:v?"Submitting...":"Submit Documents"})]})]})})}function J1({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n,requestId:i,preFilledIONumber:o,preFilledBlockedAmount:l}){const[c,d]=p.useState("approve"),[m,u]=p.useState(o||""),[h,x]=p.useState(""),[g,f]=p.useState(""),[j,w]=p.useState(!1);p.useEffect(()=>{t&&o&&u(o)},[t,o]);const b=h.length,C=g.length,v=300,N=500,k=p.useMemo(()=>(c==="reject"||m.trim().length>0&&h.trim().length>0)&&g.trim().length>0,[c,m,h,g]),E=async()=>{if(!k){if(c==="approve"){if(!m.trim()){ne.error("Please enter IO number");return}if(!h.trim()){ne.error("Please enter IO remark");return}}if(!g.trim()){ne.error("Please provide comments");return}return}try{w(!0),c==="approve"?await a({ioNumber:m.trim(),ioRemark:h.trim(),comments:g.trim()}):await r(g.trim()),P(),s()}catch(y){console.error(`Failed to ${c} request:`,y),ne.error(`Failed to ${c} request. Please try again.`)}finally{w(!1)}},P=()=>{d("approve"),u(o||""),x(""),f("")},M=()=>{j||(P(),s())};return e.jsx(nt,{open:t,onOpenChange:M,children:e.jsxs(tt,{className:"max-w-2xl",children:[e.jsxs(it,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 rounded-lg bg-green-100",children:e.jsx(Ce,{className:"w-6 h-6 text-green-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(st,{className:"font-semibold text-xl",children:"Approve and Organise IO"}),e.jsx(Mt,{className:"text-sm mt-1",children:"Enter blocked IO details and provide your approval comments"})]})]}),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:"Workflow Step:"}),e.jsx(se,{variant:"outline",className:"font-mono",children:"Step 3"})]}),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(se,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"}),"APPROVE"]})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2 p-1 bg-gray-100 rounded-lg",children:[e.jsxs(R,{type:"button",onClick:()=>d("approve"),className:`flex-1 ${c==="approve"?"bg-green-600 text-white shadow-sm":"text-gray-700 hover:bg-gray-200"}`,variant:c==="approve"?"default":"ghost",children:[e.jsx(Ce,{className:"w-4 h-4 mr-1"}),"Approve"]}),e.jsxs(R,{type:"button",onClick:()=>d("reject"),className:`flex-1 ${c==="reject"?"bg-red-600 text-white shadow-sm":"text-gray-700 hover:bg-gray-200"}`,variant:c==="reject"?"destructive":"ghost",children:[e.jsx(yt,{className:"w-4 h-4 mr-1"}),"Reject"]})]}),c==="approve"&&e.jsxs("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-lg space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ms,{className:"w-4 h-4 text-blue-600"}),e.jsx("h4",{className:"font-semibold text-blue-900",children:"IO Organisation Details"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Q,{htmlFor:"ioNumber",className:"text-sm font-semibold text-gray-900 flex items-center gap-2",children:["Blocked IO Number ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(we,{id:"ioNumber",placeholder:"Enter IO number from SAP",value:m,onChange:y=>u(y.target.value),className:"bg-white h-8"}),o&&e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"Pre-filled from IO tab"})]}),l!==void 0&&l>0&&e.jsxs("div",{className:"p-2 bg-green-50 border border-green-200 rounded",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-semibold text-gray-700",children:"Blocked Amount:"}),e.jsxs("span",{className:"text-sm font-bold text-green-700",children:["₹",l.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsx("p",{className:"text-xs text-gray-600 mt-1",children:"Amount already blocked in SAP from IO tab"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Q,{htmlFor:"ioRemark",className:"text-sm font-semibold text-gray-900 flex items-center gap-2",children:["IO Remark ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ns,{id:"ioRemark",placeholder:"Enter remarks about IO blocking",value:h,onChange:y=>{const A=y.target.value;A.length<=v&&x(A)},rows:2,className:"bg-white text-sm min-h-[60px] resize-none"}),e.jsx("div",{className:"flex justify-end text-xs text-gray-600",children:e.jsxs("span",{children:[b,"/",v]})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(Q,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900 flex items-center gap-2",children:["Comments & Remarks ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ns,{id:"comment",placeholder:c==="approve"?"Enter your approval comments and any conditions or notes...":"Enter detailed reasons for rejection...",value:g,onChange:y=>{const A=y.target.value;A.length<=N&&f(A)},rows:4,className:"text-sm min-h-[80px] resize-none"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(as,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[C,"/",N]})]})]})]}),e.jsxs(Nt,{className:"flex flex-col-reverse sm:flex-row sm:justify-end gap-2",children:[e.jsx(R,{variant:"outline",onClick:M,disabled:j,children:"Cancel"}),e.jsx(R,{onClick:E,disabled:!k||j,className:`${c==="approve"?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700"} text-white`,children:j?`${c==="approve"?"Approving":"Rejecting"}...`:e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),c==="approve"?"Approve Request":"Reject Request"]})})]})]})})}function Q1({isOpen:t,onClose:s,onPush:a,completionDetails:r,ioDetails:n,requestTitle:i,requestNumber:o}){const[l,c]=p.useState(""),[d,m]=p.useState(!1),u=l.length,h=500,x=p.useMemo(()=>r!=null&&r.totalClosedExpenses?r.totalClosedExpenses:r!=null&&r.closedExpenses&&Array.isArray(r.closedExpenses)?r.closedExpenses.reduce((C,v)=>{const N=typeof v=="object"&&v.amount||0;return C+(Number(N)||0)},0):0,[r]),g=C=>{if(!C)return"—";try{return new Date(C).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return C}},f=C=>`₹${C.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,j=async()=>{if(!l.trim()){ne.error("Please provide comments before pushing to DMS");return}try{m(!0),await a(l.trim()),w(),s()}catch(C){console.error("Failed to push to DMS:",C),ne.error("Failed to push to DMS. Please try again.")}finally{m(!1)}},w=()=>{c("")},b=()=>{d||(w(),s())};return e.jsx(nt,{open:t,onOpenChange:b,children:e.jsxs(tt,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(it,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 rounded-lg bg-indigo-100",children:e.jsx(Vt,{className:"w-6 h-6 text-indigo-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(st,{className:"font-semibold text-xl",children:"Push to DMS - Verification"}),e.jsx(Mt,{className:"text-sm mt-1",children:"Review completion details and expenses before pushing to DMS for e-invoice generation"})]})]}),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:"Workflow Step:"}),e.jsx(se,{variant:"outline",className:"font-mono",children:"Step 6"})]}),o&&e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Request Number:"}),e.jsx("p",{className:"text-gray-700 mt-1 font-mono",children:o})]}),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:i||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Action:"}),e.jsxs(se,{className:"bg-indigo-100 text-indigo-800 border-indigo-200",children:[e.jsx(Vt,{className:"w-3 h-3 mr-1"}),"PUSH TO DMS"]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs(X,{children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Er,{className:"w-5 h-5 text-green-600"}),"Completion Details"]}),e.jsx(je,{children:"Review activity completion information"})]}),e.jsxs(J,{className:"space-y-3",children:[r.activityCompletionDate&&e.jsxs("div",{className:"flex items-center justify-between py-2 border-b",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Activity Completion Date:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:g(r.activityCompletionDate)})]}),r.numberOfParticipants!==void 0&&e.jsxs("div",{className:"flex items-center justify-between py-2 border-b",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Number of Participants:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:r.numberOfParticipants})]}),r.completionDescription&&e.jsxs("div",{className:"pt-2",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Completion Description:"}),e.jsx("p",{className:"text-sm text-gray-900",children:r.completionDescription})]})]})]}),(r==null?void 0:r.closedExpenses)&&r.closedExpenses.length>0&&e.jsxs(X,{children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-lg",children:[e.jsx(_s,{className:"w-5 h-5 text-blue-600"}),"Expense Breakdown"]}),e.jsx(je,{children:"Review closed expenses before pushing to DMS"})]}),e.jsx(J,{children:e.jsxs("div",{className:"space-y-2",children:[r.closedExpenses.map((C,v)=>e.jsxs("div",{className:"flex items-center justify-between py-2 px-3 bg-gray-50 rounded border",children:[e.jsx("div",{className:"flex-1",children:e.jsx("p",{className:"text-sm font-medium text-gray-900",children:C.description||`Expense ${v+1}`})}),e.jsx("div",{className:"ml-4",children:e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:f(typeof C=="object"&&C.amount||0)})})]},v)),e.jsxs("div",{className:"flex items-center justify-between py-3 px-3 bg-blue-50 rounded border-2 border-blue-200 mt-3",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:"Total Closed Expenses:"}),e.jsx("span",{className:"text-lg font-bold text-blue-700",children:f(x)})]})]})})]}),n&&n.ioNumber&&e.jsxs(X,{children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ms,{className:"w-5 h-5 text-purple-600"}),"IO Details"]}),e.jsx(je,{children:"Internal Order information for budget reference"})]}),e.jsxs(J,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between py-2 border-b",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"IO Number:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900 font-mono",children:n.ioNumber})]}),n.blockedAmount!==void 0&&n.blockedAmount>0&&e.jsxs("div",{className:"flex items-center justify-between py-2 border-b",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Blocked Amount:"}),e.jsx("span",{className:"text-sm font-bold text-green-700",children:f(n.blockedAmount)})]}),n.remainingBalance!==void 0&&e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Remaining Balance:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:f(n.remainingBalance)})]})]})]}),e.jsx("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(as,{className:"w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-yellow-900",children:"Please verify all details before pushing to DMS"}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1",children:"Once pushed, the system will automatically generate an e-invoice and the workflow will proceed to Step 7."})]})]})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(Q,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900 flex items-center gap-2",children:["Comments & Remarks ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ns,{id:"comment",placeholder:"Enter your comments about pushing to DMS (e.g., verified expenses, ready for invoice generation)...",value:l,onChange:C=>{const v=C.target.value;v.length<=h&&c(v)},rows:4,className:"text-sm min-h-[80px] resize-none"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(as,{className:"w-3 h-3"}),"Required and visible to all"]}),e.jsxs("span",{children:[u,"/",h]})]})]})]}),e.jsxs(Nt,{className:"flex flex-col-reverse sm:flex-row sm:justify-end gap-2",children:[e.jsx(R,{variant:"outline",onClick:b,disabled:d,children:"Cancel"}),e.jsx(R,{onClick:j,disabled:!l.trim()||d,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:d?"Pushing to DMS...":e.jsxs(e.Fragment,{children:[e.jsx(Vt,{className:"w-4 h-4 mr-2"}),"Push to DMS"]})})]})]})})}function q1({isOpen:t,onClose:s,stepNumber:a,stepName:r,requestNumber:n="RE-REQ-2024-CM-101",recipientEmail:i="system@royalenfield.com",subject:o,emailBody:l}){const c=`System Notification: Activity Created - ${n}`,d=o||c,m=`System Notification Activity has been automatically created for claim ${n}. All stakeholders have been notified. This is an automated message.`,u=l||m;return e.jsx(nt,{open:t,onOpenChange:s,children:e.jsxs(tt,{className:"sm:max-w-2xl max-w-2xl",children:[e.jsx(it,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center",children:e.jsx(aa,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(st,{className:"text-lg leading-none font-semibold",children:"Email Notification Template"}),e.jsxs(Mt,{className:"text-sm",children:["Step ",a,": ",r]})]})]})})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-4 border border-blue-200",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-gray-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs text-gray-600",children:"To:"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:i})]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(aa,{className:"w-4 h-4 text-gray-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs text-gray-600",children:"Subject:"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:d})]})]})]})}),e.jsx("div",{className:"bg-white rounded-lg border border-gray-200 p-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-3 border-b border-gray-200",children:[e.jsx(On,{className:"w-5 h-5 text-purple-600"}),e.jsx("span",{className:"font-semibold text-gray-900",children:"Royal Enfield"})]}),e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("pre",{className:"whitespace-pre-wrap font-sans text-sm text-gray-700 leading-relaxed bg-transparent p-0 border-0",children:u})}),e.jsx("div",{className:"pt-3 border-t border-gray-200",children:e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx(qe,{className:"w-3 h-3"}),e.jsx("span",{children:"Automated email • Royal Enfield Claims Portal"})]})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(se,{className:"bg-blue-50 text-blue-700 border-blue-200",children:["Step ",a]}),e.jsx(se,{className:"bg-purple-50 text-purple-700 border-purple-200",children:"Auto-triggered"})]})]}),e.jsx("div",{className:"flex justify-end gap-2 pt-2",children:e.jsxs(R,{variant:"outline",onClick:s,className:"h-9",children:[e.jsx(ut,{className:"w-4 h-4 mr-2"}),"Close"]})})]})})}function e2({isOpen:t,onClose:s,onApprove:a,onReject:r,proposalData:n,dealerName:i="Dealer",activityName:o="Activity",requestId:l}){const[c,d]=p.useState(""),[m,u]=p.useState(!1),[h,x]=p.useState(null),g=p.useMemo(()=>{if(!(n!=null&&n.costBreakup))return 0;const v=Array.isArray(n.costBreakup)?n.costBreakup:typeof n.costBreakup=="string"?JSON.parse(n.costBreakup):[];return Array.isArray(v)?v.reduce((N,k)=>{const E=typeof k=="object"&&k.amount||0;return N+(Number(E)||0)},0):0},[n]),f=v=>{if(!v)return"—";try{return new Date(v).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return v}},j=async()=>{if(!c.trim()){ne.error("Please provide approval comments");return}try{u(!0),x("approve"),await a(c),b(),s()}catch(v){console.error("Failed to approve proposal:",v),ne.error("Failed to approve proposal. Please try again.")}finally{u(!1),x(null)}},w=async()=>{if(!c.trim()){ne.error("Please provide rejection reason");return}try{u(!0),x("reject"),await r(c),b(),s()}catch(v){console.error("Failed to reject proposal:",v),ne.error("Failed to reject proposal. Please try again.")}finally{u(!1),x(null)}},b=()=>{d(""),x(null)},C=()=>{m||(b(),s())};return t?e.jsx(nt,{open:t,onOpenChange:C,children:e.jsxs(tt,{className:"max-w-4xl max-h-[90vh] flex flex-col p-0 overflow-hidden",children:[e.jsxs(it,{className:"px-6 pt-6 pb-4 flex-shrink-0 border-b",children:[e.jsxs(st,{className:"flex items-center gap-2 text-2xl",children:[e.jsx(Ce,{className:"w-6 h-6 text-green-600"}),"Requestor Evaluation & Confirmation"]}),e.jsx(Mt,{className:"text-base",children:"Step 2: Review dealer proposal and make a decision"}),e.jsxs("div",{className:"space-y-1 mt-2 text-sm text-gray-600",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",i]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",o]}),e.jsxs("div",{className:"mt-2 text-amber-600 font-medium",children:["Decision: ",e.jsx("strong",{children:"Confirms?"})," (YES → Continue to Dept Lead / NO → Request is cancelled)"]})]})]}),e.jsxs("div",{className:"space-y-6 py-4 px-6 overflow-y-auto flex-1",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-lg flex items-center gap-2",children:[e.jsx(Ee,{className:"w-5 h-5 text-blue-600"}),"Proposal Document"]})}),n!=null&&n.proposalDocument?e.jsxs("div",{className:"border rounded-lg p-4 bg-gray-50 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ee,{className:"w-8 h-8 text-blue-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:n.proposalDocument.name}),(n==null?void 0:n.submittedAt)&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Submitted on ",f(n.submittedAt)]})]})]}),e.jsx("div",{className:"flex gap-2",children:n.proposalDocument.url&&e.jsxs(e.Fragment,{children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>{var v;return window.open((v=n.proposalDocument)==null?void 0:v.url,"_blank")},children:[e.jsx(rs,{className:"w-4 h-4 mr-1"}),"View"]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>{var N,k;const v=document.createElement("a");v.href=((N=n.proposalDocument)==null?void 0:N.url)||"",v.download=((k=n.proposalDocument)==null?void 0:k.name)||"",v.click()},children:[e.jsx(ss,{className:"w-4 h-4 mr-1"}),"Download"]})]})})]}):e.jsx("p",{className:"text-sm text-gray-500 italic",children:"No proposal document available"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-lg flex items-center gap-2",children:[e.jsx(_s,{className:"w-5 h-5 text-green-600"}),"Cost Breakup"]})}),(()=>{const v=n!=null&&n.costBreakup?Array.isArray(n.costBreakup)?n.costBreakup:typeof n.costBreakup=="string"?JSON.parse(n.costBreakup):[]:[];return v&&Array.isArray(v)&&v.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsx("div",{className:"bg-gray-50 px-4 py-2 border-b",children:e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm font-semibold text-gray-700",children:[e.jsx("div",{children:"Item Description"}),e.jsx("div",{className:"text-right",children:"Amount"})]})}),e.jsx("div",{className:"divide-y",children:v.map((N,k)=>e.jsxs("div",{className:"px-4 py-3 grid grid-cols-2 gap-4",children:[e.jsx("div",{className:"text-sm text-gray-700",children:(N==null?void 0:N.description)||"N/A"}),e.jsxs("div",{className:"text-sm font-semibold text-gray-900 text-right",children:["₹",(Number(N==null?void 0:N.amount)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]},(N==null?void 0:N.id)||(N==null?void 0:N.description)||k))})]}),e.jsx("div",{className:"border-2 border-[--re-green] rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"w-5 h-5 text-[--re-green]"}),e.jsx("span",{className:"font-semibold text-gray-700",children:"Total Estimated Budget"})]}),e.jsxs("div",{className:"text-2xl font-bold text-[--re-green]",children:["₹",g.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}):e.jsx("p",{className:"text-sm text-gray-500 italic",children:"No cost breakdown available"})})()]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-lg flex items-center gap-2",children:[e.jsx(qe,{className:"w-5 h-5 text-purple-600"}),"Expected Completion Date"]})}),e.jsx("div",{className:"border rounded-lg p-4 bg-gray-50",children:e.jsx("p",{className:"text-lg font-semibold text-gray-900",children:n!=null&&n.expectedCompletionDate?f(n.expectedCompletionDate):"Not specified"})})]}),(n==null?void 0:n.otherDocuments)&&n.otherDocuments.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h3",{className:"font-semibold text-lg flex items-center gap-2",children:[e.jsx(Ee,{className:"w-5 h-5 text-gray-600"}),"Other Supporting Documents"]}),e.jsxs(se,{variant:"secondary",className:"text-xs",children:[n.otherDocuments.length," file(s)"]})]}),e.jsx("div",{className:"space-y-2",children:n.otherDocuments.map((v,N)=>e.jsxs("div",{className:"border rounded-lg p-3 bg-gray-50 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ee,{className:"w-5 h-5 text-gray-600"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:v.name})]}),v.url&&e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>window.open(v.url,"_blank"),children:e.jsx(ss,{className:"w-4 h-4"})})]},N))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-lg flex items-center gap-2",children:[e.jsx(Ps,{className:"w-5 h-5 text-blue-600"}),"Dealer Comments"]})}),e.jsx("div",{className:"border rounded-lg p-4 bg-gray-50",children:e.jsx("p",{className:"text-sm text-gray-700 whitespace-pre-wrap",children:(n==null?void 0:n.dealerComments)||"No comments provided"})})]}),e.jsxs("div",{className:"space-y-3 border-t pt-4",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Your Decision & Comments"}),e.jsx(ns,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:c,onChange:v=>d(v.target.value),className:"min-h-[120px]"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[c.length," characters"]})]}),!c.trim()&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 flex items-start gap-2",children:[e.jsx(yt,{className:"w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-sm text-amber-800",children:"Please provide comments before making a decision. Comments are required and will be visible to all participants."})]})]}),e.jsxs(Nt,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end px-6 pb-6 pt-4 flex-shrink-0 border-t bg-gray-50",children:[e.jsx(R,{variant:"outline",onClick:C,disabled:m,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{onClick:w,disabled:!c.trim()||m,variant:"destructive",className:"bg-red-600 hover:bg-red-700",children:m&&h==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(yt,{className:"w-4 h-4 mr-2"}),"Reject (Cancel Request)"]})}),e.jsx(R,{onClick:j,disabled:!c.trim()||m,className:"bg-green-600 hover:bg-green-700 text-white",children:m&&h==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),"Approve (Continue to Dept Lead)"]})})]})]})]})}):null}async function t2(t){var s;try{const a=await he.post("/dealer-claims",t);return((s=a.data)==null?void 0:s.data)||a.data}catch(a){throw console.error("[DealerClaimAPI] Error creating claim request:",a),a}}async function s2(t){var s;try{const a=await he.get(`/dealer-claims/${t}`);return((s=a.data)==null?void 0:s.data)||a.data}catch(a){throw console.error("[DealerClaimAPI] Error fetching claim details:",a),a}}async function a2(t,s){var a;try{const r=new FormData;s.proposalDocument&&r.append("proposalDocument",s.proposalDocument),s.costBreakup&&r.append("costBreakup",JSON.stringify(s.costBreakup)),s.totalEstimatedBudget!==void 0&&r.append("totalEstimatedBudget",s.totalEstimatedBudget.toString()),s.timelineMode&&r.append("timelineMode",s.timelineMode),s.expectedCompletionDate&&r.append("expectedCompletionDate",s.expectedCompletionDate),s.expectedCompletionDays!==void 0&&r.append("expectedCompletionDays",s.expectedCompletionDays.toString()),s.dealerComments&&r.append("dealerComments",s.dealerComments);const n=await he.post(`/dealer-claims/${t}/proposal`,r,{headers:{"Content-Type":"multipart/form-data"}});return((a=n.data)==null?void 0:a.data)||n.data}catch(r){throw console.error("[DealerClaimAPI] Error submitting proposal:",r),r}}async function r2(t,s){var a;try{const r=new FormData;r.append("activityCompletionDate",s.activityCompletionDate),s.numberOfParticipants!==void 0&&r.append("numberOfParticipants",s.numberOfParticipants.toString()),s.closedExpenses&&r.append("closedExpenses",JSON.stringify(s.closedExpenses)),s.totalClosedExpenses!==void 0&&r.append("totalClosedExpenses",s.totalClosedExpenses.toString()),s.completionDocuments&&s.completionDocuments.forEach(i=>{r.append("completionDocuments",i)}),s.activityPhotos&&s.activityPhotos.forEach(i=>{r.append("activityPhotos",i)});const n=await he.post(`/dealer-claims/${t}/completion`,r,{headers:{"Content-Type":"multipart/form-data"}});return((a=n.data)==null?void 0:a.data)||n.data}catch(r){throw console.error("[DealerClaimAPI] Error submitting completion:",r),r}}async function n2(t,s){var a;try{const r=await he.get(`/dealer-claims/${t}/io/validate`,{params:{ioNumber:s}});return((a=r.data)==null?void 0:a.data)||r.data}catch(r){throw console.error("[DealerClaimAPI] Error validating IO:",r),r}}async function bp(t,s){var a;try{const r={ioNumber:s.ioNumber,ioRemark:s.ioRemark||"",availableBalance:s.ioAvailableBalance??0,blockedAmount:s.ioBlockedAmount??0,remainingBalance:s.ioRemainingBalance??0},n=await he.put(`/dealer-claims/${t}/io`,r);return((a=n.data)==null?void 0:a.data)||n.data}catch(r){throw console.error("Error updating IO details:",r),r}}async function i2(t,s){var a;try{const r=await he.put(`/dealer-claims/${t}/e-invoice`,s);return((a=r.data)==null?void 0:a.data)||r.data}catch(r){throw console.error("[DealerClaimAPI] Error updating e-invoice:",r),r}}const mn=t=>{if(!t)return"";try{return Qt(t)}catch{try{return new Date(t).toLocaleString("en-IN",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}catch{return t}}},o2=t=>{switch(t){case"approved":return e.jsx(Ce,{className:"w-5 h-5 text-green-600"});case"pending":return e.jsx(He,{className:"w-5 h-5 text-blue-600"});case"rejected":return e.jsx(Ce,{className:"w-5 h-5 text-red-600"});default:return e.jsx(He,{className:"w-5 h-5 text-gray-400"})}},l2=t=>{switch(t){case"approved":return"bg-green-100 text-green-800 border-green-200";case"pending":return"bg-purple-100 text-purple-800 border-purple-200";case"rejected":return"bg-red-100 text-red-800 border-red-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},c2=(t,s)=>s&&(t==="pending"||t==="in_progress")?"border-purple-500 bg-purple-50 shadow-md":t==="approved"?"border-green-500 bg-green-50":t==="rejected"?"border-red-500 bg-red-50":"border-gray-200 bg-white",d2=t=>{switch(t){case"approved":return"bg-green-100";case"pending":return"bg-purple-100";case"rejected":return"bg-red-100";default:return"bg-gray-100"}};function m2({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n}){var te,xe,dt,ue,Te,Qe,ht,et,qt,Es,Xs,H,me,z,fe,ye,Re,be,Me,ke,Le,Xt,wt,Ke,$e,at,zt,vt,Cs,Is,Js,Qs,ot,va,ja,Na,Ht,is,Ms,or,lr,cr,dr,mr,ur,hr,pr,xr,gr,fr,Ct,Ss,Ba,El,Il,Ml,Fl,_l,Ll,Ol,$l,Bl,Ul,Vl,zl,Hl,Wl,Gl,Kl,Yl,Zl,Xl,Jl,Ql,ql,ec,tc,sc,ac,rc;const[i,o]=p.useState(!1),[l,c]=p.useState(!1),[d,m]=p.useState(!1),[u,h]=p.useState(!1),[x,g]=p.useState(!1),[f,j]=p.useState(!1),[w,b]=p.useState(!1),[C,v]=p.useState(null),[N,k]=p.useState([]),[E,P]=p.useState(0);p.useEffect(()=>{(async()=>{if(t!=null&&t.approvalFlow&&t.approvalFlow.length>0){k(t.approvalFlow);return}if(t!=null&&t.id||t!=null&&t.requestId){const Xe=t.id||t.requestId;try{const De=await xs(Xe),oe=(De==null?void 0:De.approvalLevels)||(De==null?void 0:De.approvals)||[];if(oe&&oe.length>0){const pe=oe.map(ve=>{var Pe;return{step:ve.levelNumber||ve.level_number||0,approver:ve.approverName||ve.approver_name||"",approverEmail:(ve.approverEmail||ve.approver_email||"").toLowerCase(),status:((Pe=ve.status)==null?void 0:Pe.toLowerCase())||"waiting",tatHours:ve.tatHours||ve.tat_hours||24,elapsedHours:ve.elapsedHours||ve.elapsed_hours,approvedAt:ve.actionDate||ve.action_date,comment:ve.comments||ve.comment,levelId:ve.levelId||ve.level_id}});k(pe)}}catch(De){console.warn("Failed to load approval flows from API:",De)}}})()},[t,E]),p.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const q=t.id||t.requestId;(async()=>{try{const De=await xs(q),oe=(De==null?void 0:De.approvalLevels)||(De==null?void 0:De.approvals)||[];if(oe&&oe.length>0){const pe=oe.map(ve=>{var Pe;return{step:ve.levelNumber||ve.level_number||0,approver:ve.approverName||ve.approver_name||"",approverEmail:(ve.approverEmail||ve.approver_email||"").toLowerCase(),status:((Pe=ve.status)==null?void 0:Pe.toLowerCase())||"waiting",tatHours:ve.tatHours||ve.tat_hours||24,elapsedHours:ve.elapsedHours||ve.elapsed_hours,approvedAt:ve.actionDate||ve.action_date,comment:ve.comments||ve.comment,levelId:ve.levelId||ve.level_id}});k(pe)}}catch(De){console.warn("Failed to load approval flows from API:",De)}})()}},[t==null?void 0:t.currentStep]);const M=()=>{P(q=>q+1),n==null||n()},y=N.map((q,Xe)=>{var rt,yr,Ua,nc;const De=["Dealer - Proposal Submission","Requestor Evaluation & Confirmation","Dept Lead Approval","Activity Creation","Dealer - Completion Documents","Requestor - Claim Approval","E-Invoice Generation","Credit Note from SAP"],oe=["Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests","Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)","Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)","Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.","Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description","Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.","E-invoice will be generated through DMS.","Got credit note from SAP. Review and send to dealer to complete the claim management process."],pe=(rt=t==null?void 0:t.approvals)==null?void 0:rt.find(lt=>lt.levelId===q.levelId);let ve;if(q.step===3){const lt=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);if(lt!=null&<.ioNumber||lt!=null&<.io_number){const sn=lt.ioRemark||lt.io_remark||lt.IORemark||lt.IO_Remark||(lt==null?void 0:lt.ioRemark)||(lt==null?void 0:lt.io_remark)||"";ve={ioNumber:lt.ioNumber||lt.io_number||"",ioRemark:sn&&typeof sn=="string"&&sn.trim()?sn.trim():"N/A",blockedAmount:lt.ioBlockedAmount||lt.io_blocked_amount||0,availableBalance:lt.ioAvailableBalance||lt.io_available_balance||0,remainingBalance:lt.ioRemainingBalance||lt.io_remaining_balance||0,organizedBy:((yr=lt.organizer)==null?void 0:yr.displayName)||((Ua=lt.organizer)==null?void 0:Ua.name)||lt.organizedBy||q.approver||"N/A",organizedAt:lt.organizedAt||lt.organized_at||q.approvedAt||(t==null?void 0:t.updatedAt)||""}}}let Pe;q.step===6&&(pe!=null&&pe.dmsDetails?Pe={dmsNumber:pe.dmsDetails.dmsNumber||"",dmsRemarks:pe.dmsDetails.dmsRemarks||"",pushedBy:pe.dmsDetails.pushedBy||q.approver,pushedAt:pe.dmsDetails.pushedAt||q.approvedAt||""}:t!=null&&t.dmsNumber&&(Pe={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||((nc=t.dmsDetails)==null?void 0:nc.dmsRemarks)||"",pushedBy:q.approver,pushedAt:q.approvedAt||t.updatedAt||""}));let pt=(q.status||"waiting").toLowerCase();return(pt==="in-review"||pt==="in_review"||pt==="in review")&&(pt="in_progress"),{step:q.step||Xe+1,title:De[Xe]||`Step ${q.step||Xe+1}`,approver:q.approver||"Unknown",description:oe[Xe]||q.description||"",tatHours:q.tatHours||24,status:pt,comment:q.comment||(pe==null?void 0:pe.comment),approvedAt:q.approvedAt||(pe==null?void 0:pe.timestamp),elapsedHours:q.elapsedHours,ioDetails:ve,dmsDetails:Pe,einvoiceUrl:q.step===7?pe==null?void 0:pe.einvoiceUrl:void 0,emailTemplateUrl:q.step===4?pe==null?void 0:pe.emailTemplateUrl:void 0}}),A=(t==null?void 0:t.totalSteps)||8,L=y.find(q=>{var De;const Xe=((De=q.status)==null?void 0:De.toLowerCase())||"";return Xe==="pending"||Xe==="in_progress"||Xe==="in-review"||Xe==="in_review"}),K=L?L.step:(t==null?void 0:t.currentStep)||1,O=((te=s==null?void 0:s.email)==null?void 0:te.toLowerCase())||"",$=((xe=t==null?void 0:t.dealerEmail)==null?void 0:xe.toLowerCase())||((ue=(dt=t==null?void 0:t.dealer)==null?void 0:dt.email)==null?void 0:ue.toLowerCase())||((Qe=(Te=t==null?void 0:t.claimDetails)==null?void 0:Te.dealerEmail)==null?void 0:Qe.toLowerCase())||((et=(ht=t==null?void 0:t.claimDetails)==null?void 0:ht.dealer_email)==null?void 0:et.toLowerCase())||"",T=$&&O===$,S=N.find(q=>(q.step||q.levelNumber||q.level_number)===K),D=((S==null?void 0:S.approverEmail)||"").toLowerCase(),I=D&&O===D,_=N.find(q=>(q.step||q.levelNumber||q.level_number)===2),F=((_==null?void 0:_.approverEmail)||"").toLowerCase(),G=F&&O===F,B=N.find(q=>(q.step||q.levelNumber||q.level_number)===1),re=((B==null?void 0:B.approverEmail)||"").toLowerCase(),ae=re&&O===re,V=N.find(q=>(q.step||q.levelNumber||q.level_number)===3),Y=((V==null?void 0:V.approverEmail)||"").toLowerCase(),Z=Y&&O===Y,U=async q=>{var Xe,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId;q.proposalDocument&&await Sr(q.proposalDocument,oe,"APPROVAL");for(const ve of q.otherDocuments)await Sr(ve,oe,"SUPPORTING");const pe=q.costBreakup.reduce((ve,Pe)=>ve+Pe.amount,0);await a2(oe,{proposalDocument:q.proposalDocument||void 0,costBreakup:q.costBreakup.map(ve=>({description:ve.description,amount:ve.amount})),totalEstimatedBudget:pe,expectedCompletionDate:q.expectedCompletionDate,dealerComments:q.dealerComments}),ne.success("Proposal submitted successfully"),M()}catch(oe){console.error("Failed to submit proposal:",oe);const pe=((De=(Xe=oe==null?void 0:oe.response)==null?void 0:Xe.data)==null?void 0:De.message)||(oe==null?void 0:oe.message)||"Failed to submit proposal. Please try again.";throw ne.error(pe),oe}},ee=async q=>{var Xe,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId,pe=await xs(oe),Pe=((pe==null?void 0:pe.approvalLevels)||(pe==null?void 0:pe.approvals)||[]).find(rt=>(rt.levelNumber||rt.level_number)===2);if(!(Pe!=null&&Pe.levelId)&&!(Pe!=null&&Pe.level_id))throw new Error("Step 2 approval level not found");const pt=Pe.levelId||Pe.level_id;await Wi(oe,pt,q),ne.success("Proposal approved successfully"),M()}catch(oe){console.error("Failed to approve proposal:",oe);const pe=((De=(Xe=oe==null?void 0:oe.response)==null?void 0:Xe.data)==null?void 0:De.message)||(oe==null?void 0:oe.message)||"Failed to approve proposal. Please try again.";throw ne.error(pe),oe}},ie=async q=>{var Xe,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId,pe=await xs(oe),Pe=((pe==null?void 0:pe.approvalLevels)||(pe==null?void 0:pe.approvals)||[]).find(rt=>(rt.levelNumber||rt.level_number)===2);if(!(Pe!=null&&Pe.levelId)&&!(Pe!=null&&Pe.level_id))throw new Error("Step 2 approval level not found");const pt=Pe.levelId||Pe.level_id;await Gi(oe,pt,"Proposal rejected by requestor",q),ne.success("Proposal rejected. Request has been cancelled."),M()}catch(oe){console.error("Failed to reject proposal:",oe);const pe=((De=(Xe=oe==null?void 0:oe.response)==null?void 0:Xe.data)==null?void 0:De.message)||(oe==null?void 0:oe.message)||"Failed to reject proposal. Please try again.";throw ne.error(pe),oe}},de=async q=>{var Xe,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId,pe=await xs(oe),Pe=((pe==null?void 0:pe.approvalLevels)||(pe==null?void 0:pe.approvals)||[]).find(rt=>(rt.levelNumber||rt.level_number)===3);if(!(Pe!=null&&Pe.levelId)&&!(Pe!=null&&Pe.level_id))throw new Error("Step 3 approval level not found");const pt=Pe.levelId||Pe.level_id;await bp(oe,{ioNumber:q.ioNumber,ioRemark:q.ioRemark,ioAvailableBalance:0,ioBlockedAmount:0,ioRemainingBalance:0}),await Wi(oe,pt,q.comments),ne.success("Request approved and IO organized successfully"),M()}catch(oe){console.error("Failed to approve and organize IO:",oe);const pe=((De=(Xe=oe==null?void 0:oe.response)==null?void 0:Xe.data)==null?void 0:De.message)||(oe==null?void 0:oe.message)||"Failed to approve request. Please try again.";throw ne.error(pe),oe}},Ae=async q=>{var Xe,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId,pe=q.closedExpenses.map(ve=>({description:ve.description,amount:ve.amount}));if(await r2(oe,{activityCompletionDate:q.activityCompletionDate,numberOfParticipants:q.numberOfParticipants,closedExpenses:pe,totalClosedExpenses:q.totalClosedExpenses,completionDocuments:q.completionDocuments,activityPhotos:q.activityPhotos}),q.invoicesReceipts&&q.invoicesReceipts.length>0)for(const ve of q.invoicesReceipts)await Sr(ve,oe,"SUPPORTING");q.attendanceSheet&&await Sr(q.attendanceSheet,oe,"SUPPORTING"),ne.success("Completion documents submitted successfully"),M()}catch(oe){console.error("Failed to submit completion documents:",oe);const pe=((De=(Xe=oe==null?void 0:oe.response)==null?void 0:Xe.data)==null?void 0:De.message)||(oe==null?void 0:oe.message)||"Failed to submit completion documents. Please try again.";throw ne.error(pe),oe}},We=async q=>{var Xe,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId,pe=new Date().toISOString().slice(0,10);await i2(oe,{eInvoiceDate:pe}),ne.success("Pushed to DMS successfully. E-invoice will be generated automatically."),M()}catch(oe){console.error("[DealerClaimWorkflowTab] Error pushing to DMS:",oe);const pe=((De=(Xe=oe==null?void 0:oe.response)==null?void 0:Xe.data)==null?void 0:De.message)||(oe==null?void 0:oe.message)||"Failed to push to DMS. Please try again.";throw ne.error(pe),oe}},Se=async q=>{var Xe,De;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const oe=t.id||t.requestId,pe=await xs(oe),Pe=((pe==null?void 0:pe.approvalLevels)||(pe==null?void 0:pe.approvals)||[]).find(rt=>(rt.levelNumber||rt.level_number)===3);if(!(Pe!=null&&Pe.levelId)&&!(Pe!=null&&Pe.level_id))throw new Error("Step 3 approval level not found");const pt=Pe.levelId||Pe.level_id;await Gi(oe,pt,"Dept Lead rejected - More clarification required",q),ne.success("Request rejected. Request has been cancelled."),M()}catch(oe){console.error("Failed to reject request:",oe);const pe=((De=(Xe=oe==null?void 0:oe.response)==null?void 0:Xe.data)==null?void 0:De.message)||(oe==null?void 0:oe.message)||"Failed to reject request. Please try again.";throw ne.error(pe),oe}},[Ye,Ge]=p.useState(null);p.useEffect(()=>{if(!t){Ge(null);return}(async()=>{try{const Xe=t.id||t.requestId;if(!Xe){Ge(null);return}const De=await xs(Xe),oe=(De==null?void 0:De.documents)||[],pe=t.proposalDetails||(De==null?void 0:De.proposalDetails)||{},ve=oe.find(rt=>rt.category==="APPROVAL"||rt.type==="proposal"||rt.documentCategory==="APPROVAL"),Pe=oe.filter(rt=>rt.category==="SUPPORTING"||rt.type==="supporting"||rt.documentCategory==="SUPPORTING");let pt=pe.costBreakup||[];if(typeof pt=="string")try{pt=JSON.parse(pt)}catch(rt){console.warn("Failed to parse costBreakup JSON:",rt),pt=[]}Array.isArray(pt)||(pt=[]),Ge({proposalDocument:ve?{name:ve.fileName||ve.file_name||ve.name,id:ve.documentId||ve.document_id||ve.id}:void 0,costBreakup:pt,expectedCompletionDate:pe.expectedCompletionDate||"",otherDocuments:Pe.map(rt=>({name:rt.fileName||rt.file_name||rt.name,id:rt.documentId||rt.document_id||rt.id})),dealerComments:pe.dealerComments||"",submittedAt:pe.submittedAt})}catch(Xe){console.warn("Failed to load proposal data:",Xe);const De=t.proposalDetails||{};let oe=De.costBreakup||[];if(typeof oe=="string")try{oe=JSON.parse(oe)}catch(pe){console.warn("Failed to parse costBreakup JSON:",pe),oe=[]}Array.isArray(oe)||(oe=[]),Ge({proposalDocument:void 0,costBreakup:oe,expectedCompletionDate:De.expectedCompletionDate||"",otherDocuments:[],dealerComments:De.dealerComments||"",submittedAt:De.submittedAt})}})()},[t]);const Oe=((qt=t==null?void 0:t.claimDetails)==null?void 0:qt.dealerName)||((Es=t==null?void 0:t.dealerInfo)==null?void 0:Es.name)||"Dealer",ct=((Xs=t==null?void 0:t.claimDetails)==null?void 0:Xs.activityName)||((H=t==null?void 0:t.activityInfo)==null?void 0:H.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(X,{children:[e.jsx(le,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(Zs,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx(je,{className:"mt-2",children:"8-Step approval process for dealer claim management"})]}),e.jsxs(se,{variant:"outline",className:"font-medium",children:["Step ",K," of ",A]})]})}),e.jsx(J,{children:e.jsx("div",{className:"space-y-4",children:y.map((q,Xe)=>{const De=(q.status==="pending"||q.status==="in_progress")&&q.step===K,oe=q.status==="approved";return e.jsx("div",{className:`relative p-5 rounded-lg border-2 transition-all ${c2(q.status,De)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${d2(q.status)}`,children:o2(q.status)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("h4",{className:"font-semibold text-gray-900",children:["Step ",q.step,": ",q.title]}),e.jsx(se,{className:l2(q.status),children:q.status.toLowerCase()}),q.step===4&&q.status==="approved"&&e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",title:"View email template",onClick:()=>{v({stepNumber:q.step,stepName:q.title}),b(!0)},children:e.jsx(aa,{className:"w-3.5 h-3.5 text-blue-600"})}),q.step===7&&q.einvoiceUrl&&oe&&e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",title:"Download E-Invoice",onClick:()=>window.open(q.einvoiceUrl,"_blank"),children:e.jsx(ss,{className:"w-3.5 h-3.5 text-green-600"})})]}),e.jsx("p",{className:"text-sm text-gray-600",children:q.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:q.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",q.tatHours,"h"]}),q.elapsedHours&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",q.elapsedHours,"h"]})]})]}),q.comment&&e.jsx("div",{className:"mt-3 p-3 bg-white rounded-lg border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-700",children:q.comment})}),q.step===3&&q.status==="approved"&&q.ioDetails&&q.ioDetails.ioNumber&&e.jsxs("div",{className:"mt-3 p-3 bg-blue-50 rounded-lg border border-blue-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ms,{className:"w-4 h-4 text-blue-600"}),e.jsx("p",{className:"text-xs font-semibold text-blue-900 uppercase tracking-wide",children:"IO Organisation Details"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"IO Number:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:q.ioDetails.ioNumber})]}),q.ioDetails.blockedAmount!==void 0&&q.ioDetails.blockedAmount>0&&e.jsxs("div",{className:"flex items-center justify-between pt-1.5 border-t border-blue-100",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"Blocked Amount:"}),e.jsxs("span",{className:"text-sm font-bold text-green-700",children:["₹",q.ioDetails.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("div",{className:"pt-1.5 border-t border-blue-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"IO Remark:"}),e.jsx("p",{className:"text-sm text-gray-900",children:q.ioDetails.ioRemark||"N/A"})]}),e.jsxs("div",{className:"pt-1.5 border-t border-blue-100 text-xs text-gray-500",children:["Organised by ",q.ioDetails.organizedBy||q.approver||"N/A"," on"," ",q.ioDetails.organizedAt?mn(q.ioDetails.organizedAt):q.approvedAt?mn(q.approvedAt):"N/A"]})]})]}),q.step===6&&q.dmsDetails&&q.dmsDetails.dmsNumber&&e.jsxs("div",{className:"mt-3 p-3 bg-purple-50 rounded-lg border border-purple-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-purple-600"}),e.jsx("p",{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"DMS Processing Details"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"DMS Number:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:q.dmsDetails.dmsNumber})]}),q.dmsDetails.dmsRemarks&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"DMS Remarks:"}),e.jsx("p",{className:"text-sm text-gray-900",children:q.dmsDetails.dmsRemarks})]}),q.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Pushed by ",q.dmsDetails.pushedBy," on"," ",mn(q.dmsDetails.pushedAt)]})]})]}),De&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[q.step===1&&(T||ae)&&e.jsxs(R,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{o(!0)},children:[e.jsx(ys,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),q.step===2&&(a||G)&&e.jsxs(R,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{c(!0)},children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),"Confirm Request"]}),q.step===3&&(()=>{const pe=N.find(pt=>(pt.step||pt.levelNumber||pt.level_number)===3),ve=((pe==null?void 0:pe.approverEmail)||"").toLowerCase();return ve&&O===ve||Z||I})()&&e.jsxs(R,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{console.log("[DealerClaimWorkflowTab] Opening IO approval modal for Step 3"),m(!0)},children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),"Approve and Organise IO"]}),q.step===5&&T&&e.jsxs(R,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{h(!0)},children:[e.jsx(ys,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),q.step===6&&(a||(()=>{const pe=N.find(Pe=>(Pe.step||Pe.levelNumber||Pe.level_number)===6),ve=((pe==null?void 0:pe.approverEmail)||"").toLowerCase();return ve&&O===ve})())&&e.jsxs(R,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:()=>{g(!0)},children:[e.jsx(Vt,{className:"w-4 h-4 mr-2"}),"Push to DMS"]}),q.step===8&&(()=>{var yr;const pe=N.find(Ua=>(Ua.step||Ua.levelNumber||Ua.level_number)===8),ve=((pe==null?void 0:pe.approverEmail)||"").toLowerCase(),Pe=ve&&O===ve,pt=((yr=s==null?void 0:s.role)==null?void 0:yr.toUpperCase())||"";return Pe||(pt==="FINANCE"||pt==="ADMIN")})()&&e.jsxs(R,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{j(!0)},children:[e.jsx(ms,{className:"w-4 h-4 mr-2"}),"View & Send Credit Note"]})]}),q.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",mn(q.approvedAt)]})]})]})},Xe)})})})]}),e.jsx(X1,{isOpen:i,onClose:()=>o(!1),onSubmit:U,dealerName:Oe,activityName:ct,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId)}),e.jsx(e2,{isOpen:l,onClose:()=>{c(!1)},onApprove:ee,onReject:ie,proposalData:Ye,dealerName:Oe,activityName:ct,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId)}),e.jsx(J1,{isOpen:d,onClose:()=>m(!1),onApprove:de,onReject:Se,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),preFilledIONumber:((me=t==null?void 0:t.internalOrder)==null?void 0:me.ioNumber)||((z=t==null?void 0:t.internalOrder)==null?void 0:z.io_number)||((fe=t==null?void 0:t.internal_order)==null?void 0:fe.ioNumber)||((ye=t==null?void 0:t.internal_order)==null?void 0:ye.io_number)||void 0,preFilledBlockedAmount:((Re=t==null?void 0:t.internalOrder)==null?void 0:Re.ioBlockedAmount)||((be=t==null?void 0:t.internalOrder)==null?void 0:be.io_blocked_amount)||((Me=t==null?void 0:t.internal_order)==null?void 0:Me.ioBlockedAmount)||((ke=t==null?void 0:t.internal_order)==null?void 0:ke.io_blocked_amount)||void 0}),e.jsx(Z1,{isOpen:u,onClose:()=>h(!1),onSubmit:Ae,dealerName:Oe,activityName:ct,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId)}),e.jsx(Q1,{isOpen:x,onClose:()=>g(!1),onPush:We,completionDetails:{activityCompletionDate:((Le=t==null?void 0:t.completionDetails)==null?void 0:Le.activityCompletionDate)||((Xt=t==null?void 0:t.completionDetails)==null?void 0:Xt.activity_completion_date),numberOfParticipants:((wt=t==null?void 0:t.completionDetails)==null?void 0:wt.numberOfParticipants)||((Ke=t==null?void 0:t.completionDetails)==null?void 0:Ke.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||(($e=t==null?void 0:t.completionDetails)==null?void 0:$e.closedExpenses)||((at=t==null?void 0:t.completionDetails)==null?void 0:at.closed_expenses),totalClosedExpenses:((zt=t==null?void 0:t.budgetTracking)==null?void 0:zt.closedExpenses)||((vt=t==null?void 0:t.budgetTracking)==null?void 0:vt.closed_expenses)||((Cs=t==null?void 0:t.completionDetails)==null?void 0:Cs.totalClosedExpenses)||((Is=t==null?void 0:t.completionDetails)==null?void 0:Is.total_closed_expenses),completionDescription:((Js=t==null?void 0:t.completionDetails)==null?void 0:Js.completionDescription)||((Qs=t==null?void 0:t.completionDetails)==null?void 0:Qs.completion_description)},ioDetails:{ioNumber:((ot=t==null?void 0:t.internalOrder)==null?void 0:ot.ioNumber)||((va=t==null?void 0:t.internalOrder)==null?void 0:va.io_number)||((ja=t==null?void 0:t.internal_order)==null?void 0:ja.ioNumber)||((Na=t==null?void 0:t.internal_order)==null?void 0:Na.io_number),blockedAmount:((Ht=t==null?void 0:t.internalOrder)==null?void 0:Ht.ioBlockedAmount)||((is=t==null?void 0:t.internalOrder)==null?void 0:is.io_blocked_amount)||((Ms=t==null?void 0:t.internal_order)==null?void 0:Ms.ioBlockedAmount)||((or=t==null?void 0:t.internal_order)==null?void 0:or.io_blocked_amount),availableBalance:((lr=t==null?void 0:t.internalOrder)==null?void 0:lr.ioAvailableBalance)||((cr=t==null?void 0:t.internalOrder)==null?void 0:cr.io_available_balance)||((dr=t==null?void 0:t.internal_order)==null?void 0:dr.ioAvailableBalance)||((mr=t==null?void 0:t.internal_order)==null?void 0:mr.io_available_balance),remainingBalance:((ur=t==null?void 0:t.internalOrder)==null?void 0:ur.ioRemainingBalance)||((hr=t==null?void 0:t.internalOrder)==null?void 0:hr.io_remaining_balance)||((pr=t==null?void 0:t.internal_order)==null?void 0:pr.ioRemainingBalance)||((xr=t==null?void 0:t.internal_order)==null?void 0:xr.io_remaining_balance)},requestTitle:t==null?void 0:t.title,requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.request_number)||(t==null?void 0:t.id)}),e.jsx(Y1,{isOpen:f,onClose:()=>j(!1),onDownload:async()=>{ne.info("Download functionality will be implemented")},onSendToDealer:async()=>{ne.info("Send to dealer functionality will be implemented")},creditNoteData:{creditNoteNumber:((gr=t==null?void 0:t.creditNote)==null?void 0:gr.creditNoteNumber)||((fr=t==null?void 0:t.creditNote)==null?void 0:fr.credit_note_number)||((Ss=(Ct=t==null?void 0:t.claimDetails)==null?void 0:Ct.creditNote)==null?void 0:Ss.creditNoteNumber)||((Ba=t==null?void 0:t.claimDetails)==null?void 0:Ba.creditNoteNumber)||((El=t==null?void 0:t.claimDetails)==null?void 0:El.credit_note_number),creditNoteDate:((Il=t==null?void 0:t.creditNote)==null?void 0:Il.creditNoteDate)||((Ml=t==null?void 0:t.creditNote)==null?void 0:Ml.credit_note_date)||((_l=(Fl=t==null?void 0:t.claimDetails)==null?void 0:Fl.creditNote)==null?void 0:_l.creditNoteDate)||((Ll=t==null?void 0:t.claimDetails)==null?void 0:Ll.creditNoteDate)||((Ol=t==null?void 0:t.claimDetails)==null?void 0:Ol.credit_note_date),creditNoteAmount:($l=t==null?void 0:t.creditNote)!=null&&$l.creditNoteAmount?Number((Bl=t==null?void 0:t.creditNote)==null?void 0:Bl.creditNoteAmount):(Ul=t==null?void 0:t.creditNote)!=null&&Ul.credit_note_amount?Number((Vl=t==null?void 0:t.creditNote)==null?void 0:Vl.credit_note_amount):(Hl=(zl=t==null?void 0:t.claimDetails)==null?void 0:zl.creditNote)!=null&&Hl.creditNoteAmount?Number((Gl=(Wl=t==null?void 0:t.claimDetails)==null?void 0:Wl.creditNote)==null?void 0:Gl.creditNoteAmount):(Kl=t==null?void 0:t.claimDetails)!=null&&Kl.creditNoteAmount?Number((Yl=t==null?void 0:t.claimDetails)==null?void 0:Yl.creditNoteAmount):(Zl=t==null?void 0:t.claimDetails)!=null&&Zl.credit_note_amount?Number((Xl=t==null?void 0:t.claimDetails)==null?void 0:Xl.credit_note_amount):void 0,status:"APPROVED"},dealerInfo:{dealerName:((Jl=t==null?void 0:t.claimDetails)==null?void 0:Jl.dealerName)||((Ql=t==null?void 0:t.claimDetails)==null?void 0:Ql.dealer_name),dealerCode:((ql=t==null?void 0:t.claimDetails)==null?void 0:ql.dealerCode)||((ec=t==null?void 0:t.claimDetails)==null?void 0:ec.dealer_code),dealerEmail:((tc=t==null?void 0:t.claimDetails)==null?void 0:tc.dealerEmail)||((sc=t==null?void 0:t.claimDetails)==null?void 0:sc.dealer_email)},activityName:((ac=t==null?void 0:t.claimDetails)==null?void 0:ac.activityName)||((rc=t==null?void 0:t.claimDetails)==null?void 0:rc.activity_name),requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.id),requestId:(t==null?void 0:t.requestId)||(t==null?void 0:t.id),dueDate:t==null?void 0:t.dueDate}),e.jsx(q1,{isOpen:w,onClose:()=>{b(!1),v(null)},stepNumber:(C==null?void 0:C.stepNumber)||4,stepName:(C==null?void 0:C.stepName)||"Activity Creation",requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.id)||(t==null?void 0:t.request_number),recipientEmail:"system@royalenfield.com"})]})}function u2({request:t,apiRequest:s,onRefresh:a}){const{user:r}=Gt(),n=(s==null?void 0:s.requestId)||(t==null?void 0:t.requestId),i=(s==null?void 0:s.internalOrder)||(s==null?void 0:s.internal_order)||null,o=(i==null?void 0:i.ioNumber)||(i==null?void 0:i.io_number)||(t==null?void 0:t.ioNumber)||"",l=(i==null?void 0:i.ioBlockedAmount)||(i==null?void 0:i.io_blocked_amount)||0,c=(i==null?void 0:i.ioAvailableBalance)||(i==null?void 0:i.io_available_balance)||0,d=(i==null?void 0:i.ioRemainingBalance)||(i==null?void 0:i.io_remaining_balance)||0,m=(i==null?void 0:i.sapDocumentNumber)||(i==null?void 0:i.sap_document_number)||"",u=(i==null?void 0:i.organizer)||null,[h,x]=p.useState(o),[g,f]=p.useState(!1),[j,w]=p.useState(null),[b,C]=p.useState(""),[v,N]=p.useState(null),[k,E]=p.useState(!1);p.useEffect(()=>{if(i&&o&&l>0){const y=Number(c)+Number(l)||Number(c),A=(u==null?void 0:u.displayName)||(u==null?void 0:u.display_name)||(u==null?void 0:u.name)||(u!=null&&u.firstName&&(u!=null&&u.lastName)?`${u.firstName} ${u.lastName}`.trim():null)||(u==null?void 0:u.email)||"Unknown User";N({ioNumber:o,blockedAmount:Number(l)||0,availableBalance:y,remainingBalance:Number(d)||Number(c),blockedDate:i.organizedAt||i.organized_at||new Date().toISOString(),blockedBy:A,sapDocumentNumber:m,status:i.status==="BLOCKED"?"blocked":i.status==="RELEASED"?"released":"blocked"}),x(o),y>0&&w(y)}},[i,o,l,c,d,m,u]);const P=async()=>{var y,A;if(!h.trim()){ne.error("Please enter an IO number");return}if(!n){ne.error("Request ID not found");return}f(!0);try{const L=await n2(n,h.trim());L.isValid&&L.availableBalance>0?(w(L.availableBalance),C(String(L.availableBalance)),ne.success(`IO fetched from SAP. Available balance: ₹${L.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`)):(ne.error("Invalid IO number or no available balance found"),w(null),C(""))}catch(L){console.error("Failed to fetch IO budget:",L);const K=((A=(y=L==null?void 0:L.response)==null?void 0:y.data)==null?void 0:A.message)||(L==null?void 0:L.message)||"Failed to validate IO number or fetch budget from SAP";ne.error(K),w(null)}finally{f(!1)}},M=async()=>{var A,L;if(!h.trim()||j===null){ne.error("Please fetch IO amount first");return}if(!n){ne.error("Request ID not found");return}const y=parseFloat(b);if(!b||isNaN(y)||y<=0){ne.error("Please enter a valid amount to block");return}if(y>j){ne.error("Amount to block exceeds available IO budget");return}E(!0);try{await bp(n,{ioNumber:h.trim(),ioAvailableBalance:j,ioBlockedAmount:y,ioRemainingBalance:j-y});const K=await s2(n),O=(K==null?void 0:K.internalOrder)||(K==null?void 0:K.internal_order);if(O){const $=r,T=($==null?void 0:$.displayName)||($==null?void 0:$.display_name)||($==null?void 0:$.name)||($!=null&&$.firstName&&($!=null&&$.lastName)?`${$.firstName} ${$.lastName}`.trim():null)||($==null?void 0:$.email)||"Current User",S={ioNumber:O.ioNumber||O.io_number||h,blockedAmount:Number(O.ioBlockedAmount||O.io_blocked_amount||y),availableBalance:j,remainingBalance:Number(O.ioRemainingBalance||O.io_remaining_balance||j-y),blockedDate:O.organizedAt||O.organized_at||new Date().toISOString(),blockedBy:T,sapDocumentNumber:O.sapDocumentNumber||O.sap_document_number||"",status:"blocked"};N(S),C(""),ne.success("IO budget blocked successfully in SAP"),a==null||a()}else ne.error("IO blocked but failed to fetch updated details"),a==null||a()}catch(K){console.error("Failed to block IO budget:",K);const O=((L=(A=K==null?void 0:K.response)==null?void 0:A.data)==null?void 0:L.message)||(K==null?void 0:K.message)||"Failed to block IO budget in SAP";ne.error(O)}finally{E(!1)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(X,{children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx(je,{children:"Enter IO number to fetch available budget from SAP"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(Q,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(we,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:h,onChange:y=>x(y.target.value),disabled:g||!!v,className:"flex-1"}),e.jsxs(R,{onClick:P,disabled:!h.trim()||g||!!v,className:"bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(ss,{className:"w-4 h-4 mr-2"}),g?"Fetching...":"Fetch Amount"]})]})]}),j!==null&&!v&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-green-50 border-2 border-green-200 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600 uppercase tracking-wide mb-1",children:"Available Amount"}),e.jsxs("p",{className:"text-2xl font-bold text-green-700",children:["₹",j.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsx(Ce,{className:"w-8 h-8 text-green-600"})]}),e.jsxs("div",{className:"mt-3 pt-3 border-t border-green-200",children:[e.jsxs("p",{className:"text-xs text-gray-600",children:[e.jsx("strong",{children:"IO Number:"})," ",h]}),e.jsxs("p",{className:"text-xs text-gray-600 mt-1",children:[e.jsx("strong",{children:"Fetched from:"})," SAP System"]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Q,{htmlFor:"blockAmount",children:"Amount to Block *"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",children:"₹"}),e.jsx(we,{type:"number",id:"blockAmount",placeholder:"Enter amount to block",min:"0",step:"0.01",value:b,onChange:y=>C(y.target.value),className:"pl-8"})]})]}),e.jsxs(R,{onClick:M,disabled:k||!b||parseFloat(b)<=0||parseFloat(b)>j,className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Dt,{className:"w-4 h-4 mr-2"}),k?"Blocking in SAP...":"Block IO in SAP"]})]})]})]}),e.jsxs(X,{children:[e.jsxs(le,{children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx(je,{children:"Details of IO blocked in SAP system"})]}),e.jsx(J,{children:v?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"bg-green-50 border-2 border-green-500 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ce,{className:"w-6 h-6 text-green-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-green-900",children:"IO Blocked Successfully"}),e.jsx("p",{className:"text-sm text-green-700 mt-1",children:"Budget has been reserved in SAP system"})]})]})}),e.jsxs("div",{className:"border rounded-lg divide-y",children:[e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"IO Number"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:v.ioNumber})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"SAP Document Number"}),e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:v.sapDocumentNumber||"N/A"})]}),e.jsxs("div",{className:"p-4 bg-green-50",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"Blocked Amount"}),e.jsxs("p",{className:"text-xl font-bold text-green-700",children:["₹",v.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"Available Amount (Before Block)"}),e.jsxs("p",{className:"text-sm font-medium text-gray-900",children:["₹",v.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("div",{className:"p-4 bg-blue-50",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"Remaining Amount (After Block)"}),e.jsxs("p",{className:"text-sm font-bold text-blue-700",children:["₹",v.remainingBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"Blocked By"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:v.blockedBy})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"Blocked At"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:new Date(v.blockedDate).toLocaleString("en-IN",{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",hour12:!0})})]}),e.jsxs("div",{className:"p-4 bg-gray-50",children:[e.jsx("p",{className:"text-xs text-gray-500 uppercase tracking-wide mb-1",children:"Status"}),e.jsxs(se,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"}),"Blocked"]})]})]})]}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(_s,{className:"w-16 h-16 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-500 mb-2",children:"No IO blocked yet"}),e.jsx("p",{className:"text-xs text-gray-400",children:"Enter IO number and fetch amount to block budget"})]})})]})]})}var _e=function(){return _e=Object.assign||function(s){for(var a,r=1,n=arguments.length;r1&&(c||!d),u=s>1&&(d||!c),h=function(){r&&i(r)},x=function(){n&&i(n)};return e.jsx(W2,{displayMonth:t.displayMonth,hideNext:m,hidePrevious:u,nextMonth:n,previousMonth:r,onPreviousClick:h,onNextClick:x})}function G2(t){var s,a=bt(),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:Np,d;return n?d=e.jsx(c,{id:t.id,displayMonth:t.displayMonth}):o==="dropdown"?d=e.jsx(Qd,{displayMonth:t.displayMonth,id:t.id}):o==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(Qd,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),e.jsx(qd,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id})]}):d=e.jsxs(e.Fragment,{children:[e.jsx(c,{id:t.id,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(qd,{displayMonth:t.displayMonth,id:t.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function K2(t){var s=bt(),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 Y2(t,s,a){for(var r=a?vo(new Date):jo(new Date,{locale:t,weekStartsOn:s}),n=[],i=0;i<7;i++){var o=bs(r,i);n.push(o)}return n}function Z2(){var t=bt(),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,d=Y2(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}),d.map(function(m,u){return e.jsx("th",{scope:"col",className:s.head_cell,style:a.head_cell,"aria-label":c(m,{locale:n}),children:l(m,{locale:n})},u)})]})}function X2(){var t,s=bt(),a=s.classNames,r=s.styles,n=s.components,i=(t=n==null?void 0:n.HeadRow)!==null&&t!==void 0?t:Z2;return e.jsx("thead",{style:r.head,className:a.head,children:e.jsx(i,{})})}function J2(t){var s=bt(),a=s.locale,r=s.formatters.formatDay;return e.jsx(e.Fragment,{children:r(t.date,{locale:a})})}var vl=p.createContext(void 0);function Q2(t){if(!qr(t.initialProps)){var s={selected:void 0,modifiers:{disabled:[]}};return e.jsx(vl.Provider,{value:s,children:t.children})}return e.jsx(q2,{initialProps:t.initialProps,children:t.children})}function q2(t){var s=t.initialProps,a=t.children,r=s.selected,n=s.min,i=s.max,o=function(d,m,u){var h,x;(h=s.onDayClick)===null||h===void 0||h.call(s,d,m,u);var g=!!(m.selected&&n&&(r==null?void 0:r.length)===n);if(!g){var f=!!(!m.selected&&i&&(r==null?void 0:r.length)===i);if(!f){var j=r?vp([],r):[];if(m.selected){var w=j.findIndex(function(b){return gs(d,b)});j.splice(w,1)}else j.push(d);(x=s.onSelect)===null||x===void 0||x.call(s,j,d,m,u)}}},l={disabled:[]};r&&l.disabled.push(function(d){var m=i&&r.length>i-1,u=r.some(function(h){return gs(h,d)});return!!(m&&!u)});var c={selected:r,onDayClick:o,modifiers:l};return e.jsx(vl.Provider,{value:c,children:a})}function jl(){var t=p.useContext(vl);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function eS(t,s){var a=s||{},r=a.from,n=a.to;return r&&n?gs(n,t)&&gs(r,t)?void 0:gs(n,t)?{from:n,to:void 0}:gs(r,t)?void 0:Oi(r,t)?{from:t,to:n}:{from:r,to:t}:n?Oi(t,n)?{from:n,to:t}:{from:t,to:n}:r?wm(t,r)?{from:t,to:r}:{from:r,to:t}:{from:t,to:void 0}}var Nl=p.createContext(void 0);function tS(t){if(!en(t.initialProps)){var s={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(Nl.Provider,{value:s,children:t.children})}return e.jsx(sS,{initialProps:t.initialProps,children:t.children})}function sS(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,d=function(x,g,f){var j,w;(j=s.onDayClick)===null||j===void 0||j.call(s,x,g,f);var b=eS(x,r);(w=s.onSelect)===null||w===void 0||w.call(s,b,x,g,f)},m={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(m.range_start=[i],o?(m.range_end=[o],gs(i,o)||(m.range_middle=[{after:i,before:o}])):m.range_end=[i]):o&&(m.range_start=[o],m.range_end=[o]),l&&(i&&!o&&m.disabled.push({after:Qn(i,l-1),before:bs(i,l-1)}),i&&o&&m.disabled.push({after:i,before:bs(i,l-1)}),!i&&o&&m.disabled.push({after:Qn(o,l-1),before:bs(o,l-1)})),c){if(i&&!o&&(m.disabled.push({before:bs(i,-c+1)}),m.disabled.push({after:bs(i,c-1)})),i&&o){var u=sa(o,i)+1,h=c-u;m.disabled.push({before:Qn(i,h)}),m.disabled.push({after:bs(o,h)})}!i&&o&&(m.disabled.push({before:bs(o,-c+1)}),m.disabled.push({after:bs(o,c-1)}))}return e.jsx(Nl.Provider,{value:{selected:r,onDayClick:d,modifiers:m},children:a})}function wl(){var t=p.useContext(Nl);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function vn(t){return Array.isArray(t)?vp([],t):t!==void 0?[t]:[]}function aS(t){var s={};return Object.entries(t).forEach(function(a){var r=a[0],n=a[1];s[r]=vn(n)}),s}var Ls;(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"})(Ls||(Ls={}));var rS=Ls.Selected,ta=Ls.Disabled,nS=Ls.Hidden,iS=Ls.Today,ki=Ls.RangeEnd,Ti=Ls.RangeMiddle,Di=Ls.RangeStart,oS=Ls.Outside;function lS(t,s,a){var r,n=(r={},r[rS]=vn(t.selected),r[ta]=vn(t.disabled),r[nS]=vn(t.hidden),r[iS]=[t.today],r[ki]=[],r[Ti]=[],r[Di]=[],r[oS]=[],r);return t.fromDate&&n[ta].push({before:t.fromDate}),t.toDate&&n[ta].push({after:t.toDate}),qr(t)?n[ta]=n[ta].concat(s.modifiers[ta]):en(t)&&(n[ta]=n[ta].concat(a.modifiers[ta]),n[Di]=a.modifiers[Di],n[Ti]=a.modifiers[Ti],n[ki]=a.modifiers[ki]),n}var Sp=p.createContext(void 0);function cS(t){var s=bt(),a=jl(),r=wl(),n=lS(s,a,r),i=aS(s.modifiers),o=_e(_e({},n),i);return e.jsx(Sp.Provider,{value:o,children:t.children})}function Ap(){var t=p.useContext(Sp);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function dS(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function mS(t){return!!(t&&typeof t=="object"&&"from"in t)}function uS(t){return!!(t&&typeof t=="object"&&"after"in t)}function hS(t){return!!(t&&typeof t=="object"&&"before"in t)}function pS(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function xS(t,s){var a,r=s.from,n=s.to;if(r&&n){var i=sa(n,r)<0;i&&(a=[n,r],r=a[0],n=a[1]);var o=sa(t,r)>=0&&sa(n,t)>=0;return o}return n?gs(n,t):r?gs(r,t):!1}function gS(t){return Am(t)}function fS(t){return Array.isArray(t)&&t.every(Am)}function yS(t,s){return s.some(function(a){if(typeof a=="boolean")return a;if(gS(a))return gs(t,a);if(fS(a))return a.includes(t);if(mS(a))return xS(t,a);if(pS(a))return a.dayOfWeek.includes(t.getDay());if(dS(a)){var r=sa(a.before,t),n=sa(a.after,t),i=r>0,o=n<0,l=Oi(a.before,a.after);return l?o&&i:i||o}return uS(a)?sa(t,a.after)>0:hS(a)?sa(a.before,t)>0:typeof a=="function"?a(t):!1})}function Cl(t,s,a){var r=Object.keys(s).reduce(function(i,o){var l=s[o];return yS(t,l)&&i.push(o),i},[]),n={};return r.forEach(function(i){return n[i]=!0}),a&&!bo(t,a)&&(n.outside=!0),n}function bS(t,s){for(var a=Ns(t[0]),r=yo(t[t.length-1]),n,i,o=a;o<=r;){var l=Cl(o,s),c=!l.disabled&&!l.hidden;if(!c){o=bs(o,1);continue}if(l.selected)return o;l.today&&!i&&(i=o),n||(n=o),o=bs(o,1)}return i||n}var vS=365;function kp(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,d=n.fromDate,m=n.toDate,u=n.locale,h={day:bs,week:Li,month:Hs,year:mg,startOfWeek:function(j){return n.ISOWeek?vo(j):jo(j,{locale:u,weekStartsOn:c})},endOfWeek:function(j){return n.ISOWeek?Cm(j):Sm(j,{locale:u,weekStartsOn:c})}},x=h[a](t,r==="after"?1:-1);r==="before"&&d?x=ug([d,x]):r==="after"&&m&&(x=hg([m,x]));var g=!0;if(i){var f=Cl(x,i);g=!f.disabled&&!f.hidden}return g?x:l.count>vS?l.lastFocused:kp(x,{moveBy:a,direction:r,context:n,modifiers:i,retry:_e(_e({},l),{count:l.count+1})})}var Tp=p.createContext(void 0);function jS(t){var s=tn(),a=Ap(),r=p.useState(),n=r[0],i=r[1],o=p.useState(),l=o[0],c=o[1],d=bS(s.displayMonths,a),m=n??(l&&s.isDateDisplayed(l))?l:d,u=function(){c(n),i(void 0)},h=function(j){i(j)},x=bt(),g=function(j,w){if(n){var b=kp(n,{moveBy:j,direction:w,context:x,modifiers:a});gs(n,b)||(s.goToDate(b,n),h(b))}},f={focusedDay:n,focusTarget:m,blur:u,focus:h,focusDayAfter:function(){return g("day","after")},focusDayBefore:function(){return g("day","before")},focusWeekAfter:function(){return g("week","after")},focusWeekBefore:function(){return g("week","before")},focusMonthBefore:function(){return g("month","before")},focusMonthAfter:function(){return g("month","after")},focusYearBefore:function(){return g("year","before")},focusYearAfter:function(){return g("year","after")},focusStartOfWeek:function(){return g("startOfWeek","before")},focusEndOfWeek:function(){return g("endOfWeek","after")}};return e.jsx(Tp.Provider,{value:f,children:t.children})}function Sl(){var t=p.useContext(Tp);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function NS(t,s){var a=Ap(),r=Cl(t,a,s);return r}var Al=p.createContext(void 0);function wS(t){if(!Zn(t.initialProps)){var s={selected:void 0};return e.jsx(Al.Provider,{value:s,children:t.children})}return e.jsx(CS,{initialProps:t.initialProps,children:t.children})}function CS(t){var s=t.initialProps,a=t.children,r=function(i,o,l){var c,d,m;if((c=s.onDayClick)===null||c===void 0||c.call(s,i,o,l),o.selected&&!s.required){(d=s.onSelect)===null||d===void 0||d.call(s,void 0,i,o,l);return}(m=s.onSelect)===null||m===void 0||m.call(s,i,i,o,l)},n={selected:s.selected,onDayClick:r};return e.jsx(Al.Provider,{value:n,children:a})}function Dp(){var t=p.useContext(Al);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function SS(t,s){var a=bt(),r=Dp(),n=jl(),i=wl(),o=Sl(),l=o.focusDayAfter,c=o.focusDayBefore,d=o.focusWeekAfter,m=o.focusWeekBefore,u=o.blur,h=o.focus,x=o.focusMonthBefore,g=o.focusMonthAfter,f=o.focusYearBefore,j=o.focusYearAfter,w=o.focusStartOfWeek,b=o.focusEndOfWeek,C=function(S){var D,I,_,F;Zn(a)?(D=r.onDayClick)===null||D===void 0||D.call(r,t,s,S):qr(a)?(I=n.onDayClick)===null||I===void 0||I.call(n,t,s,S):en(a)?(_=i.onDayClick)===null||_===void 0||_.call(i,t,s,S):(F=a.onDayClick)===null||F===void 0||F.call(a,t,s,S)},v=function(S){var D;h(t),(D=a.onDayFocus)===null||D===void 0||D.call(a,t,s,S)},N=function(S){var D;u(),(D=a.onDayBlur)===null||D===void 0||D.call(a,t,s,S)},k=function(S){var D;(D=a.onDayMouseEnter)===null||D===void 0||D.call(a,t,s,S)},E=function(S){var D;(D=a.onDayMouseLeave)===null||D===void 0||D.call(a,t,s,S)},P=function(S){var D;(D=a.onDayPointerEnter)===null||D===void 0||D.call(a,t,s,S)},M=function(S){var D;(D=a.onDayPointerLeave)===null||D===void 0||D.call(a,t,s,S)},y=function(S){var D;(D=a.onDayTouchCancel)===null||D===void 0||D.call(a,t,s,S)},A=function(S){var D;(D=a.onDayTouchEnd)===null||D===void 0||D.call(a,t,s,S)},L=function(S){var D;(D=a.onDayTouchMove)===null||D===void 0||D.call(a,t,s,S)},K=function(S){var D;(D=a.onDayTouchStart)===null||D===void 0||D.call(a,t,s,S)},O=function(S){var D;(D=a.onDayKeyUp)===null||D===void 0||D.call(a,t,s,S)},$=function(S){var D;switch(S.key){case"ArrowLeft":S.preventDefault(),S.stopPropagation(),a.dir==="rtl"?l():c();break;case"ArrowRight":S.preventDefault(),S.stopPropagation(),a.dir==="rtl"?c():l();break;case"ArrowDown":S.preventDefault(),S.stopPropagation(),d();break;case"ArrowUp":S.preventDefault(),S.stopPropagation(),m();break;case"PageUp":S.preventDefault(),S.stopPropagation(),S.shiftKey?f():x();break;case"PageDown":S.preventDefault(),S.stopPropagation(),S.shiftKey?j():g();break;case"Home":S.preventDefault(),S.stopPropagation(),w();break;case"End":S.preventDefault(),S.stopPropagation(),b();break}(D=a.onDayKeyDown)===null||D===void 0||D.call(a,t,s,S)},T={onClick:C,onFocus:v,onBlur:N,onKeyDown:$,onKeyUp:O,onMouseEnter:k,onMouseLeave:E,onPointerEnter:P,onPointerLeave:M,onTouchCancel:y,onTouchEnd:A,onTouchMove:L,onTouchStart:K};return T}function AS(){var t=bt(),s=Dp(),a=jl(),r=wl(),n=Zn(t)?s.selected:qr(t)?a.selected:en(t)?r.selected:void 0;return n}function kS(t){return Object.values(Ls).includes(t)}function TS(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(kS(r)){var i=t.classNames["day_".concat(r)];i&&a.push(i)}}),a}function DS(t,s){var a=_e({},t.styles.day);return Object.keys(s).forEach(function(r){var n;a=_e(_e({},a),(n=t.modifiersStyles)===null||n===void 0?void 0:n[r])}),a}function RS(t,s,a){var r,n,i,o=bt(),l=Sl(),c=NS(t,s),d=SS(t,c),m=AS(),u=!!(o.onDayClick||o.mode!=="default");p.useEffect(function(){var k;c.outside||l.focusedDay&&u&&gs(l.focusedDay,t)&&((k=a.current)===null||k===void 0||k.focus())},[l.focusedDay,t,a,u,c.outside]);var h=TS(o,c).join(" "),x=DS(o,c),g=!!(c.outside&&!o.showOutsideDays||c.hidden),f=(i=(n=o.components)===null||n===void 0?void 0:n.DayContent)!==null&&i!==void 0?i:J2,j=e.jsx(f,{date:t,displayMonth:s,activeModifiers:c}),w={style:x,className:h,children:j,role:"gridcell"},b=l.focusTarget&&gs(l.focusTarget,t)&&!c.outside,C=l.focusedDay&&gs(l.focusedDay,t),v=_e(_e(_e({},w),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=C||b?0:-1,r)),d),N={isButton:u,isHidden:g,activeModifiers:c,selectedDays:m,buttonProps:v,divProps:w};return N}function PS(t){var s=p.useRef(null),a=RS(t.date,t.displayMonth,s);return a.isHidden?e.jsx("div",{role:"gridcell"}):a.isButton?e.jsx(Dn,_e({name:"day",ref:s},a.buttonProps)):e.jsx("div",_e({},a.divProps))}function ES(t){var s=t.number,a=t.dates,r=bt(),n=r.onWeekNumberClick,i=r.styles,o=r.classNames,l=r.locale,c=r.labels.labelWeekNumber,d=r.formatters.formatWeekNumber,m=d(Number(s),{locale:l});if(!n)return e.jsx("span",{className:o.weeknumber,style:i.weeknumber,children:m});var u=c(Number(s),{locale:l}),h=function(x){n(s,a,x)};return e.jsx(Dn,{name:"week-number","aria-label":u,className:o.weeknumber,style:i.weeknumber,onClick:h,children:m})}function IS(t){var s,a,r=bt(),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:PS,d=(a=l==null?void 0:l.WeekNumber)!==null&&a!==void 0?a:ES,m;return o&&(m=e.jsx("td",{className:i.cell,style:n.cell,children:e.jsx(d,{number:t.weekNumber,dates:t.dates})})),e.jsxs("tr",{className:i.row,style:n.row,children:[m,t.dates.map(function(u){return e.jsx("td",{className:i.cell,style:n.cell,role:"presentation",children:e.jsx(c,{displayMonth:t.displayMonth,date:u})},dg(u))})]})}function em(t,s,a){for(var r=a!=null&&a.ISOWeek?Cm(s):Sm(s,a),n=a!=null&&a.ISOWeek?vo(t):jo(t,a),i=sa(r,n),o=[],l=0;l<=i;l++)o.push(bs(n,l));var c=o.reduce(function(d,m){var u=a!=null&&a.ISOWeek?gg(m):fg(m,a),h=d.find(function(x){return x.weekNumber===u});return h?(h.dates.push(m),d):(d.push({weekNumber:u,dates:[m]}),d)},[]);return c}function MS(t,s){var a=em(Ns(t),yo(t),s);if(s!=null&&s.useFixedWeeks){var r=cg(t,s);if(r<6){var n=a[a.length-1],i=n.dates[n.dates.length-1],o=Li(i,6-r),l=em(Li(i,1),o,s);a.push.apply(a,l)}}return a}function FS(t){var s,a,r,n=bt(),i=n.locale,o=n.classNames,l=n.styles,c=n.hideHead,d=n.fixedWeeks,m=n.components,u=n.weekStartsOn,h=n.firstWeekContainsDate,x=n.ISOWeek,g=MS(t.displayMonth,{useFixedWeeks:!!d,ISOWeek:x,locale:i,weekStartsOn:u,firstWeekContainsDate:h}),f=(s=m==null?void 0:m.Head)!==null&&s!==void 0?s:X2,j=(a=m==null?void 0:m.Row)!==null&&a!==void 0?a:IS,w=(r=m==null?void 0:m.Footer)!==null&&r!==void 0?r:K2;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:g.map(function(b){return e.jsx(j,{displayMonth:t.displayMonth,dates:b.dates,weekNumber:b.weekNumber},b.weekNumber)})}),e.jsx(w,{displayMonth:t.displayMonth})]})}function _S(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var LS=_S()?p.useLayoutEffect:p.useEffect,Ri=!1,OS=0;function tm(){return"react-day-picker-".concat(++OS)}function $S(t){var s,a=t??(Ri?tm():null),r=p.useState(a),n=r[0],i=r[1];return LS(function(){n===null&&i(tm())},[]),p.useEffect(function(){Ri===!1&&(Ri=!0)},[]),(s=t??n)!==null&&s!==void 0?s:void 0}function BS(t){var s,a,r=bt(),n=r.dir,i=r.classNames,o=r.styles,l=r.components,c=tn().displayMonths,d=$S(r.id?"".concat(r.id,"-").concat(t.displayIndex):void 0),m=r.id?"".concat(r.id,"-grid-").concat(t.displayIndex):void 0,u=[i.month],h=o.month,x=t.displayIndex===0,g=t.displayIndex===c.length-1,f=!x&&!g;n==="rtl"&&(s=[x,g],g=s[0],x=s[1]),x&&(u.push(i.caption_start),h=_e(_e({},h),o.caption_start)),g&&(u.push(i.caption_end),h=_e(_e({},h),o.caption_end)),f&&(u.push(i.caption_between),h=_e(_e({},h),o.caption_between));var j=(a=l==null?void 0:l.Caption)!==null&&a!==void 0?a:G2;return e.jsxs("div",{className:u.join(" "),style:h,children:[e.jsx(j,{id:d,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),e.jsx(FS,{id:m,"aria-labelledby":d,displayMonth:t.displayMonth})]},t.displayIndex)}function US(t){var s=bt(),a=s.classNames,r=s.styles;return e.jsx("div",{className:a.months,style:r.months,children:t.children})}function VS(t){var s,a,r=t.initialProps,n=bt(),i=Sl(),o=tn(),l=p.useState(!1),c=l[0],d=l[1];p.useEffect(function(){n.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),d(!0)))},[n.initialFocus,c,i.focus,i.focusTarget,i]);var m=[n.classNames.root,n.className];n.numberOfMonths>1&&m.push(n.classNames.multiple_months),n.showWeekNumber&&m.push(n.classNames.with_weeknumber);var u=_e(_e({},n.styles.root),n.style),h=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,f){var j;return _e(_e({},g),(j={},j[f]=r[f],j))},{}),x=(a=(s=r.components)===null||s===void 0?void 0:s.Months)!==null&&a!==void 0?a:US;return e.jsx("div",_e({className:m.join(" "),style:u,dir:n.dir,id:n.id,nonce:r.nonce,title:r.title,lang:r.lang},h,{children:e.jsx(x,{children:o.displayMonths.map(function(g,f){return e.jsx(BS,{displayIndex:f,displayMonth:g},f)})})}))}function zS(t){var s=t.children,a=h2(t,["children"]);return e.jsx(E2,{initialProps:a,children:e.jsx(V2,{children:e.jsx(wS,{initialProps:a,children:e.jsx(Q2,{initialProps:a,children:e.jsx(tS,{initialProps:a,children:e.jsx(cS,{children:e.jsx(jS,{children:s})})})})})})})}function HS(t){return e.jsx(zS,_e({},t,{children:e.jsx(VS,{initialProps:t})}))}function Pi({className:t,classNames:s,showOutsideDays:a=!0,...r}){return e.jsx(HS,{showOutsideDays:a,className:ge("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:ge(Mr({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:ge("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:ge(Mr({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(Lm,{className:ge("size-4",n),...i}),IconRight:({className:n,...i})=>e.jsx(ko,{className:ge("size-4",n),...i})},...r})}async function WS(){var t;try{const s=await he.get("/dealers");return((t=s.data)==null?void 0:t.data)||s.data||[]}catch(s){throw console.error("[DealerAPI] Error fetching dealers:",s),s}}async function GS(t){var s;try{const a=await he.get(`/dealers/code/${t}`);return((s=a.data)==null?void 0:s.data)||a.data||null}catch(a){return console.error("[DealerAPI] Error fetching dealer by code:",a),null}}const KS=["Marketing Activity","Promotional Event","Dealer Training","Infrastructure Development","Customer Experience Initiative","Service Campaign"],Ei=["Claim Details","Review & Submit"];function YS({onBack:t,onSubmit:s}){const[a,r]=p.useState(1),[n,i]=p.useState([]),[o,l]=p.useState(!0),[c,d]=p.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:""}),m=Ei.length;p.useEffect(()=>{(async()=>{l(!0);try{const C=await WS();i(C)}catch(C){ne.error("Failed to load dealer list."),console.error("Error fetching dealers:",C)}finally{l(!1)}})()},[]);const u=(b,C)=>{d(v=>({...v,[b]:C}))},h=()=>{switch(a){case 1:return c.activityName&&c.activityType&&c.dealerCode&&c.dealerName&&c.activityDate&&c.location&&c.requestDescription;case 2:return!0;default:return!1}},x=()=>{a{a>1&&r(a-1)},f=async b=>{const C=n.find(v=>v.dealerCode===b);if(C){u("dealerCode",b),u("dealerName",C.dealerName),u("dealerEmail",C.email||""),u("dealerPhone",C.phone||""),u("dealerAddress","");try{const v=await GS(b);v&&(u("dealerEmail",v.email||C.email||""),u("dealerPhone",v.phone||C.phone||""))}catch(v){console.debug("Could not fetch full dealer info:",v)}}},j=()=>{const b={...c,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"}]};s&&s(b)},w=()=>{switch(a){case 1:return e.jsxs(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(ms,{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(Q,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(we,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:c.activityName,onChange:b=>u("activityName",b.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(Q,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(Be,{value:c.activityType,onValueChange:b=>u("activityType",b),children:[e.jsx(Ve,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(Ue,{placeholder:"Select activity type"})}),e.jsx(ze,{children:KS.map(b=>e.jsx(W,{value:b,children:b},b))})]})]})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-base font-semibold",children:"Dealer Code / Dealer Name *"}),e.jsxs(Be,{value:c.dealerCode,onValueChange:f,disabled:o,children:[e.jsx(Ve,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"dealer-select",children:e.jsx(Ue,{placeholder:o?"Loading dealers...":"Select dealer",children:c.dealerCode&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm",children:c.dealerCode}),e.jsx("span",{className:"text-gray-400",children:"•"}),e.jsx("span",{children:c.dealerName})]})})}),e.jsx(ze,{children:n.length===0&&!o?e.jsx("div",{className:"p-2 text-sm text-gray-500",children:"No dealers available"}):n.map(b=>e.jsx(W,{value:b.dealerCode,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-semibold",children:b.dealerCode}),e.jsx("span",{className:"text-gray-400",children:"•"}),e.jsx("span",{children:b.dealerName})]})},b.userId))})]}),c.dealerCode&&e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:c.dealerName})," (",c.dealerCode,")"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Q,{className:"text-base font-semibold",children:"Date *"}),e.jsxs($s,{children:[e.jsx(Bs,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),c.activityDate?Ne(c.activityDate,"PPP"):"Select date"]})}),e.jsx(Us,{className:"w-auto p-0",align:"start",children:e.jsx(Pi,{mode:"single",selected:c.activityDate,onSelect:b=>u("activityDate",b),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(Q,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(we,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:c.location,onChange:b=>u("location",b.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(Q,{htmlFor:"requestDescription",className:"text-base font-semibold",children:"Request in Detail - Brief Requirement *"}),e.jsx(ns,{id:"requestDescription",placeholder:"Provide a detailed description of your claim requirement...",value:c.requestDescription,onChange:b=>u("requestDescription",b.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(Q,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(se,{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(Q,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs($s,{children:[e.jsx(Bs,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),c.periodStartDate?Ne(c.periodStartDate,"PPP"):"Start date"]})}),e.jsx(Us,{className:"w-auto p-0",align:"start",children:e.jsx(Pi,{mode:"single",selected:c.periodStartDate,onSelect:b=>u("periodStartDate",b),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs($s,{children:[e.jsx(Bs,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),c.periodEndDate?Ne(c.periodEndDate,"PPP"):"End date"]})}),e.jsx(Us,{className:"w-auto p-0",align:"start",children:e.jsx(Pi,{mode:"single",selected:c.periodEndDate,onSelect:b=>u("periodEndDate",b),initialFocus:!0})})]})]})]}),(c.periodStartDate||c.periodEndDate)&&e.jsx("p",{className:"text-xs text-gray-600 mt-2",children:c.periodStartDate&&c.periodEndDate?`Period: ${Ne(c.periodStartDate,"MMM dd, yyyy")} - ${Ne(c.periodEndDate,"MMM dd, yyyy")}`:"Please select both start and end dates for the period"})]})]})]});case 2:return e.jsxs(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-green-500 to-emerald-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(Ce,{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(X,{className:"border-2",children:[e.jsx(le,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(ms,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(J,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Q,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:c.activityName})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(se,{variant:"secondary",className:"mt-1",children:c.activityType})]})]})})]}),e.jsxs(X,{className:"border-2",children:[e.jsx(le,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(On,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(J,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Q,{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:c.dealerCode})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:c.dealerName})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:c.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:c.dealerPhone})]}),c.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(Q,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:c.dealerAddress})]})]})})]}),e.jsxs(X,{className:"border-2",children:[e.jsx(le,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(J,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Q,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:c.activityDate?Ne(c.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(Q,{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(So,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:c.location})]})]}),c.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(Q,{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:c.estimatedBudget})]})]})})]}),e.jsxs(X,{className:"border-2",children:[e.jsx(le,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(J,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(Q,{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:c.requestDescription})})]})})]}),(c.periodStartDate||c.periodEndDate)&&e.jsxs(X,{className:"border-2",children:[e.jsx(le,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(He,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(J,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(Q,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:c.periodStartDate?Ne(c.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:c.periodEndDate?Ne(c.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(Hr,{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(R,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(Rs,{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(se,{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 ",m,": ",e.jsx("span",{className:"hidden sm:inline",children:Ei[a-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(Gs,{value:a/m*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:Ei.map((b,C)=>e.jsx("span",{className:`text-xs sm:text-sm ${C+1<=a?"text-blue-600 font-medium":"text-gray-400"}`,children:C+1},C))})]})]}),e.jsx(X,{className:"mb-6 sm:mb-8",children:e.jsx(J,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(Hn,{mode:"wait",children:w()})})}),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(R,{variant:"outline",onClick:g,disabled:a===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(Rs,{className:"w-4 h-4"}),"Previous"]}),awindow.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(R,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function aA({requestId:t,onBack:s,dynamicRequests:a=[]}){var lr,cr,dr,mr,ur,hr,pr,xr,gr,fr;const n=Oa().requestId||t||"",o=new URLSearchParams(window.location.search).get("tab")||"overview",[l,c]=p.useState(o),[d,m]=p.useState(!1),[u,h]=p.useState(null),[x,g]=p.useState(null),[f,j]=p.useState(!1),[w,b]=p.useState(0),[C,v]=p.useState(!1),[N,k]=p.useState(!1),[E,P]=p.useState(!1),{user:M}=Gt(),{request:y,apiRequest:A,loading:L,refreshing:K,refreshDetails:O,currentApprovalLevel:$,isSpectator:T,isInitiator:S,existingParticipants:D,accessDenied:I}=Fo(n,a,M),_=(M==null?void 0:M.userId)||"",F=((lr=M==null?void 0:M.email)==null?void 0:lr.toLowerCase())||"",G=(cr=A==null?void 0:A.initiator)==null?void 0:cr.userId,B=(mr=(dr=A==null?void 0:A.initiator)==null?void 0:dr.email)==null?void 0:mr.toLowerCase(),re=(A==null?void 0:A.initiator)&&(G&&G===_||B&&B===F),ae=(A==null?void 0:A.approvalFlow)||[],V=(A==null?void 0:A.approvals)||[],Y=ae.find(Ct=>(Ct.step||Ct.levelNumber||Ct.level_number)===3)||V.find(Ct=>(Ct.levelNumber||Ct.level_number)===3),Z=(Y==null?void 0:Y.approverId)||(Y==null?void 0:Y.approver_id)||((ur=Y==null?void 0:Y.approver)==null?void 0:ur.userId),U=((Y==null?void 0:Y.approverEmail)||(Y==null?void 0:Y.approver_email)||((hr=Y==null?void 0:Y.approver)==null?void 0:hr.email)||"").toLowerCase().trim(),ee=Z&&Z===_||U&&F&&U===F,ie=Y!=null&&Y.status?String(Y.status).toUpperCase():"",de=ie==="PENDING"||ie==="IN_PROGRESS"||ie==="PAUSED",We=((A==null?void 0:A.currentLevel)||(A==null?void 0:A.current_level)||(A==null?void 0:A.currentStep)||0)===3,Ge=re||ee||Y&&de&&We&&(Z&&Z===_||U&&F&&U===F)||ie==="APPROVED",{mergedMessages:Oe,unreadWorkNotes:ct,workNoteAttachments:te,setWorkNoteAttachments:xe}=sp(n,A,l,M),{uploadingDocument:dt,triggerFileInput:ue,previewDocument:Te,setPreviewDocument:Qe,documentPolicy:ht,documentError:et,setDocumentError:qt}=ap(A,O),{showApproveModal:Es,setShowApproveModal:Xs,showRejectModal:H,setShowRejectModal:me,showAddApproverModal:z,setShowAddApproverModal:fe,showAddSpectatorModal:ye,setShowAddSpectatorModal:Re,showSkipApproverModal:be,setShowSkipApproverModal:Me,showActionStatusModal:ke,setShowActionStatusModal:Le,skipApproverData:Xt,setSkipApproverData:wt,actionStatus:Ke,setActionStatus:$e,handleApproveConfirm:at,handleRejectConfirm:zt,handleAddApprover:vt,handleSkipApprover:Cs,handleAddSpectator:Is}=rp(n,$,O);p.useEffect(()=>{const Ss=new URLSearchParams(window.location.search).get("tab");Ss&&c(Ss)},[n]);const Js=()=>{O()},Qs=()=>{v(!0)},ot=()=>{k(!0)},va=async()=>{await O()},ja=()=>{P(!0)},Na=async()=>{await O()},Ht=async()=>{await O()},is=async()=>{if(!(A!=null&&A.requestId)){ne.error("Request ID not found");return}if(!u){ne.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},Ms=(y==null?void 0:y.status)==="closed"||(y==null?void 0:y.status)==="approved"&&!S||(y==null?void 0:y.status)==="rejected"&&!S;p.useEffect(()=>{(async()=>{if(!Ms||!(A!=null&&A.requestId)){g(null),h(null);return}try{j(!0);const Ss=await dp(A.requestId);if(Ss!=null&&Ss.summaryId){h(Ss.summaryId);try{const Ba=await fl(Ss.summaryId);g(Ba)}catch(Ba){console.error("Failed to fetch summary details:",Ba),g(null),h(null)}}else g(null),h(null)}catch{g(null),h(null)}finally{j(!1)}})()},[Ms,A==null?void 0:A.requestId]);const or=((y==null?void 0:y.approvalFlow)||[]).filter(Ct=>Ct&&typeof Ct.step=="number").map(Ct=>({levelNumber:Ct.step||0,approverName:Ct.approver||"Unknown",status:Ct.status||"pending",tatHours:Ct.tatHours||24}));return L&&!y&&!A?e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Zt,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading dealer claim request details..."})]})}):I!=null&&I.denied?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"access-denied-state",children:e.jsxs("div",{className:"max-w-lg w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(Fm,{className:"w-10 h-10 text-red-500"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Access Denied"}),e.jsx("p",{className:"text-gray-600 mb-6 leading-relaxed",children:I.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(R,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Rs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(R,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):y?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"dealer-claim-request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx(qS,{request:y,refreshing:K,onBack:s||(()=>window.history.back()),onRefresh:Js,onShareSummary:is,isInitiator:S}),e.jsxs(Jr,{value:l,onValueChange:c,className:"w-full","data-testid":"dealer-claim-request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(Qr,{className:"grid grid-cols-3 sm:grid-cols-6 lg:flex lg:flex-row h-auto bg-gray-100 p-1.5 sm:p-1 rounded-lg gap-1.5 sm:gap-1",children:[e.jsxs(gt,{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(_m,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),Ms&&x&&e.jsxs(gt,{value:"summary",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-summary",children:[e.jsx(Ao,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Summary"})]}),e.jsxs(gt,{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(Zs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),Ge&&e.jsxs(gt,{value:"io",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-io",children:[e.jsx(_s,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"IO"})]}),e.jsxs(gt,{value:"documents",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-documents",children:[e.jsx(Ee,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Docs"})]}),e.jsxs(gt,{value:"activity",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 col-span-1 sm:col-span-1","data-testid":"tab-activity",children:[e.jsx(Vt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Activity"})]}),e.jsxs(gt,{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(Ps,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),ct>0&&e.jsx(se,{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:ct>9?"9+":ct})]})]})}),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(ft,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(K1,{request:y,apiRequest:A,currentUserId:_,isInitiator:S})}),Ms&&e.jsx(ft,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(QS,{summary:x,loading:f,onShare:is,isInitiator:S})}),e.jsx(ft,{value:"workflow",className:"mt-0",children:e.jsx(m2,{request:y,user:M,isInitiator:S,onSkipApprover:Ct=>{if(!Ct.levelId){alert("Level ID not available");return}wt(Ct),Me(!0)},onRefresh:O})}),Ge&&e.jsx(ft,{value:"io",className:"mt-0",children:e.jsx(u2,{request:y,apiRequest:A,onRefresh:O})}),e.jsx(ft,{value:"documents",className:"mt-0",children:e.jsx(ZS,{request:y,workNoteAttachments:te,uploadingDocument:dt,documentPolicy:ht,triggerFileInput:ue,setPreviewDocument:Qe,downloadDocument:_r})}),e.jsx(ft,{value:"activity",className:"mt-0",children:e.jsx(XS,{request:y})}),e.jsx(ft,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:l!=="worknotes",children:e.jsx(JS,{requestId:n,requestTitle:y.title,mergedMessages:Oe,setWorkNoteAttachments:xe,isInitiator:S,isSpectator:T,currentLevels:or,onAddApprover:vt})})]}),l!=="worknotes"&&e.jsx(eA,{request:y,isInitiator:S,isSpectator:T,currentApprovalLevel:$,onAddApprover:()=>fe(!0),onAddSpectator:()=>Re(!0),onApprove:()=>Xs(!0),onReject:()=>me(!0),onPause:Qs,onResume:ot,onRetrigger:ja,summaryId:u,refreshTrigger:w,pausedByUserId:(xr=(pr=y==null?void 0:y.pauseInfo)==null?void 0:pr.pausedBy)==null?void 0:xr.userId,currentUserId:_,apiRequest:A})]})]})]})}),d&&u&&e.jsx(xp,{isOpen:d,onClose:()=>m(!1),summaryId:u,requestTitle:(y==null?void 0:y.title)||"N/A",onSuccess:()=>{O(),b(Ct=>Ct+1)}}),C&&(A==null?void 0:A.requestId)&&e.jsx(gp,{isOpen:C,onClose:()=>v(!1),requestId:A.requestId,levelId:($==null?void 0:$.levelId)||null,onSuccess:Na}),N&&(A==null?void 0:A.requestId)&&e.jsx(fp,{isOpen:N,onClose:()=>k(!1),requestId:A.requestId,onSuccess:va}),E&&(A==null?void 0:A.requestId)&&e.jsx(yp,{isOpen:E,onClose:()=>P(!1),requestId:A.requestId,approverName:(fr=(gr=y==null?void 0:y.pauseInfo)==null?void 0:gr.pausedBy)==null?void 0:fr.name,onSuccess:Ht}),e.jsx(tA,{showApproveModal:Es,showRejectModal:H,showAddApproverModal:z,showAddSpectatorModal:ye,showSkipApproverModal:be,showActionStatusModal:ke,previewDocument:Te,documentError:et,request:y,skipApproverData:Xt,actionStatus:Ke,existingParticipants:D,currentLevels:or,setShowApproveModal:Xs,setShowRejectModal:me,setShowAddApproverModal:fe,setShowAddSpectatorModal:Re,setShowSkipApproverModal:Me,setShowActionStatusModal:Le,setPreviewDocument:Qe,setDocumentError:qt,setSkipApproverData:wt,setActionStatus:$e,handleApproveConfirm:at,handleRejectConfirm:zt,handleAddApprover:vt,handleAddSpectator:Is,handleSkipApprover:Cs,downloadDocument:_r,documentPolicy:ht})]}):e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"not-found-state",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(Ee,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Dealer Claim Request Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The dealer claim request you're looking for doesn't exist or may have been deleted."}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(R,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Rs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(R,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function rA(t){return e.jsx(sA,{children:e.jsx(aA,{...t})})}function nA(t){switch(t){case"DEALER_CLAIM":return rA;case"CUSTOM":default:return G1}}class iA extends p.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("RequestDetail Router Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(as,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(R,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(R,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function oA({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=Oa().requestId||t||"",{user:i}=Gt(),{apiRequest:o,loading:l}=Fo(n,a,i);if(l&&!o)return e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Zt,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading request details..."})]})});const c=Ib(o),d=nA(c);return e.jsx(d,{requestId:t,onBack:s,dynamicRequests:a})}function lA(t){return e.jsx(iA,{children:e.jsx(oA,{...t})})}function cA({onViewSummary:t}){const s=ya(),[a,r]=p.useState([]),[n,i]=p.useState(!0),[o,l]=p.useState(""),[c,d]=p.useState(1),[m,u]=p.useState(1),[h,x]=p.useState(0),g=10,f=p.useCallback(async(C=1)=>{try{i(!0);const v=await S1({page:C,limit:g});r(v.data||[]),u(v.pagination.totalPages||1),x(v.pagination.total||0),d(v.pagination.page||1)}catch(v){console.error("Failed to fetch shared summaries:",v),ne.error("Failed to load shared summaries")}finally{i(!1)}},[]);p.useEffect(()=>{f(1)},[f]);const j=async C=>{try{await cp(C),r(v=>v.map(N=>N.sharedSummaryId===C?{...N,isRead:!0,viewedAt:new Date().toISOString()}:N)),t?t(C):s(`/shared-summaries/${C}`)}catch(v){console.error("Failed to mark as viewed:",v),t?t(C):s(`/shared-summaries/${C}`)}},w=C=>{C>=1&&C<=m&&f(C)},b=a.filter(C=>{var N,k,E,P;if(!o)return!0;const v=o.toLowerCase();return((N=C.title)==null?void 0:N.toLowerCase().includes(v))||((k=C.requestNumber)==null?void 0:k.toLowerCase().includes(v))||((E=C.initiatorName)==null?void 0:E.toLowerCase().includes(v))||((P=C.sharedByName)==null?void 0:P.toLowerCase().includes(v))});return e.jsx("div",{className:"min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6 overflow-x-hidden",children:e.jsxs("div",{className:"max-w-7xl mx-auto w-full",children:[e.jsxs("div",{className:"mb-4 sm:mb-6",children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900 mb-1 sm:mb-2",children:"Shared Summaries"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600",children:"View summaries of closed requests shared with you"})]}),e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs("div",{className:"relative",children:[e.jsx(ws,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(we,{placeholder:"Search by title, request number, or user...",value:o,onChange:C=>l(C.target.value),className:"pl-10 text-sm sm:text-base"})]})}),n&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Je,{className:"h-8 w-8 animate-spin text-blue-600"})}),!n&&b.length===0&&e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 p-6 sm:p-12 text-center",children:[e.jsx(Ee,{className:"h-8 w-8 sm:h-12 sm:w-12 text-gray-400 mx-auto mb-3 sm:mb-4"}),e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-1 sm:mb-2",children:"No shared summaries"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:o?"No summaries match your search.":"You haven't received any shared summaries yet."})]}),!n&&b.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-3 sm:gap-4 mb-4 sm:mb-6",children:b.map(C=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${C.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>j(C.sharedSummaryId),children:e.jsx("div",{className:"p-3 sm:p-4 md:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0 w-full sm:w-auto",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[C.isRead?e.jsx(Yg,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}):e.jsx(rs,{className:"h-4 w-4 text-blue-600 flex-shrink-0"}),e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900 truncate flex-1 min-w-0",children:C.title}),!C.isRead&&e.jsx("span",{className:"px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-medium rounded-full flex-shrink-0",children:"New"})]}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 break-words",children:["Request: ",e.jsx("span",{className:"font-medium",children:C.requestNumber})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap items-start sm:items-center gap-2 sm:gap-3 md:gap-4 text-xs sm:text-sm text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(St,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Initiator: ",e.jsx("span",{className:"font-medium",children:C.initiatorName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(St,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared by: ",e.jsx("span",{className:"font-medium",children:C.sharedByName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(qe,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",Ne(new Date(C.sharedAt),"MMM dd, yyyy HH:mm")]})]}),C.viewedAt&&e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(rs,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",Ne(new Date(C.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(R,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:v=>{v.stopPropagation(),j(C.sharedSummaryId)},children:"View"})]})})},C.sharedSummaryId))}),m>1&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 sm:gap-4 bg-white rounded-lg shadow-sm border border-gray-200 p-3 sm:p-4",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-gray-600 text-center sm:text-left",children:["Showing ",(c-1)*g+1," to ",Math.min(c*g,h)," of ",h," summaries"]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(R,{variant:"outline",size:"sm",onClick:()=>w(c-1),disabled:c===1,className:"text-xs sm:text-sm",children:"Previous"}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 whitespace-nowrap",children:["Page ",c," of ",m]}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>w(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function dA(){const{sharedSummaryId:t}=Oa(),s=ya(),[a,r]=p.useState(null),[n,i]=p.useState(!0);p.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var m,u;try{i(!0);try{await cp(t)}catch(x){console.warn("Failed to mark as viewed:",x)}const h=await fl(t);r(h)}catch(h){console.error("Failed to fetch summary details:",h),ne.error(((u=(m=h==null?void 0:h.response)==null?void 0:m.data)==null?void 0:u.message)||"Failed to load summary"),s("/shared-summaries")}finally{i(!1)}})()},[t,s]);const o=d=>{const m=d.toLowerCase();return m==="approved"?e.jsx(Ce,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(yt,{className:"h-4 w-4 text-red-600"}):m==="pending"||m==="in progress"?e.jsx(He,{className:"h-4 w-4 text-orange-600"}):e.jsx(Ee,{className:"h-4 w-4 text-gray-600"})},l=d=>{const m=d.toLowerCase();return m==="approved"?"bg-green-100 text-green-700 border-green-300":m==="rejected"?"bg-red-100 text-red-700 border-red-300":m==="pending"||m==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},c=(d,m)=>d&&d.trim()&&d.trim().toUpperCase()!=="N/A"?d:m&&m.trim()&&m.trim().toUpperCase()!=="N/A"?m:"N/A";return n?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Je,{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(R,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(Rs,{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(se,{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("div",{className:"mb-4",children:e.jsx(ma,{content:a.description,className:"text-gray-700"})})]}),e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Initiator"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(a.initiator.designation,a.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.status})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:Ne(new Date(a.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),a.approvers&&a.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),a.approvers.map((d,m)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsxs("h4",{className:"text-md font-semibold text-gray-800 mb-3",children:["Approver ",d.levelNumber]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:d.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(d.designation,d.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1",children:[o(d.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:d.status})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:Ne(new Date(d.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),e.jsx("p",{className:"text-sm text-gray-700",children:d.remarks})]})]},m))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:a.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(a.initiator.designation,a.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),a.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(se,{variant:"outline",className:"text-xs",children:"AI Generated"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),a.closingRemarks?e.jsx(ma,{content:a.closingRemarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]})]})]})]})}):e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ee,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Summary Not Found"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"The summary you're looking for doesn't exist."}),e.jsx(R,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function mA(){const{requestId:t}=Oa(),s=ya(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(es,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(lp,{requestId:t||""})})})}function Rp({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(se,{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 vs({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:o,testId:l="stats-card",onClick:c}){return e.jsx(X,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":l,onClick:c,children:e.jsx(J,{className:"p-3 sm:p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:`text-xs sm:text-sm font-medium ${i}`,"data-testid":`${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 uA({stats:t,onStatusFilter:s}){const a=r=>{s&&s(r)};return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-3 sm:gap-4","data-testid":"my-requests-stats",children:[e.jsx(vs,{label:"Total",value:t.total,icon:Ee,iconColor:"text-blue-600",gradient:"bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200",textColor:"text-blue-700",valueColor:"text-blue-900",testId:"stat-total",onClick:s?()=>a("all"):void 0}),e.jsx(vs,{label:"Pending",value:t.pending,icon:He,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(vs,{label:"Paused",value:t.paused,icon:ha,iconColor:"text-amber-600",gradient:"bg-gradient-to-br from-amber-50 to-amber-100 border-amber-200",textColor:"text-amber-700",valueColor:"text-amber-900",testId:"stat-paused",onClick:s?()=>a("paused"):void 0}),e.jsx(vs,{label:"Approved",value:t.approved,icon:Ce,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(vs,{label:"Rejected",value:t.rejected,icon:yt,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(vs,{label:"Draft",value:t.draft,icon:$n,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(vs,{label:"Closed",value:t.closed,icon:Bn,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 hA({searchTerm:t,statusFilter:s,priorityFilter:a,onSearchChange:r,onStatusChange:n,onPriorityChange:i}){return e.jsx(X,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(J,{className:"p-3 sm:p-4 md:p-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-3 sm:gap-4 items-start md:items-center",children:[e.jsxs("div",{className:"flex-1 relative w-full",children:[e.jsx(ws,{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(we,{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(Be,{value:s,onValueChange:n,children:[e.jsx(Ve,{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(Ue,{placeholder:"Status"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Status"}),e.jsx(W,{value:"draft",children:"Draft"}),e.jsx(W,{value:"pending",children:"Pending"}),e.jsx(W,{value:"paused",children:"Paused"}),e.jsx(W,{value:"approved",children:"Approved"}),e.jsx(W,{value:"rejected",children:"Rejected"}),e.jsx(W,{value:"closed",children:"Closed"})]})]}),e.jsxs(Be,{value:a,onValueChange:i,children:[e.jsx(Ve,{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(Ue,{placeholder:"Priority"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Priority"}),e.jsx(W,{value:"express",children:"Express"}),e.jsx(W,{value:"standard",children:"Standard"})]})]})]})]})})})}function pA(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Os,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Dt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Dt,iconColor:"text-gray-600"}}}function xA(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Ce,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:yt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:He,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ce,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:$n,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ie,iconColor:"text-gray-600"}}}const gA=t=>{if(!t)return"";if(typeof document>"u")return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();const s=document.createElement("div");s.innerHTML=t;let a=s.textContent||s.innerText||"";return a=a.replace(/\s+/g," ").trim(),a};function fA({request:t,index:s,onViewRequest:a}){var l;const r=xA(t.status),n=pA(t.priority),i=r.icon,o=n.icon;return e.jsx(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(X,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(J,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(se,{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})]}),(((l=t.pauseInfo)==null?void 0:l.isPaused)||t.isPaused)&&e.jsxs(se,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-300 font-medium text-xs shrink-0","data-testid":"pause-badge",children:[e.jsx(ha,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(se,{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]}),(()=>{const c=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",d=(c==null?void 0:c.toUpperCase())||"";let m="Custom",u="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Claim Management",u="bg-blue-100 !text-blue-700 border-blue-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(se,{variant:"outline",className:`${u} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:m})})()]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 line-clamp-2 leading-relaxed","data-testid":"request-description",children:gA(t.description||"")||"No description provided"}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-4 text-xs sm:text-sm text-gray-500",children:[e.jsxs("span",{className:"truncate","data-testid":"request-id-display",children:[e.jsx("span",{className:"font-medium",children:"ID:"})," ",t.displayId||t.id]}),e.jsxs("span",{className:"truncate","data-testid":"submitted-date",children:[e.jsx("span",{className:"font-medium",children:"Submitted:"})," ",Ks(t.submittedDate)]})]})]}),e.jsx(Wt,{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(St,{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(Zs,{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(He,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",Ks(t.submittedDate)]})]})]})]})})})})}function yA({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(X,{"data-testid":"loading-state",children:e.jsx(J,{className:"p-6 text-sm text-gray-600",children:"Loading your requests…"})});if(t.length===0){const o=a||r!=="all"||n!=="all";return e.jsx(X,{"data-testid":"empty-state",children:e.jsxs(J,{className:"p-12 text-center",children:[e.jsx(Ee,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600",children: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(fA,{request:o,index:l,onViewRequest:i},o.id))})}function bA(t){var r,n;const s=t.submittedAt||t.submitted_at||t.createdAt||t.created_at,a=(t.priority||"").toString().toLowerCase();return{id:t.requestNumber||t.request_number||t.requestId||t.id||t.request_id,requestId:t.requestId||t.id||t.request_id,displayId:t.requestNumber||t.request_number||t.id,title:t.title,description:t.description,status:(t.status||"").toString().toLowerCase().replace("_","-"),priority:a,department:t.department,submittedDate:t.submittedAt||(t.createdAt?new Date(t.createdAt).toISOString().split("T")[0]:void 0),createdAt:s,currentApprover:((r=t.currentApprover)==null?void 0:r.name)||((n=t.currentApprover)==null?void 0:n.email)||"—",approverLevel:t.currentLevel&&t.totalLevels?`${t.currentLevel} of ${t.totalLevels}`:t.currentStep&&t.totalSteps?`${t.currentStep} of ${t.totalSteps}`:"—",templateType:t.templateType||t.template_type,workflowType:t.workflowType||t.workflow_type,templateName:t.templateName||t.template_name}}function Pp(t){return Array.isArray(t)?t.map(bA):[]}function vA({itemsPerPage:t=10}={}){const[s,a]=p.useState([]),[r,n]=p.useState(!1),[i,o]=p.useState(!1),[l,c]=p.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=p.useCallback(async(m=1,u)=>{try{m===1&&(n(!0),a([]));const h=await hs.listMyInitiatedWorkflows({page:m,limit:t,search:u==null?void 0:u.search,status:u==null?void 0:u.status,priority:u==null?void 0:u.priority}),x=Array.isArray(h==null?void 0:h.data)?h.data:[],g=Pp(x);a(g),o(!0);const f=h==null?void 0:h.pagination;f&&c({currentPage:f.page||1,totalPages:f.totalPages||1,totalRecords:f.total||0,itemsPerPage:t})}catch(h){console.error("[MyRequests] Error fetching requests:",h),a([]),o(!0)}finally{n(!1)}},[t]);return{requests:s,loading:r,hasFetchedFromApi:i,pagination:l,fetchMyRequests:d}}const jA={searchTerm:"",statusFilter:"all",priorityFilter:"all",currentPage:1},Ep=tr({name:"myRequests",initialState:jA,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload,t.currentPage=1},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.currentPage=1}}}),{setSearchTerm:NA,setStatusFilter:wA,setPriorityFilter:CA,setCurrentPage:SA,clearFilters:AA}=Ep.actions;function kA({onFiltersChange:t,debounceMs:s=500}={}){const a=Gr(),r=p.useRef(null),n=p.useRef(!0),{searchTerm:i,statusFilter:o,priorityFilter:l,currentPage:c}=ar(f=>f.myRequests),d=p.useCallback(f=>a(NA(f)),[a]),m=p.useCallback(f=>a(wA(f)),[a]),u=p.useCallback(f=>a(CA(f)),[a]),h=p.useCallback(f=>a(SA(f)),[a]),x=p.useCallback(()=>({search:i,status:o,priority:l}),[i,o,l]);p.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const f=setTimeout(()=>{t&&t(x())},i?s:0);return r.current=f,()=>{r.current&&clearTimeout(r.current)}},[i,o,l,t,x,s]);const g=p.useCallback(()=>{a(AA())},[a]);return{searchTerm:i,statusFilter:o,priorityFilter:l,currentPage:c,setSearchTerm:d,setStatusFilter:m,setPriorityFilter:u,setCurrentPage:h,getFilters:x,resetFilters:g}}function TA({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=Gt(),r=vA({itemsPerPage:10}),n=p.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=kA(),o=p.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter}),l=p.useRef(!1);p.useEffect(()=>{const w=i.currentPage||1;n.current(w,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0}),l.current=!0},[]),p.useEffect(()=>{if(!l.current)return;const w=o.current;if(!(w.searchTerm!==i.searchTerm||w.statusFilter!==i.statusFilter||w.priorityFilter!==i.priorityFilter))return;const C=setTimeout(()=>{i.setCurrentPage(1),n.current(1,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0}),o.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter}},i.searchTerm!==w.searchTerm?500:0);return()=>clearTimeout(C)},[i.searchTerm,i.statusFilter,i.priorityFilter]);const[c,d]=p.useState(null),[m,u]=p.useState(!1),h=p.useCallback(async()=>{if(a!=null&&a.userId)try{u(!0);const w=await xt.getRequestStats(void 0,void 0,void 0,void 0,i.priorityFilter!=="all"?i.priorityFilter:void 0,void 0,a.userId,void 0,void 0,i.searchTerm||void 0,void 0);d({total:w.totalRequests||0,pending:w.openRequests||0,paused:w.pausedRequests||0,approved:w.approvedRequests||0,rejected:w.rejectedRequests||0,draft:w.draftRequests||0,closed:w.closedRequests||0})}catch(w){console.error("Failed to fetch backend stats:",w),d(null)}finally{u(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter]);p.useEffect(()=>{const w=setTimeout(()=>{h()},i.searchTerm?500:0);return()=>clearTimeout(w)},[i.searchTerm,i.priorityFilter,h]);const x=Pp(s),g=r.hasFetchedFromApi?r.requests:x,f=p.useMemo(()=>c?{total:c.total||0,pending:c.pending||0,paused:c.paused||0,approved:c.approved||0,rejected:c.rejected||0,draft:c.draft||0,closed:c.closed||0}:{total:0,pending:0,paused:0,approved:0,rejected:0,draft:0,closed:0},[c]),j=p.useCallback(w=>{w>=1&&w<=r.pagination.totalPages&&(i.setCurrentPage(w),r.fetchMyRequests(w,{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(Rp,{icon:Ee,title:"My Requests",description:"Track and manage all your submitted requests",badge:{value:`${f.total} total`,label:"requests",loading:r.loading||m},testId:"my-requests-header"}),e.jsx(uA,{stats:f,onStatusFilter:w=>{i.setStatusFilter(w)}}),e.jsx(hA,{searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onSearchChange:i.setSearchTerm,onStatusChange:i.setStatusFilter,onPriorityChange:i.setPriorityFilter}),e.jsx(yA,{requests:g,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx($a,{currentPage:i.currentPage||r.pagination.currentPage,totalPages:r.pagination.totalPages,totalRecords:r.pagination.totalRecords,itemsPerPage:r.pagination.itemsPerPage,onPageChange:j,loading:r.loading,itemLabel:"requests",testIdPrefix:"my-requests-pagination"})]})}function Ip({isOrgLevel:t,isAdmin:s,loading:a,exporting:r,onExport:n}){const i=()=>"All Requests",o=()=>t?"View and filter all organization-wide workflow requests":s?"Viewing requests where you are initiator, approver, or participant":"View and filter your workflow requests";return e.jsxs("div",{className:"flex items-start justify-between gap-4","data-testid":"requests-header-container",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Rp,{icon:Ee,title:i(),description:o(),testId:"requests-header"}),e.jsx(se,{variant:"outline",className:t?"bg-blue-50 text-blue-700 border-blue-200":"bg-green-50 text-green-700 border-green-200",children:t?"Organization":"Personal"})]}),e.jsx(R,{onClick:n,disabled:r||a,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-button",children:r?e.jsxs(e.Fragment,{children:[e.jsx(Zt,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function Mp({stats:t,onStatusFilter:s}){const a=r=>{s&&s(r)};return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 sm:gap-4","data-testid":"requests-stats",children:[e.jsx(vs,{label:"Total",value:t.total,icon:Ee,iconColor:"text-blue-600",gradient:"bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200",textColor:"text-blue-700",valueColor:"text-blue-900",testId:"stat-total",onClick:s?()=>a("all"):void 0}),e.jsx(vs,{label:"Pending",value:t.pending,icon:He,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(vs,{label:"Paused",value:t.paused,icon:ha,iconColor:"text-amber-600",gradient:"bg-gradient-to-br from-amber-50 to-amber-100 border-amber-200",textColor:"text-amber-700",valueColor:"text-amber-900",testId:"stat-paused",onClick:s?()=>a("paused"):void 0}),e.jsx(vs,{label:"Approved",value:t.approved,icon:Ce,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(vs,{label:"Rejected",value:t.rejected,icon:yt,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(vs,{label:"Closed",value:t.closed,icon:Bn,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 DA=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Os,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Dt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Dt,iconColor:"text-gray-600"}}},RA=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Ce,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:yt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:He,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ce,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:$n,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ie,iconColor:"text-gray-600"}}},PA=t=>{if(!t)return"";if(typeof document>"u")return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();const s=document.createElement("div");s.innerHTML=t;let a=s.textContent||s.innerText||"";return a=a.replace(/\s+/g," ").trim(),a};function EA({request:t,index:s,onViewRequest:a}){var l;const r=RA(t.status),n=DA(t.priority),i=r.icon,o=n.icon;return e.jsx(Yt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(X,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(J,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(se,{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})]}),(((l=t.pauseInfo)==null?void 0:l.isPaused)||t.isPaused)&&e.jsxs(se,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-300 font-medium text-xs shrink-0","data-testid":"pause-badge",children:[e.jsx(ha,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(se,{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]}),(()=>{const c=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",d=(c==null?void 0:c.toUpperCase())||"";let m="Custom",u="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Claim Management",u="bg-blue-100 !text-blue-700 border-blue-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(se,{variant:"outline",className:`${u} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:m})})(),t.department&&e.jsx(se,{variant:"secondary",className:"bg-purple-100 text-purple-700 text-xs shrink-0","data-testid":"department-badge",children:t.department})]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 line-clamp-2 leading-relaxed","data-testid":"request-description",children:PA(t.description||"")||"No description provided"}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-4 text-xs sm:text-sm text-gray-500",children:[e.jsxs("span",{className:"truncate","data-testid":"request-id-display",children:[e.jsx("span",{className:"font-medium",children:"ID:"})," ",t.displayId||t.id]}),e.jsxs("span",{className:"truncate","data-testid":"submitted-date",children:[e.jsx("span",{className:"font-medium",children:"Submitted:"})," ",Ks(t.submittedDate)]})]})]}),e.jsx(Wt,{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(St,{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(Zs,{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(He,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",Ks(t.submittedDate)]})]})]})]})})})})}function Fp({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(X,{"data-testid":"loading-state",children:e.jsx(J,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(X,{"data-testid":"empty-state",children:e.jsxs(J,{className:"p-12 text-center",children:[e.jsx(Ee,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600",children:a?"Try adjusting your search or filters":"No requests match the current criteria"})]})}):e.jsx("div",{className:"space-y-4","data-testid":"requests-list",children:t.map((n,i)=>e.jsx(EA,{request:n,index:i,onViewRequest:r},n.id))})}const IA={searchTerm:"",statusFilter:"all",priorityFilter:"all",slaComplianceFilter:"all",departmentFilter:"all",initiatorFilter:"all",approverFilter:"all",approverFilterType:"current",dateRange:"all",customStartDate:void 0,customEndDate:void 0,showCustomDatePicker:!1,currentPage:1},_p=tr({name:"requests",initialState:IA,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setSlaComplianceFilter:(t,s)=>{t.slaComplianceFilter=s.payload},setDepartmentFilter:(t,s)=>{t.departmentFilter=s.payload},setInitiatorFilter:(t,s)=>{t.initiatorFilter=s.payload},setApproverFilter:(t,s)=>{t.approverFilter=s.payload},setApproverFilterType:(t,s)=>{t.approverFilterType=s.payload},setDateRange:(t,s)=>{t.dateRange=s.payload},setCustomStartDate:(t,s)=>{t.customStartDate=s.payload},setCustomEndDate:(t,s)=>{t.customEndDate=s.payload},setShowCustomDatePicker:(t,s)=>{t.showCustomDatePicker=s.payload},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.slaComplianceFilter="all",t.departmentFilter="all",t.initiatorFilter="all",t.approverFilter="all",t.approverFilterType="current",t.dateRange="all",t.customStartDate=void 0,t.customEndDate=void 0,t.showCustomDatePicker=!1,t.currentPage=1}}}),{setSearchTerm:MA,setStatusFilter:FA,setPriorityFilter:_A,setSlaComplianceFilter:LA,setDepartmentFilter:OA,setInitiatorFilter:$A,setApproverFilter:BA,setApproverFilterType:UA,setDateRange:sm,setCustomStartDate:Ii,setCustomEndDate:Mi,setShowCustomDatePicker:un,setCurrentPage:VA,clearFilters:zA}=_p.actions;function Lp(){const t=Gr(),{searchTerm:s,statusFilter:a,priorityFilter:r,slaComplianceFilter:n,departmentFilter:i,initiatorFilter:o,approverFilter:l,approverFilterType:c,dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,currentPage:x}=ar(T=>T.requests),g=p.useCallback(T=>t(MA(T)),[t]),f=p.useCallback(T=>t(FA(T)),[t]),j=p.useCallback(T=>t(_A(T)),[t]),w=p.useCallback(T=>t(LA(T)),[t]),b=p.useCallback(T=>t(OA(T)),[t]),C=p.useCallback(T=>t($A(T)),[t]),v=p.useCallback(T=>t(BA(T)),[t]),N=p.useCallback(T=>t(UA(T)),[t]),k=p.useCallback(T=>t(sm(T)),[t]),E=p.useCallback(T=>t(Ii(T)),[t]),P=p.useCallback(T=>t(Mi(T)),[t]),M=p.useCallback(T=>t(un(T)),[t]),y=p.useCallback(T=>t(VA(T)),[t]),A=p.useCallback(()=>({search:s||void 0,status:a!=="all"?a:void 0,priority:r!=="all"?r:void 0,slaCompliance:n!=="all"?n:void 0,department:i!=="all"?i:void 0,initiator:o!=="all"?o:void 0,approver:l!=="all"?l:void 0,approverType:l!=="all"?c:void 0,dateRange:d,startDate:m,endDate:u}),[s,a,r,n,i,o,l,c,d,m,u]),L=p.useCallback(()=>{t(zA())},[t]),K=p.useCallback(T=>{const S=T;t(sm(S)),S!=="custom"?(t(Ii(void 0)),t(Mi(void 0)),t(un(!1))):t(un(!0))},[t]),O=p.useCallback(()=>{m&&u&&(m>u&&(t(Ii(u)),t(Mi(m))),t(un(!1)))},[m,u,t]);return{searchTerm:s,statusFilter:a,priorityFilter:r,slaComplianceFilter:n,departmentFilter:i,initiatorFilter:o,approverFilter:l,approverFilterType:c,dateRange:d,customStartDate:m,customEndDate:u,showCustomDatePicker:h,currentPage:x,hasActiveFilters:!!(s||a!=="all"||r!=="all"||n!=="all"||i!=="all"||o!=="all"||l!=="all"||d!=="all"||m||u),setSearchTerm:g,setStatusFilter:f,setPriorityFilter:j,setSlaComplianceFilter:w,setDepartmentFilter:b,setInitiatorFilter:C,setApproverFilter:v,setApproverFilterType:N,setDateRange:k,setCustomStartDate:E,setCustomEndDate:P,setShowCustomDatePicker:M,setCurrentPage:y,getFilters:A,clearFilters:L,handleDateRangeChange:K,handleApplyCustomDate:O}}function Rn({allUsers:t,filterValue:s,onFilterChange:a}){const[r,n]=p.useState(""),[i,o]=p.useState([]),[l,c]=p.useState(!1),[d,m]=p.useState(null),u=p.useRef(null);p.useEffect(()=>{if(s!=="all"&&t.length>0){const f=t.find(j=>j.userId===s);f&&(m(f),n(f.displayName||f.email))}},[s,t]),p.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const h=p.useCallback(f=>{if(n(f),u.current&&clearTimeout(u.current),!f||f.trim().length<2){o([]),c(!1);return}u.current=setTimeout(()=>{const j=f.toLowerCase().trim(),w=t.filter(b=>{const C=(b.email||"").toLowerCase(),v=(b.displayName||"").toLowerCase();return C.includes(j)||v.includes(j)});o(w.slice(0,10)),c(w.length>0)},300)},[t]),x=p.useCallback(f=>{m(f),a(f.userId),n(f.displayName||f.email),c(!1),o([])},[a]),g=p.useCallback(()=>{m(null),a("all"),n(""),c(!1),o([])},[a]);return{searchQuery:r,searchResults:i,showResults:l,selectedUser:d,handleSearch:h,handleSelect:x,handleClear:g,setShowResults:c}}function HA(t){var d,m,u,h,x,g,f;const s=t.submittedAt||t.submitted_at||t.createdAt||t.created_at,a=(t.priority||"").toString().toLowerCase(),r=(t.status||"").toString().toUpperCase();let n="—",i="—";const 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 j=t.approvals.find(w=>{const b=(w.status||"").toString().toUpperCase();return b==="PENDING"||b==="IN_PROGRESS"});if(j)n=j.approverName||((d=j.approver)==null?void 0:d.name)||((m=j.approver)==null?void 0:m.displayName)||j.approverEmail||((u=j.approver)==null?void 0:u.email)||"—";else{const b=[...t.approvals].sort((C,v)=>{const N=C.levelNumber||C.level_number||0;return(v.levelNumber||v.level_number||0)-N})[0];b&&(n=b.approverName||((h=b.approver)==null?void 0:h.name)||((x=b.approver)==null?void 0:x.displayName)||b.approverEmail||((g=b.approver)==null?void 0:g.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 j=t.approvals.find(w=>{const b=(w.status||"").toString().toUpperCase();return b==="PENDING"||b==="IN_PROGRESS"});if(j){const w=j.levelNumber||j.level_number||0,b=c||t.approvals.length;i=`${w} of ${b}`}else c&&(i=`${c} of ${c}`)}else t.currentStep&&t.totalSteps&&(i=`${t.currentStep} of ${t.totalSteps}`);return{id:t.requestNumber||t.request_number||t.requestId||t.id||t.request_id,requestId:t.requestId||t.id||t.request_id,displayId:t.requestNumber||t.request_number||t.id,title:t.title,description:t.description,status:r.toLowerCase().replace("_","-"),priority:a,department:t.department||((f=t.initiator)==null?void 0:f.department),submittedDate:t.submittedAt||(t.createdAt?new Date(t.createdAt).toISOString().split("T")[0]:void 0),createdAt:s,currentApprover:n,approverLevel:i,templateType:t.templateType||t.template_type,workflowType:t.workflowType||t.workflow_type,templateName:t.templateName||t.template_name}}function Op(t){return Array.isArray(t)?t.map(HA):[]}function WA(t,s,a,r,n,i){if(t.length>0){const o=t.length,l=t.filter(x=>{const g=(x.status||"").toString().toUpperCase();return g==="PENDING"||g==="IN_PROGRESS"}).length,c=t.filter(x=>(x.status||"").toString().toUpperCase()==="APPROVED").length,d=t.filter(x=>(x.status||"").toString().toUpperCase()==="REJECTED").length,m=t.filter(x=>(x.status||"").toString().toUpperCase()==="DRAFT").length,u=t.filter(x=>(x.status||"").toString().toUpperCase()==="CLOSED").length,h=t.filter(x=>(x.status||"").toString().toUpperCase()==="PAUSED").length;return{total:o,pending:l,paused:h,approved:c,rejected:d,draft:m,closed:u}}else return s&&a?{total:a.total,pending:a.pending,paused:a.paused||0,approved:a.approved,rejected:a.rejected,draft:a.draft,closed:a.closed}:{total:n||i.length,pending:i.filter(l=>l.status==="pending"||l.status==="in-progress").length,paused:i.filter(l=>l.status==="paused").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 $p={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Pn,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})($p);var GA=$p.exports;const Bp=En(GA);var Up={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Pn,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(Up);var KA=Up.exports;const Vp=En(KA);kt.extend(Vp);kt.extend(Bp);function YA(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=>{var o;const n=(r.status||"").toString().toUpperCase(),i=((o=r.pauseInfo)==null?void 0:o.isPaused)||r.isPaused||!1;return(n==="PENDING"||n==="IN_PROGRESS")&&!i});else if(s.status.toLowerCase()==="paused")a=a.filter(r=>{var o;const n=(r.status||"").toString().toUpperCase(),i=((o=r.pauseInfo)==null?void 0:o.isPaused)||r.isPaused||!1;return n==="PAUSED"||i});else{const r=s.status.toUpperCase().replace("-","_");a=a.filter(n=>{var l;const i=(n.status||"").toString().toUpperCase(),o=((l=n.pauseInfo)==null?void 0:l.isPaused)||n.isPaused||!1;return r==="IN_PROGRESS"||r==="IN-PROGRESS"?i==="IN_PROGRESS"&&!o:i===r&&!o})}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,d,m,u;return(((o=n.currentApprover)==null?void 0:o.userId)||((l=n.currentApprover)==null?void 0:l.user_id)||((d=(c=n.approvals)==null?void 0:c.find(h=>{const x=(h.status||"").toString().toUpperCase();return x==="IN_PROGRESS"||x==="PENDING"}))==null?void 0:d.approverId)||((u=(m=n.approvals)==null?void 0:m.find(h=>{const x=(h.status||"").toString().toUpperCase();return x==="IN_PROGRESS"||x==="PENDING"}))==null?void 0:u.approver_id)||n.currentApproverId||n.current_approver_id)===s.approver}):a=a.filter(n=>{var o,l;const i=[];return(o=n.currentApprover)!=null&&o.userId&&i.push(n.currentApprover.userId),(l=n.currentApprover)!=null&&l.user_id&&i.push(n.currentApprover.user_id),Array.isArray(n.approvals)&&n.approvals.forEach(c=>{c.approverId&&i.push(c.approverId),c.approver_id&&i.push(c.approver_id)}),i.includes(s.approver||"")})),s.slaCompliance&&s.slaCompliance!=="all"&&(a=a.filter(r=>{var c,d,m,u,h,x,g,f,j,w,b,C;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const v=(r.status||"").toString().toUpperCase();if(!(v==="APPROVED"||v==="REJECTED"||v==="CLOSED"))return!1;const k=((c=r.currentLevelSLA)==null?void 0:c.status)||((m=(d=r.currentApprover)==null?void 0:d.sla)==null?void 0:m.status)||((u=r.sla)==null?void 0:u.status)||((x=(h=r.summary)==null?void 0:h.sla)==null?void 0:x.status);return k?k!=="breached"&&k.toLowerCase()!=="breached":!0}const i=((g=r.currentLevelSLA)==null?void 0:g.status)||((j=(f=r.currentApprover)==null?void 0:f.sla)==null?void 0:j.status)||((w=r.sla)==null?void 0:w.status)||((C=(b=r.summary)==null?void 0:b.sla)==null?void 0:C.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=kt(s.startDate).startOf("day").toDate(),n=kt(s.endDate).endOf("day").toDate();else{const i=kt();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 m=i.createdAt||i.created_at||i.created_date;if(!m)return!1;const u=kt(m).startOf("day").toDate(),h=kt(r).startOf("day").toDate(),x=kt(n).endOf("day").toDate();return u>=h&&u<=x}const l=kt(o).startOf("day").toDate(),c=kt(r).startOf("day").toDate(),d=kt(n).endOf("day").toDate();return l>=c&&l<=d}))}return a}kt.extend(Bp);kt.extend(Vp);function ZA(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return Ne(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function zp(t,s){const a=YA(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var b,C,v,N,k;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),u=((b=c.initiator)==null?void 0:b.displayName)||((C=c.initiator)==null?void 0:C.email)||c.initiatorName||"N/A",h=c.department||((v=c.initiator)==null?void 0:v.department)||"N/A",x=((N=c.currentApprover)==null?void 0:N.displayName)||((k=c.currentApprover)==null?void 0:k.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",f=ZA(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),j=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),w=[c.requestNumber||c.request_number||"",`"${(c.title||"").replace(/"/g,'""')}"`,d,m,`"${u.replace(/"/g,'""')}"`,`"${h.replace(/"/g,'""')}"`,`"${x.replace(/"/g,'""')}"`,g,f,`"${j}"`];r.push(w.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 XA({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 d=await hs.listWorkflows({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const u=m.filter(g=>(g.status||"").toString().toUpperCase()!=="DRAFT"),h=(d==null?void 0:d.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 d=await hs.listParticipantRequests({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const u=m.filter(x=>(x.status||"").toString().toUpperCase()!=="DRAFT"),h=(d==null?void 0:d.pagination)||{page:t,limit:s,total:u.length,totalPages:1};return{data:u,allData:[],filteredData:u,pagination:h}}}async function JA(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const o=t?await hs.listWorkflows({page:r,limit:100}):await hs.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(d=>(d.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 QA({onViewRequest:t}){const{user:s}=Gt(),a=ar(B=>B.dashboard.viewAsUser),r=p.useMemo(()=>Un(s),[s]),n=p.useMemo(()=>r&&!a,[r,a]),i=Lp(),[o,l]=p.useState([]),[c,d]=p.useState(!1),[m,u]=p.useState(!1),[h,x]=p.useState(null),[g,f]=p.useState([]),[j,w]=p.useState(!1),[b,C]=p.useState([]),[v,N]=p.useState(1),[k,E]=p.useState(0),[P]=p.useState(10),M=Rn({allUsers:b,filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter}),y=Rn({allUsers:b,filterValue:i.approverFilter,onFilterChange:i.setApproverFilter}),A=p.useCallback(async(B,re,ae,V)=>{try{const Y=V==null?void 0:V.slaCompliance;if(Y&&Y!=="all"&&Y!=="breached"&&Y!=="compliant"){const U={};V!=null&&V.search&&(U.search=V.search),V!=null&&V.priority&&V.priority!=="all"&&(U.priority=V.priority),V!=null&&V.department&&V.department!=="all"&&(U.department=V.department),V!=null&&V.initiator&&V.initiator!=="all"&&(U.initiator=V.initiator),V!=null&&V.approver&&V.approver!=="all"&&(U.approver=V.approver,U.approverType=V.approverType||"current"),U.slaCompliance=Y,B&&(U.dateRange=B),re&&(U.startDate=re.toISOString()),ae&&(U.endDate=ae.toISOString());const ee=n?await hs.listWorkflows({page:1,limit:1e3,...U}):await hs.listParticipantRequests({page:1,limit:1e3,...U}),ie=Array.isArray(ee==null?void 0:ee.data)?ee.data:[],de=ie.length,Ae=ie.filter(Ge=>{const Oe=(Ge.status||"").toString().toUpperCase();return Oe==="PENDING"||Oe==="IN_PROGRESS"}).length,We=ie.filter(Ge=>(Ge.status||"").toString().toUpperCase()==="APPROVED").length,Se=ie.filter(Ge=>(Ge.status||"").toString().toUpperCase()==="REJECTED").length,Ye=ie.filter(Ge=>(Ge.status||"").toString().toUpperCase()==="CLOSED").length;x({total:de,pending:Ae,paused:0,approved:We,rejected:Se,draft:0,closed:Ye})}else{const U=await xt.getRequestStats(B,re?re.toISOString():void 0,ae?ae.toISOString():void 0,void 0,V==null?void 0:V.priority,V==null?void 0:V.department,V==null?void 0:V.initiator,V==null?void 0:V.approver,V==null?void 0:V.approverType,V==null?void 0:V.search,V==null?void 0:V.slaCompliance,!n);x({total:U.totalRequests||0,pending:U.openRequests||0,paused:U.pausedRequests||0,approved:U.approvedRequests||0,rejected:U.rejectedRequests||0,draft:U.draftRequests||0,closed:U.closedRequests||0})}}catch(Y){console.error("Failed to fetch backend stats:",Y)}finally{}},[n]),L=p.useCallback(async()=>{try{w(!0);const B=await xt.getDepartments();f(B)}catch{}finally{w(!1)}},[]),K=p.useCallback(async()=>{try{const re=(await js.getAllUsers()).map(ae=>({userId:ae.userId,email:ae.email,displayName:ae.displayName||ae.email}));C(re)}catch(B){console.error("Failed to fetch users:",B)}},[]),O=p.useRef(i),$=p.useRef(A);p.useEffect(()=>{O.current=i,$.current=A},[i,A]);const T=p.useCallback(async(B=1)=>{try{B===1&&(d(!0),l([]));const re=O.current.getFilters(),ae=await XA({page:B,itemsPerPage:P,filters:re,isOrgLevel:n});l(ae.data),i.setCurrentPage(ae.pagination.page),N(ae.pagination.totalPages),E(ae.pagination.total)}catch{l([])}finally{d(!1)}},[P,n]),S=p.useCallback(async()=>{try{u(!0);const B=await JA(n);await zp(B,i.getFilters())}catch(B){console.error("Failed to export requests:",B),alert("Failed to export requests. Please try again.")}finally{u(!1)}},[n,i]);p.useEffect(()=>{L(),K()},[L,K]),p.useEffect(()=>{const B=setTimeout(()=>{const re={priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,department:i.departmentFilter!=="all"?i.departmentFilter:void 0,initiator:i.initiatorFilter!=="all"?i.initiatorFilter:void 0,approver:i.approverFilter!=="all"?i.approverFilter:void 0,approverType:i.approverFilter!=="all"?i.approverFilterType:void 0,search:i.searchTerm||void 0,slaCompliance:i.slaComplianceFilter!=="all"?i.slaComplianceFilter:void 0},ae=i.dateRange||"all";$.current(ae,i.customStartDate,i.customEndDate,re)},i.searchTerm?500:0);return()=>clearTimeout(B)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const D=p.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,slaComplianceFilter:i.slaComplianceFilter,departmentFilter:i.departmentFilter,initiatorFilter:i.initiatorFilter,approverFilter:i.approverFilter,approverFilterType:i.approverFilterType,dateRange:i.dateRange,customStartDate:i.customStartDate,customEndDate:i.customEndDate,isOrgLevel:n}),I=p.useRef(!1);p.useEffect(()=>{const B=i.currentPage||1;T(B),I.current=!0},[]),p.useEffect(()=>{if(!I.current)return;const B=D.current;if(!(B.searchTerm!==i.searchTerm||B.statusFilter!==i.statusFilter||B.priorityFilter!==i.priorityFilter||B.slaComplianceFilter!==i.slaComplianceFilter||B.departmentFilter!==i.departmentFilter||B.initiatorFilter!==i.initiatorFilter||B.approverFilter!==i.approverFilter||B.approverFilterType!==i.approverFilterType||B.dateRange!==i.dateRange||B.customStartDate!==i.customStartDate||B.customEndDate!==i.customEndDate||B.isOrgLevel!==n))return;const ae=setTimeout(()=>{i.setCurrentPage(1),T(1),D.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,slaComplianceFilter:i.slaComplianceFilter,departmentFilter:i.departmentFilter,initiatorFilter:i.initiatorFilter,approverFilter:i.approverFilter,approverFilterType:i.approverFilterType,dateRange:i.dateRange,customStartDate:i.customStartDate,customEndDate:i.customEndDate,isOrgLevel:n}},i.searchTerm!==B.searchTerm?500:0);return()=>clearTimeout(ae)},[n,i.searchTerm,i.statusFilter,i.priorityFilter,i.slaComplianceFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.dateRange,i.customStartDate,i.customEndDate]);const _=p.useCallback(B=>{B>=1&&B<=v&&(i.setCurrentPage(B),T(B))},[v,T,i]),F=p.useMemo(()=>Op(o),[o]),G=p.useMemo(()=>h?{total:h.total||0,pending:h.pending||0,paused:h.paused||0,approved:h.approved||0,rejected:h.rejected||0,draft:h.draft||0,closed:h.closed||0}:WA([],n,h,!1,k,F),[n,h,k,F]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(Ip,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:S}),e.jsx(Mp,{stats:G,onStatusFilter:B=>{i.setStatusFilter(B)}}),e.jsx(X,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(J,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zr,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(se,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),i.hasActiveFilters&&e.jsxs(R,{variant:"ghost",size:"sm",onClick:i.clearFilters,className:"gap-2",children:[e.jsx(Zt,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(It,{}),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(ws,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(we,{placeholder:"Search requests...",value:i.searchTerm,onChange:B=>i.setSearchTerm(B.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Be,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(Ve,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ue,{placeholder:"All Status"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Status"}),e.jsx(W,{value:"pending",children:"Pending"}),e.jsx(W,{value:"paused",children:"Paused"}),e.jsx(W,{value:"approved",children:"Approved"}),e.jsx(W,{value:"rejected",children:"Rejected"}),e.jsx(W,{value:"closed",children:"Closed"})]})]}),e.jsxs(Be,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(Ve,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ue,{placeholder:"All Priority"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Priority"}),e.jsx(W,{value:"express",children:"Express"}),e.jsx(W,{value:"standard",children:"Standard"})]})]}),e.jsxs(Be,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:j||g.length===0,children:[e.jsx(Ve,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ue,{placeholder:j?"Loading...":"All Departments"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Departments"}),g.map(B=>e.jsx(W,{value:B,children:B},B))]})]}),e.jsxs(Be,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(Ve,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ue,{placeholder:"All SLA Status"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All SLA Status"}),e.jsx(W,{value:"compliant",children:"Compliant"}),e.jsx(W,{value:"on-track",children:"On Track"}),e.jsx(W,{value:"approaching",children:"Approaching"}),e.jsx(W,{value:"critical",children:"Critical"}),e.jsx(W,{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(Q,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:M.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:M.selectedUser.displayName||M.selectedUser.email}),e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:M.handleClear,children:e.jsx(ut,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(we,{placeholder:"Search initiator...",value:M.searchQuery,onChange:B=>M.handleSearch(B.target.value),onFocus:()=>{M.searchResults.length>0&&M.setShowResults(!0)},onBlur:()=>setTimeout(()=>M.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),M.showResults&&M.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:M.searchResults.map(B=>e.jsx("button",{type:"button",onClick:()=>M.handleSelect(B),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:B.displayName||B.email}),B.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:B.email})]})},B.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(Q,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(Be,{value:i.approverFilterType,onValueChange:B=>i.setApproverFilterType(B),children:[e.jsx(Ve,{className:"h-7 w-32 text-xs",children:e.jsx(Ue,{})}),e.jsxs(ze,{children:[e.jsx(W,{value:"current",children:"Current Only"}),e.jsx(W,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:y.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:y.selectedUser.displayName||y.selectedUser.email}),e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:y.handleClear,children:e.jsx(ut,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(we,{placeholder:"Search approver...",value:y.searchQuery,onChange:B=>y.handleSearch(B.target.value),onFocus:()=>{y.searchResults.length>0&&y.setShowResults(!0)},onBlur:()=>setTimeout(()=>y.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),y.showResults&&y.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:y.searchResults.map(B=>e.jsx("button",{type:"button",onClick:()=>y.handleSelect(B),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:B.displayName||B.email}),B.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:B.email})]})},B.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Be,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(Ve,{className:"w-[160px] h-10",children:e.jsx(Ue,{placeholder:"Date Range"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Time"}),e.jsx(W,{value:"today",children:"Today"}),e.jsx(W,{value:"week",children:"This Week"}),e.jsx(W,{value:"month",children:"This Month"}),e.jsx(W,{value:"last7days",children:"Last 7 Days"}),e.jsx(W,{value:"last30days",children:"Last 30 Days"}),e.jsx(W,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs($s,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(Bs,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(qe,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${Ne(i.customStartDate,"MMM d, yyyy")} - ${Ne(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Us,{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(Q,{htmlFor:"start-date",children:"Start Date"}),e.jsx(we,{id:"start-date",type:"date",value:i.customStartDate?Ne(i.customStartDate,"yyyy-MM-dd"):"",onChange:B=>{const re=B.target.value?new Date(B.target.value):void 0;re?(i.setCustomStartDate(re),i.customEndDate&&re>i.customEndDate&&i.setCustomEndDate(re)):i.setCustomStartDate(void 0)},max:Ne(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"end-date",children:"End Date"}),e.jsx(we,{id:"end-date",type:"date",value:i.customEndDate?Ne(i.customEndDate,"yyyy-MM-dd"):"",onChange:B=>{const re=B.target.value?new Date(B.target.value):void 0;re?(i.setCustomEndDate(re),i.customStartDate&&re{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx(Fp,{requests:F,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx($a,{currentPage:i.currentPage||1,totalPages:v,totalRecords:k,itemsPerPage:P,onPageChange:_,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function qA({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 hs.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:{page:l.page,limit:l.limit||s,total:l.total||o.length,totalPages:l.totalPages||1}}}const am=100;async function ek(t){const s=[];let a=!0,r=1;const n=100,i={};for(t!=null&&t.search&&(i.search=t.search),t!=null&&t.status&&t.status!=="all"&&(i.status=t.status),t!=null&&t.priority&&t.priority!=="all"&&(i.priority=t.priority),t!=null&&t.department&&t.department!=="all"&&(i.department=t.department),t!=null&&t.initiator&&t.initiator!=="all"&&(i.initiator=t.initiator),t!=null&&t.approver&&t.approver!=="all"&&(i.approver=t.approver,i.approverType=t.approverType||"current"),t!=null&&t.slaCompliance&&t.slaCompliance!=="all"&&(i.slaCompliance=t.slaCompliance),t!=null&&t.dateRange&&(i.dateRange=t.dateRange),t!=null&&t.startDate&&(i.startDate=t.startDate instanceof Date?t.startDate.toISOString():t.startDate),t!=null&&t.endDate&&(i.endDate=t.endDate instanceof Date?t.endDate.toISOString():t.endDate);a&&r<=n;){const o=await hs.listParticipantRequests({page:r,limit:am,...i});let l=[];if(Array.isArray(o==null?void 0:o.data)?l=o.data:Array.isArray(o)&&(l=o),l.length===0)a=!1;else{const c=l.filter(d=>(d.status||"").toString().toUpperCase()!=="DRAFT");s.push(...c),r++,o!=null&&o.pagination?a=r<=o.pagination.totalPages:a=l.length===am}}return s}function tk({onViewRequest:t}){const s=Lp(),[a,r]=p.useState([]),[n,i]=p.useState(!1),[o,l]=p.useState(!1),[c,d]=p.useState(null),[m,u]=p.useState([]),[h,x]=p.useState(!1),[g,f]=p.useState([]),[j,w]=p.useState(1),[b,C]=p.useState(0),[v]=p.useState(10),N=Rn({allUsers:g,filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter}),k=Rn({allUsers:g,filterValue:s.approverFilter,onFilterChange:s.setApproverFilter}),E=p.useCallback(async(I,_,F,G)=>{try{const B=await xt.getRequestStats(I,_?_.toISOString():void 0,F?F.toISOString():void 0,void 0,G==null?void 0:G.priority,G==null?void 0:G.department,G==null?void 0:G.initiator,G==null?void 0:G.approver,G==null?void 0:G.approverType,G==null?void 0:G.search,G==null?void 0:G.slaCompliance,!0);d({total:B.totalRequests||0,pending:B.openRequests||0,paused:B.pausedRequests||0,approved:B.approvedRequests||0,rejected:B.rejectedRequests||0,draft:B.draftRequests||0,closed:B.closedRequests||0})}catch(B){console.error("Failed to fetch backend stats:",B)}},[]),P=p.useCallback(async()=>{try{x(!0);const I=await xt.getDepartments();u(I)}catch{}finally{x(!1)}},[]),M=p.useCallback(async()=>{try{const _=(await js.getAllUsers()).map(F=>({userId:F.userId,email:F.email,displayName:F.displayName||F.email}));f(_)}catch(I){console.error("Failed to fetch users:",I)}},[]),y=p.useRef(s),A=p.useRef(E);p.useEffect(()=>{y.current=s,A.current=E},[s,E]);const L=p.useCallback(async(I=1)=>{try{I===1&&(i(!0),r([]));const _=y.current.getFilters(),F=await qA({page:I,itemsPerPage:v,filters:_});r(F.data),s.setCurrentPage(F.pagination.page),w(F.pagination.totalPages),C(F.pagination.total)}catch{r([])}finally{i(!1)}},[v]),K=p.useCallback(async()=>{try{l(!0);const I=await ek(s.getFilters());await zp(I,s.getFilters())}catch(I){console.error("Failed to export requests:",I),alert("Failed to export requests. Please try again.")}finally{l(!1)}},[s]);p.useEffect(()=>{P(),M()},[P,M]),p.useEffect(()=>{const I=setTimeout(()=>{const _={priority:s.priorityFilter!=="all"?s.priorityFilter:void 0,department:s.departmentFilter!=="all"?s.departmentFilter:void 0,initiator:s.initiatorFilter!=="all"?s.initiatorFilter:void 0,approver:s.approverFilter!=="all"?s.approverFilter:void 0,approverType:s.approverFilter!=="all"?s.approverFilterType:void 0,search:s.searchTerm||void 0,slaCompliance:s.slaComplianceFilter!=="all"?s.slaComplianceFilter:void 0},F=s.dateRange||"month";A.current(F,s.customStartDate,s.customEndDate,_)},s.searchTerm?500:0);return()=>clearTimeout(I)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const O=p.useRef({searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}),$=p.useRef(!1);p.useEffect(()=>{const I=s.currentPage||1;L(I),$.current=!0},[]),p.useEffect(()=>{if(!$.current)return;const I=O.current;if(!(I.searchTerm!==s.searchTerm||I.statusFilter!==s.statusFilter||I.priorityFilter!==s.priorityFilter||I.slaComplianceFilter!==s.slaComplianceFilter||I.departmentFilter!==s.departmentFilter||I.initiatorFilter!==s.initiatorFilter||I.approverFilter!==s.approverFilter||I.approverFilterType!==s.approverFilterType||I.dateRange!==s.dateRange||I.customStartDate!==s.customStartDate||I.customEndDate!==s.customEndDate))return;const F=setTimeout(()=>{s.setCurrentPage(1),L(1),O.current={searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}},s.searchTerm!==I.searchTerm?500:0);return()=>clearTimeout(F)},[s.searchTerm,s.statusFilter,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const T=p.useCallback(I=>{I>=1&&I<=j&&(s.setCurrentPage(I),L(I))},[j,L,s]),S=p.useMemo(()=>Op(a),[a]),D=p.useMemo(()=>{if(c)return{total:c.total||0,pending:c.pending||0,paused:c.paused||0,approved:c.approved||0,rejected:c.rejected||0,draft:c.draft||0,closed:c.closed||0};const I=S.filter(re=>{const ae=(re.status||"").toString().toLowerCase();return ae==="pending"||ae==="in-progress"}).length,_=S.filter(re=>(re.status||"").toString().toLowerCase()==="paused").length,F=S.filter(re=>(re.status||"").toString().toLowerCase()==="approved").length,G=S.filter(re=>(re.status||"").toString().toLowerCase()==="rejected").length,B=S.filter(re=>(re.status||"").toString().toLowerCase()==="closed").length;return{total:b>0?b:S.length,pending:I,paused:_,approved:F,rejected:G,draft:0,closed:B}},[c,b,S]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"user-all-requests-page",children:[e.jsx(Ip,{isOrgLevel:!1,isAdmin:!1,loading:n,exporting:o,onExport:K}),e.jsx(Mp,{stats:D,onStatusFilter:I=>{s.setStatusFilter(I)}}),e.jsx(X,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(J,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zr,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),s.hasActiveFilters&&e.jsx(se,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),s.hasActiveFilters&&e.jsxs(R,{variant:"ghost",size:"sm",onClick:s.clearFilters,className:"gap-2",children:[e.jsx(Zt,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(It,{}),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(ws,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(we,{placeholder:"Search requests...",value:s.searchTerm,onChange:I=>s.setSearchTerm(I.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(Be,{value:s.statusFilter,onValueChange:s.setStatusFilter,children:[e.jsx(Ve,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ue,{placeholder:"All Status"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Status"}),e.jsx(W,{value:"pending",children:"Pending"}),e.jsx(W,{value:"paused",children:"Paused"}),e.jsx(W,{value:"approved",children:"Approved"}),e.jsx(W,{value:"rejected",children:"Rejected"}),e.jsx(W,{value:"closed",children:"Closed"})]})]}),e.jsxs(Be,{value:s.priorityFilter,onValueChange:s.setPriorityFilter,children:[e.jsx(Ve,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ue,{placeholder:"All Priority"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Priority"}),e.jsx(W,{value:"express",children:"Express"}),e.jsx(W,{value:"standard",children:"Standard"})]})]}),e.jsxs(Be,{value:s.departmentFilter,onValueChange:s.setDepartmentFilter,disabled:h||m.length===0,children:[e.jsx(Ve,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ue,{placeholder:h?"Loading...":"All Departments"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Departments"}),m.map(I=>e.jsx(W,{value:I,children:I},I))]})]}),e.jsxs(Be,{value:s.slaComplianceFilter,onValueChange:s.setSlaComplianceFilter,children:[e.jsx(Ve,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ue,{placeholder:"All SLA Status"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All SLA Status"}),e.jsx(W,{value:"compliant",children:"Compliant"}),e.jsx(W,{value:"on-track",children:"On Track"}),e.jsx(W,{value:"approaching",children:"Approaching"}),e.jsx(W,{value:"critical",children:"Critical"}),e.jsx(W,{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(Q,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:N.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:N.selectedUser.displayName||N.selectedUser.email}),e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:N.handleClear,children:e.jsx(ut,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(we,{placeholder:"Search initiator...",value:N.searchQuery,onChange:I=>N.handleSearch(I.target.value),onFocus:()=>{N.searchResults.length>0&&N.setShowResults(!0)},onBlur:()=>setTimeout(()=>N.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),N.showResults&&N.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:N.searchResults.map(I=>e.jsx("button",{type:"button",onClick:()=>N.handleSelect(I),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:I.displayName||I.email}),I.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:I.email})]})},I.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(Q,{className:"text-sm font-medium text-gray-700",children:"Approver"}),s.approverFilter!=="all"&&e.jsxs(Be,{value:s.approverFilterType,onValueChange:I=>s.setApproverFilterType(I),children:[e.jsx(Ve,{className:"h-7 w-32 text-xs",children:e.jsx(Ue,{})}),e.jsxs(ze,{children:[e.jsx(W,{value:"current",children:"Current Only"}),e.jsx(W,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:k.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:k.selectedUser.displayName||k.selectedUser.email}),e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:k.handleClear,children:e.jsx(ut,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(we,{placeholder:"Search approver...",value:k.searchQuery,onChange:I=>k.handleSearch(I.target.value),onFocus:()=>{k.searchResults.length>0&&k.setShowResults(!0)},onBlur:()=>setTimeout(()=>k.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),k.showResults&&k.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:k.searchResults.map(I=>e.jsx("button",{type:"button",onClick:()=>k.handleSelect(I),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:I.displayName||I.email}),I.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:I.email})]})},I.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Be,{value:s.dateRange,onValueChange:s.handleDateRangeChange,children:[e.jsx(Ve,{className:"w-[160px] h-10",children:e.jsx(Ue,{placeholder:"Date Range"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Time"}),e.jsx(W,{value:"today",children:"Today"}),e.jsx(W,{value:"week",children:"This Week"}),e.jsx(W,{value:"month",children:"This Month"}),e.jsx(W,{value:"last7days",children:"Last 7 Days"}),e.jsx(W,{value:"last30days",children:"Last 30 Days"}),e.jsx(W,{value:"custom",children:"Custom Range"})]})]}),s.dateRange==="custom"&&e.jsxs($s,{open:s.showCustomDatePicker,onOpenChange:s.setShowCustomDatePicker,children:[e.jsx(Bs,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(qe,{className:"w-4 h-4"}),s.customStartDate&&s.customEndDate?`${Ne(s.customStartDate,"MMM d, yyyy")} - ${Ne(s.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Us,{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(Q,{htmlFor:"start-date",children:"Start Date"}),e.jsx(we,{id:"start-date",type:"date",value:s.customStartDate?Ne(s.customStartDate,"yyyy-MM-dd"):"",onChange:I=>{const _=I.target.value?new Date(I.target.value):void 0;_?(s.setCustomStartDate(_),s.customEndDate&&_>s.customEndDate&&s.setCustomEndDate(_)):s.setCustomStartDate(void 0)},max:Ne(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"end-date",children:"End Date"}),e.jsx(we,{id:"end-date",type:"date",value:s.customEndDate?Ne(s.customEndDate,"yyyy-MM-dd"):"",onChange:I=>{const _=I.target.value?new Date(I.target.value):void 0;_?(s.setCustomEndDate(_),s.customStartDate&&_{s.setShowCustomDatePicker(!1),s.setCustomStartDate(void 0),s.setCustomEndDate(void 0),s.setDateRange("month")},children:"Cancel"})]})]})})]})]})]})})}),e.jsx(Fp,{requests:S,loading:n,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx($a,{currentPage:s.currentPage||1,totalPages:j,totalRecords:b,itemsPerPage:v,onPageChange:T,loading:n,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function sk(){const t=ya();return e.jsx("div",{className:"flex-1 p-3 lg:p-6 overflow-auto min-w-0","data-testid":"approver-performance-empty",children:e.jsx("div",{className:"max-w-7xl mx-auto p-4",children:e.jsx(X,{children:e.jsxs(J,{className:"p-8 text-center",children:[e.jsx(Ie,{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(R,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(Rs,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function ak({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(Pt,{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(R,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx(Zt,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function rk({approverStats:t}){const s=(t==null?void 0:t.tatCompliancePercent)??0;return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4","data-testid":"approver-stats-cards",children:[e.jsxs(X,{children:[e.jsx(le,{className:"pb-3",children:e.jsx(ce,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(J,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[s,"%"]}),e.jsx("div",{className:`p-2 rounded-lg ${s>=95?"bg-green-100":s>=90?"bg-blue-100":s>=85?"bg-orange-100":"bg-red-100"}`,children:e.jsx(Dt,{className:`w-5 h-5 ${s>=95?"text-green-600":s>=90?"text-blue-600":s>=85?"text-orange-600":"text-red-600"}`})})]}),e.jsx(Gs,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(X,{children:[e.jsx(le,{className:"pb-3",children:e.jsx(ce,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(J,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.totalApproved}),e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Ce,{className:"w-5 h-5 text-blue-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Requests handled"})]})]}),e.jsxs(X,{children:[e.jsx(le,{className:"pb-3",children:e.jsx(ce,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(J,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[t.avgResponseHours.toFixed(1),"h"]}),e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(To,{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(X,{children:[e.jsx(le,{className:"pb-3",children:e.jsx(ce,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(J,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.pendingCount}),e.jsx("div",{className:"p-2 bg-orange-100 rounded-lg",children:e.jsx(He,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function nk({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(X,{"data-testid":"approver-actions-stats",children:[e.jsxs(le,{children:[e.jsx(ce,{children:"Approver's Actions"}),e.jsxs(je,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?Ty(a,r,n,""):"(all time)"]})]}),e.jsxs(J,{children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2",children:[e.jsx(Pt,{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(Ce,{className:"w-5 h-5 text-green-600"}),e.jsx("span",{className:"text-xs text-green-600 font-medium",children:s&&s.approvedCount+s.rejectedCount>0?`${Math.round(s.approvedCount/(s.approvedCount+s.rejectedCount)*100)}%`:"0%"})]}),e.jsx("div",{className:"text-2xl font-bold text-green-700",children:(s==null?void 0:s.approvedCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Approved by Approver"})]}),e.jsxs("div",{className:"p-4 bg-red-50 rounded-lg border border-red-200",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(yt,{className:"w-5 h-5 text-red-600"}),e.jsx("span",{className:"text-xs text-red-600 font-medium",children:s&&s.approvedCount+s.rejectedCount>0?`${Math.round(s.rejectedCount/(s.approvedCount+s.rejectedCount)*100)}%`:"0%"})]}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:(s==null?void 0:s.rejectedCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Rejected by Approver"})]}),e.jsxs("div",{className:"p-4 bg-yellow-50 rounded-lg border border-yellow-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(He,{className:"w-5 h-5 text-yellow-600"})}),e.jsx("div",{className:"text-2xl font-bold text-yellow-700",children:(s==null?void 0:s.pendingCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Pending Actions"})]}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-lg border border-gray-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(Bn,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"text-2xl font-bold text-gray-700",children:(s==null?void 0:s.closedCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Closed Requests"})]}),e.jsxs("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(Ee,{className:"w-5 h-5 text-blue-600"})}),e.jsx("div",{className:"text-2xl font-bold text-blue-700",children:(s==null?void 0:s.totalApproved)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Total Requests"})]})]})]}),e.jsxs("div",{className:"mb-6 pt-4 border-t",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2",children:[e.jsx(Dt,{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(Zg,{className:"w-5 h-5 text-green-600"}),e.jsx("span",{className:"text-xs text-green-600 font-medium",children:(s==null?void 0:s.tatCompliancePercent)!==void 0?`${s.tatCompliancePercent}%`:"N/A"})]}),e.jsx("div",{className:"text-2xl font-bold text-green-700",children:(s==null?void 0:s.withinTatCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"TAT Compliant"})]}),e.jsxs("div",{className:"p-4 bg-red-50 rounded-lg border border-red-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(Ie,{className:"w-5 h-5 text-red-600"})}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:(s==null?void 0:s.breachedCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"TAT Breached"})]}),e.jsxs("div",{className:"p-4 bg-purple-50 rounded-lg border border-purple-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(Om,{className:"w-5 h-5 text-purple-600"})}),e.jsx("div",{className:"text-2xl font-bold text-purple-700",children:s?s.approvedCount+s.rejectedCount:0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Completed Actions"})]})]})]})]})]})}function ik({searchTerm:t,statusFilter:s,priorityFilter:a,slaComplianceFilter:r,dateRange:n,customStartDate:i,customEndDate:o,showCustomDatePicker:l,tempCustomStartDate:c,tempCustomEndDate:d,onSearchChange:m,onStatusChange:u,onPriorityChange:h,onSlaComplianceChange:x,onDateRangeChange:g,onShowCustomDatePickerChange:f,onTempStartDateChange:j,onTempEndDateChange:w,onApplyCustomDate:b,onClearFilters:C}){return e.jsxs(X,{"data-testid":"approver-performance-filters",children:[e.jsx(le,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{children:"Filters"}),e.jsx(R,{variant:"ghost",size:"sm",onClick:C,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(J,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ws,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(we,{placeholder:"Search requests...",value:t,onChange:v=>m(v.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(Be,{value:s,onValueChange:u,children:[e.jsx(Ve,{"data-testid":"status-filter",children:e.jsx(Ue,{placeholder:"Status"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Status"}),e.jsx(W,{value:"pending",children:"Pending"}),e.jsx(W,{value:"approved",children:"Approved"}),e.jsx(W,{value:"rejected",children:"Rejected"}),e.jsx(W,{value:"closed",children:"Closed"})]})]}),e.jsxs(Be,{value:a,onValueChange:h,children:[e.jsx(Ve,{"data-testid":"priority-filter",children:e.jsx(Ue,{placeholder:"Priority"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Priority"}),e.jsx(W,{value:"express",children:"Express"}),e.jsx(W,{value:"standard",children:"Standard"})]})]}),e.jsxs(Be,{value:r,onValueChange:x,children:[e.jsx(Ve,{"data-testid":"sla-compliance-filter",children:e.jsx(Ue,{placeholder:"SLA Compliance"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All SLA"}),e.jsx(W,{value:"compliant",children:"Compliant"}),e.jsx(W,{value:"on-track",children:"On Track"}),e.jsx(W,{value:"approaching",children:"Approaching"}),e.jsx(W,{value:"critical",children:"Critical"}),e.jsx(W,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Be,{value:n,onValueChange:g,children:[e.jsx(Ve,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Ue,{placeholder:"Date Range"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Time"}),e.jsx(W,{value:"today",children:"Today"}),e.jsx(W,{value:"week",children:"This Week"}),e.jsx(W,{value:"month",children:"This Month"}),e.jsx(W,{value:"last7days",children:"Last 7 Days"}),e.jsx(W,{value:"last30days",children:"Last 30 Days"}),e.jsx(W,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs($s,{open:l,onOpenChange:f,children:[e.jsx(Bs,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(qe,{className:"w-4 h-4"}),c&&d?`${Ne(c,"MMM d")} - ${Ne(d,"MMM d")}`:"Select dates"]})}),e.jsx(Us,{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(Q,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(we,{id:"start-date",type:"date",value:c?Ne(c,"yyyy-MM-dd"):"",onChange:v=>{const N=v.target.value?new Date(v.target.value):void 0;N?(j(N),d&&N>d&&w(N)):j(void 0)},max:Ne(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(we,{id:"end-date",type:"date",value:d?Ne(d,"yyyy-MM-dd"):"",onChange:v=>{const N=v.target.value?new Date(v.target.value):void 0;N?(w(N),c&&N{f(!1),j(i),w(o),(!i||!o)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const ok=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Zs,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Dt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Dt,iconColor:"text-gray-600"}}},lk=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Ce,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:yt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:He,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:He,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ce,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ee,iconColor:"text-gray-600"}}},ck=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 dk(t){if(!t)return"N/A";try{return Ne(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function mk(t){if(!t)return"N/A";try{return Ne(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function uk({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:o,onPageChange:l}){const c=ya();return e.jsxs(X,{"data-testid":"approver-performance-request-list",children:[e.jsxs(le,{children:[e.jsx(ce,{children:"Request Details"}),e.jsxs(je,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(J,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx(Zt,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading requests..."})]}):t.length===0?e.jsxs("div",{className:"text-center py-12 text-gray-500","data-testid":"empty-state",children:[e.jsx(Ee,{className:"w-12 h-12 mx-auto mb-4 text-gray-400"}),e.jsx("p",{className:"text-sm",children:"No requests found for this approver"})]}):e.jsx("div",{className:"space-y-4",children:t.map(d=>{const m=ok(d.priority),u=lk(d.status),h=ck(d.slaStatus||""),x=m.icon,g=u.icon;return e.jsx(X,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{const{navigateToRequest:f}=require("@/utils/requestNavigation");f({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":`request-card-${d.requestId}`,children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm text-blue-600 hover:underline","data-testid":"request-number",children:d.requestNumber}),e.jsxs(se,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(x,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(se,{className:u.color,"data-testid":"status-badge",children:[e.jsx(g,{className:`w-3 h-3 mr-1 ${u.iconColor}`}),d.status]}),d.approvalStatus&&e.jsx(se,{className:d.approvalStatus==="approved"||d.approvalStatus==="APPROVED"?"bg-green-100 text-green-800 border-green-200":d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?"bg-red-100 text-red-800 border-red-200":"bg-yellow-100 text-yellow-800 border-yellow-200","data-testid":"approval-status-badge",children:d.approvalStatus==="approved"||d.approvalStatus==="APPROVED"?e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"}),"Approved"]}):d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(yt,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(se,{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:d.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-500 mt-2",children:[e.jsxs("span",{className:"flex items-center gap-1","data-testid":"initiator-info",children:[e.jsx(St,{className:"w-3 h-3"}),d.initiatorName,d.initiatorDepartment&&e.jsxs("span",{className:"ml-1",children:["(",d.initiatorDepartment,")"]})]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"submission-date",children:[e.jsx(He,{className:"w-3 h-3"}),"Submitted: ",dk(d.submissionDate)]}),d.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(Ce,{className:"w-3 h-3"}),"Action: ",mk(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(Dt,{className:"w-3 h-3"}),"Level ",d.levelNumber," of ",d.totalLevels]}),d.levelElapsedHours&&d.levelElapsedHours>0&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"tat-info",children:[e.jsx(To,{className:"w-3 h-3"}),Et(d.levelElapsedHours)," / ",Et(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:f=>{f.stopPropagation();const{navigateToRequest:j}=require("@/utils/requestNavigation");j({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":"view-request-button",children:e.jsx(Wt,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx($a,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:o,onPageChange:l,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function hk(){const[t]=Um(),[s,a]=p.useState(""),[r,n]=p.useState(t.get("status")||"all"),[i,o]=p.useState(t.get("priority")||"all"),[l,c]=p.useState(t.get("slaCompliance")||"all"),[d,m]=p.useState(t.get("dateRange")||"all"),[u,h]=p.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[x,g]=p.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[f,j]=p.useState(!1),[w,b]=p.useState(void 0),[C,v]=p.useState(void 0),N=p.useCallback(()=>{a(""),n("all"),o("all"),c("all"),m("all"),h(void 0),g(void 0),b(void 0),v(void 0),j(!1)},[]),k=p.useCallback(P=>{const M=P;m(M),M!=="custom"?(h(void 0),g(void 0),b(void 0),v(void 0),j(!1)):(b(u),v(x),j(!0))},[u,x]),E=p.useCallback(()=>{if(w&&C){if(w>C){const P=w;h(C),g(P),b(C),v(P)}else h(w),g(C);j(!1)}},[w,C]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:l,dateRange:d,customStartDate:u,customEndDate:x,showCustomDatePicker:f,tempCustomStartDate:w,tempCustomEndDate:C,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:o,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:h,setCustomEndDate:g,setShowCustomDatePicker:j,setTempCustomStartDate:b,setTempCustomEndDate:v,clearFilters:N,handleDateRangeChange:k,handleApplyCustomDate:E}}function pk({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:o,searchTerm:l,itemsPerPage:c}){const[d,m]=p.useState([]),[u,h]=p.useState(null),[x,g]=p.useState([]),[f,j]=p.useState(!0),[w,b]=p.useState(!1),[C,v]=p.useState(1),[N,k]=p.useState(1),[E,P]=p.useState(0),M=p.useRef(!0),y=p.useCallback(async()=>{if(t)try{const O=s==="all"?void 0:s,$=await xt.getSingleApproverStats(t,O,a,r,i!=="all"?i:void 0,o!=="all"?o:void 0);h($)}catch(O){console.error("[ApproverPerformance] Failed to fetch approver stats:",O),h(null)}},[t,s,a,r,i,o]),A=p.useCallback(async(O=1)=>{if(!t){j(!1);return}try{j(!0);const $=await xt.getRequestsByApprover(t,O,c,s==="all"?void 0:s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,o!=="all"?o:void 0,l||void 0);m($.requests),P($.pagination.totalRecords),k($.pagination.totalPages),v($.pagination.currentPage),g($.requests)}catch($){console.error("Failed to fetch requests:",$)}finally{j(!1),b(!1)}},[t,s,a,r,n,i,o,l,c]);p.useEffect(()=>{M.current&&(M.current=!1,y(),A(1))},[]),p.useEffect(()=>{M.current||y()},[s,a,r,i,o]),p.useEffect(()=>{M.current||A(1)},[s,a,r,n,i,o,l]);const L=p.useCallback(()=>{b(!0),y(),A(1)},[y,A]),K=p.useCallback(O=>{A(O)},[A]);return{requests:d,approverStats:u,allFilteredRequests:x,loading:f,refreshing:w,currentPage:C,totalPages:N,totalRecords:E,handleRefresh:L,handlePageChange:K}}const rm=10;function xk(){const[t]=Um(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=hk(),n=pk({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:rm});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(ak,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(rk,{approverStats:n.approverStats}),n.approverStats&&e.jsx(nk,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(ik,{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(uk,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:rm,onPageChange:n.handlePageChange})]}):e.jsx(sk,{})}function gk(){const{user:t}=Gt(),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(X,{className:"relative overflow-hidden shadow-xl border-0",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(J,{className:"relative z-10 p-8 lg:p-12",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-start md:items-center gap-6",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Bt,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Vn,{src:(t==null?void 0:t.picture)||""}),e.jsx(Ut,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),Aa(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(ls,{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:[Aa(t)&&e.jsxs(se,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(ls,{className:"w-3 h-3 mr-1"}),"Administrator"]}),br(t)&&e.jsxs(se,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(Pt,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(se,{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(X,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(le,{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(St,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(je,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(J,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(aa,{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(St,{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(St,{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(St,{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(Mn,{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(X,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(le,{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(dc,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(je,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(J,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[(t==null?void 0:t.employeeId)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(St,{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(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:"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(dc,{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(ls,{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(se,{variant:Aa(t)||br(t)?"default":"secondary",className:Aa(t)?"bg-yellow-400 text-slate-900":br(t)?"bg-blue-400 text-slate-900":"",children:Aa(t)?"Administrator":br(t)?"Management":"User"}),(Aa(t)||br(t))&&e.jsx(Ce,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(X,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(le,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-purple-100 rounded-lg",children:e.jsx(qe,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(je,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(J,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-green-50 rounded-lg border border-green-200",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-green-500 rounded-full",children:e.jsx(Ce,{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(se,{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 hn="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",fk="https://re-workflow-nt-dev.siplsolutions.com";function Fi(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{}),s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Fi(hn)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Fi(hn)})}catch(o){console.warn("[Push] Initial subscription failed, attempting to clear and retry...");try{const l=await t.pushManager.getSubscription();l&&await l.unsubscribe().catch(()=>{}),s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Fi(hn)})}catch(l){const c=(o==null?void 0:o.message)||(l==null?void 0:l.message)||"Unknown error";throw c.includes("push service error")||c.includes("Registration failed")?new Error("Push service error: The browser's push service rejected the subscription. This may be due to an invalid VAPID key, network issues, or browser push service problems. Please verify your VAPID key configuration and try again."):new Error(`Failed to subscribe to push notifications: ${c}`)}}}catch(i){const o=(i==null?void 0:i.message)||"Unknown error";throw o.includes("push service error")||o.includes("Registration failed")?new Error("Push service error: The browser's push service rejected the subscription. Please verify your VAPID key is correct and matches the backend configuration. If the problem persists, try clearing your browser cache and service workers."):o.includes("Invalid key")?new Error("Invalid VAPID key format. Please verify that VITE_PUBLIC_VAPID_KEY is correctly set and matches the backend VAPID_PUBLIC_KEY."):new Error(`Failed to subscribe to push notifications: ${o}`)}const a=s.toJSON(),r=!0,n=null;try{const i={"Content-Type":"application/json"},o=await fetch(`${fk}/api/v1/workflows/notifications/subscribe`,{method:"POST",headers:i,credentials:"include",body:JSON.stringify(a)});if(!o.ok){const c=await o.json().catch(()=>({error:"Unknown error"}));throw new Error((c==null?void 0:c.error)||(c==null?void 0:c.message)||`Server error: ${o.status}`)}const l=await o.json();if(!l.success)throw new Error(l.error||"Failed to save subscription")}catch(i){throw i instanceof Error&&i.message.includes("Failed")?i:new Error(`Failed to save subscription to server: ${(i==null?void 0:i.message)||"Network error"}`)}return s}async function vk(){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 yk()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await bk(s)}catch(a){throw a}}function xo({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const o=p.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(Yx,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:ge("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(Zx,{"data-slot":"slider-track",className:ge("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(Xx,{"data-slot":"slider-range",className:ge("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:o.length},(l,c)=>e.jsx(Jx,{"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 jk({onConfigUpdate:t}){const[s,a]=p.useState([]),[r,n]=p.useState(!0),[i,o]=p.useState(null),[l,c]=p.useState(null),[d,m]=p.useState({}),[u,h]=p.useState(null);p.useEffect(()=>{x()},[]);const x=async()=>{var y,A;try{n(!0),c(null);const L=await Yn();a(L)}catch(L){c(((A=(y=L.response)==null?void 0:y.data)==null?void 0:A.error)||"Failed to load configurations")}finally{n(!1)}},g=async y=>{var A,L;try{o(y.configKey),c(null);const K=d[y.configKey]??y.configValue;if(y.validationRules){const O=parseFloat(K);if(y.valueType==="NUMBER"){if(y.validationRules.min!==void 0&&Oy.validationRules.max)throw new Error(`Value must be at most ${y.validationRules.max}`)}}await os(y.configKey,K),a(O=>O.map($=>$.configKey===y.configKey?{...$,configValue:K}:$)),m(O=>{const $={...O};return delete $[y.configKey],$}),h(`${y.displayName} updated successfully`),setTimeout(()=>h(null),3e3),t&&t()}catch(K){c(K.message||((L=(A=K.response)==null?void 0:A.data)==null?void 0:L.error)||"Failed to save configuration")}finally{o(null)}},f=async y=>{var A,L;if(confirm(`Reset "${y.displayName}" to default value?`))try{o(y.configKey),c(null),await wC(y.configKey),a(K=>K.map(O=>O.configKey===y.configKey?{...O,configValue:O.defaultValue||""}:O)),m(K=>{const O={...K};return delete O[y.configKey],O}),h(`${y.displayName} reset to default`),setTimeout(()=>h(null),3e3)}catch(K){c(((L=(A=K.response)==null?void 0:A.data)==null?void 0:L.error)||"Failed to reset configuration")}finally{o(null)}},j=(y,A)=>{m(L=>({...L,[y]:A}))},w=y=>d[y.configKey]??y.configValue,b=y=>d[y.configKey]!==void 0&&d[y.configKey]!==y.configValue,C=y=>{var K,O,$,T;const A=w(y),L=i===y.configKey;if(!y.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:y.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(Ie,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(y.uiComponent||y.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(us,{checked:A==="true",onCheckedChange:_=>j(y.configKey,_?"true":"false"),disabled:L})]});case"slider":const S=parseInt(A)||0,D=((K=y.validationRules)==null?void 0:K.min)||0,I=((O=y.validationRules)==null?void 0:O.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:[S,"%"]}),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,"-",I]})]}),e.jsx(xo,{value:[S],min:D,max:I,step:1,onValueChange:([_])=>{_!==void 0&&j(y.configKey,_.toString())},disabled:L,className:"w-full"})]});case"number":return e.jsx(we,{type:"number",value:A,onChange:_=>j(y.configKey,_.target.value),disabled:L,min:($=y.validationRules)==null?void 0:$.min,max:(T=y.validationRules)==null?void 0:T.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(we,{type:"text",value:A,onChange:_=>j(y.configKey,_.target.value),disabled:L,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},v=y=>{switch(y){case"TAT_SETTINGS":return e.jsx(He,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Ee,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(cs,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(Fn,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(qa,{className:"w-5 h-5"});default:return e.jsx(ua,{className:"w-5 h-5"})}},N=["DASHBOARD_LAYOUT"],k=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],E=s.filter(y=>!N.includes(y.configCategory)&&!k.includes(y.configKey)),P=E.reduce((y,A)=>(y[A.configCategory]||(y[A.configCategory]=[]),y[A.configCategory].push(A),y),{});if(Object.keys(P).forEach(y=>{const A=P[y];A&&A.sort((L,K)=>L.sortOrder-K.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Je,{className:"w-8 h-8 animate-spin text-gray-400"})});if(E.length===0)return e.jsx(X,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(J,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(ua,{className:"w-10 h-10 text-slate-400"})}),e.jsx("p",{className:"text-slate-700 font-medium text-lg",children:"No configurations found"}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 max-w-md mx-auto",children:"System configurations will appear here once they are initialized"})]})});const M=Object.keys(P);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(Ce,{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(Ie,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:l}),e.jsx(R,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(Jr,{defaultValue:M[0],className:"w-full",children:[e.jsx(Qr,{className:"flex flex-wrap w-full bg-slate-100/80 backdrop-blur-sm p-1 gap-1 rounded-md h-auto border border-slate-200 shadow-sm",children:M.map(y=>e.jsx(gt,{value:y,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:y.replace(/_/g," ")})},y))}),M.map(y=>{var A,L,K;return e.jsx(ft,{value:y,className:"space-y-4 mt-6",children:e.jsxs(X,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(le,{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:v(y)})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg font-semibold text-slate-900",children:y.replace(/_/g," ")}),e.jsxs(je,{className:"text-sm",children:[((A=P[y])==null?void 0:A.length)||0," setting",(((L=P[y])==null?void 0:L.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(J,{className:"space-y-6",children:(K=P[y])==null?void 0:K.map(O=>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(Q,{className:"text-sm font-semibold text-slate-900",children:O.displayName}),b(O)&&e.jsx(se,{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"}),O.requiresRestart&&e.jsx(se,{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"})]}),O.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:O.description}),O.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:O.defaultValue})]})]})}),C(O),O.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(R,{size:"sm",onClick:()=>g(O),disabled:!b(O)||i===O.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===O.configKey?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(fa,{className:"w-4 h-4"}),"Save Changes"]})}),O.defaultValue&&e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>f(O),disabled:i===O.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(Xg,{className:"w-4 h-4"}),"Reset to Default"]})]})]},O.configKey))})]})},y)})]})]})}function Nk(){const[t,s]=p.useState([]),[a,r]=p.useState(!0),[n,i]=p.useState(new Date().getFullYear()),[o,l]=p.useState(!1),[c,d]=p.useState(null),[m,u]=p.useState(null),[h,x]=p.useState(null),[g,f]=p.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});p.useEffect(()=>{j()},[n]);const j=async()=>{var y,A;try{r(!0),u(null);const L=await CC(n);s(L)}catch(L){u(((A=(y=L.response)==null?void 0:y.data)==null?void 0:A.error)||"Failed to load holidays")}finally{r(!1)}},w=()=>{f({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),l(!0)},b=y=>{f({holidayDate:y.holidayDate,holidayName:y.holidayName,description:y.description||"",holidayType:y.holidayType,isRecurring:y.isRecurring}),d(y),l(!0)},C=()=>{if(c)return;const y=new Date;return y.setDate(y.getDate()+1),y.toISOString().split("T")[0]},v=async()=>{var y,A;try{if(u(null),!g.holidayDate||!g.holidayName){u("Holiday date and name are required");return}c?(await AC(c.holidayId,g),x("Holiday updated successfully")):(await SC(g),x("Holiday created successfully")),await j(),l(!1),setTimeout(()=>x(null),3e3)}catch(L){u(((A=(y=L.response)==null?void 0:y.data)==null?void 0:A.error)||"Failed to save holiday")}},N=async y=>{var A,L;if(confirm(`Delete "${y.holidayName}"?`))try{u(null),await kC(y.holidayId),x("Holiday deleted successfully"),await j(),setTimeout(()=>x(null),3e3)}catch(K){u(((L=(A=K.response)==null?void 0:A.data)==null?void 0:L.error)||"Failed to delete holiday")}},k=y=>{switch(y){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"}},E=Array.from({length:5},(y,A)=>new Date().getFullYear()-1+A),P=t.reduce((y,A)=>{const L=new Date(A.holidayDate).toLocaleString("default",{month:"long"});return y[L]||(y[L]=[]),y[L].push(A),y},{}),M=Object.keys(P).sort((y,A)=>{const L=new Date(Date.parse(y+" 1, 2000")).getMonth(),K=new Date(Date.parse(A+" 1, 2000")).getMonth();return L-K});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(Ce,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:h})]}),m&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(Ie,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:m}),e.jsx(R,{size:"sm",variant:"ghost",onClick:()=>u(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(X,{className:"shadow-lg border-0 rounded-md",children:e.jsx(le,{className:"border-b border-slate-100 py-4 sm:py-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(qe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(je,{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(Be,{value:n.toString(),onValueChange:y=>i(parseInt(y)),children:[e.jsx(Ve,{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(Ue,{})}),e.jsx(ze,{className:"rounded-md",children:E.map(y=>e.jsx(W,{value:y.toString(),children:y},y))})]}),e.jsxs(R,{onClick:w,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(Ws,{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(Je,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(X,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(J,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(qe,{className:"w-10 h-10 text-slate-400"})}),e.jsxs("p",{className:"text-slate-700 font-medium text-lg",children:["No holidays found for ",n]}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 mb-6",children:"Add holidays to exclude them from TAT calculations"}),e.jsxs(R,{onClick:w,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(Ws,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:M.map(y=>{var A,L,K;return e.jsxs(X,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(le,{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(ce,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[y," ",n]}),e.jsxs(je,{className:"text-xs sm:text-sm",children:[((A=P[y])==null?void 0:A.length)||0," holiday",(((L=P[y])==null?void 0:L.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(qe,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(J,{className:"space-y-3 pt-4",children:(K=P[y])==null?void 0:K.map(O=>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:O.holidayName}),e.jsx(se,{variant:"outline",className:`${k(O.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:O.holidayType}),O.isRecurring&&e.jsx(se,{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:hu(O.holidayDate)}),O.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:O.description})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(R,{size:"sm",variant:"ghost",onClick:()=>b(O),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(Mm,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(R,{size:"sm",variant:"ghost",onClick:()=>N(O),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(Do,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},O.holidayId))})]},y)})}),e.jsx(nt,{open:o,onOpenChange:l,children:e.jsxs(tt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(it,{className:"pb-4 border-b border-slate-100 px-6 pt-6 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-lg shadow-md",children:e.jsx(qe,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(st,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(Mt,{className:"text-sm text-slate-600 mt-1",children:c?"Update holiday information":"Add a new holiday to the calendar for TAT calculations"})]})]})}),e.jsxs("div",{className:"space-y-5 py-6 px-6 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{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(we,{id:"date",type:"date",value:g.holidayDate,onChange:y=>f({...g,holidayDate:y.target.value}),min:C(),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(Q,{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(we,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:y=>f({...g,holidayName:y.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(Q,{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(we,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:y=>f({...g,description:y.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(Q,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(Be,{value:g.holidayType,onValueChange:y=>f({...g,holidayType:y}),children:[e.jsx(Ve,{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(Ue,{})}),e.jsxs(ze,{className:"rounded-lg",children:[e.jsx(W,{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(W,{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(W,{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(W,{value:"OPTIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-500"}),e.jsx("span",{children:"Optional"})]})})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Select the category of this holiday"})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gradient-to-br from-slate-50 to-slate-100/50 border-2 border-slate-200 rounded-lg hover:border-slate-300 hover:bg-slate-100 transition-all cursor-pointer group",onClick:()=>f({...g,isRecurring:!g.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:g.isRecurring,onChange:y=>f({...g,isRecurring:y.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(Q,{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(Nt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(R,{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(R,{onClick:v,disabled:!g.holidayDate||!g.holidayName,className:"h-11 bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(qe,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function wk(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function Ck(){const[t,s]=p.useState(""),[a,r]=p.useState([]),[n,i]=p.useState(!1),[o,l]=p.useState(null),[c,d]=p.useState("USER"),[m,u]=p.useState(!1),[h,x]=p.useState(null),[g,f]=p.useState([]),[j,w]=p.useState(!1),[b,C]=p.useState({admins:0,management:0,users:0}),[v,N]=p.useState("ELEVATED"),[k,E]=p.useState(1),[P,M]=p.useState(1),[y,A]=p.useState(0),L=10,K=p.useRef(null),O=p.useRef(null),$=p.useCallback(wk(async V=>{var Y,Z,U;if(!V||!V.startsWith("@")||V.length<2){r([]),i(!1);return}i(!0);try{const ee=V.slice(1),de=((Y=(await js.searchUsers(ee,20)).data)==null?void 0:Y.data)||[];r(de)}catch(ee){console.error("Search failed:",ee),x({type:"error",text:((U=(Z=ee.response)==null?void 0:Z.data)==null?void 0:U.message)||"Failed to search users"})}finally{i(!1)}},300),[]),T=V=>{const Y=V.target.value;s(Y),$(Y)},S=async V=>{l(V),s(V.email),r([]);const Y=g.find(Z=>Z.email.toLowerCase()===V.email.toLowerCase()||Z.userId===V.userId);if(Y&&Y.role)d(Y.role);else try{const U=(await js.getAllUsers()).find(ee=>ee.email&&ee.email.toLowerCase()===V.email.toLowerCase()||ee.userId&&ee.userId===V.userId);U&&U.role?d(U.role):d("USER")}catch(Z){console.error("Failed to check user role:",Z),d("USER")}},D=async()=>{var V,Y;if(!o||!c){x({type:"error",text:"Please select a user and role"});return}u(!0),x(null);try{await js.assignRole(o.email,c),x({type:"success",text:`Successfully assigned ${c} role to ${o.displayName||o.email}`}),l(null),s(""),d("USER"),await I(),await _()}catch(Z){console.error("Role assignment failed:",Z),x({type:"error",text:((Y=(V=Z.response)==null?void 0:V.data)==null?void 0:Y.error)||"Failed to assign role"})}finally{u(!1)}},I=async(V=k)=>{var Y,Z,U,ee,ie,de;w(!0);try{const Ae=await js.getUsersByRole(v,V,L),We=((Z=(Y=Ae.data)==null?void 0:Y.data)==null?void 0:Z.users)||[],Se=(ee=(U=Ae.data)==null?void 0:U.data)==null?void 0:ee.pagination,Ye=(de=(ie=Ae.data)==null?void 0:ie.data)==null?void 0:de.summary;f(We),Se&&(E(Se.currentPage),M(Se.totalPages),A(Se.totalUsers)),Ye&&C({admins:Ye.ADMIN||0,management:Ye.MANAGEMENT||0,users:Ye.USER||0})}catch(Ae){console.error("Failed to fetch users:",Ae)}finally{w(!1)}},_=async()=>{var V,Y,Z,U,ee,ie;try{const de=await js.getRoleStatistics(),Ae=((Y=(V=de.data)==null?void 0:V.data)==null?void 0:Y.statistics)||((Z=de.data)==null?void 0:Z.statistics)||[];C({admins:parseInt(((U=Ae.find(We=>We.role==="ADMIN"))==null?void 0:U.count)||"0"),management:parseInt(((ee=Ae.find(We=>We.role==="MANAGEMENT"))==null?void 0:ee.count)||"0"),users:parseInt(((ie=Ae.find(We=>We.role==="USER"))==null?void 0:ie.count)||"0")})}catch(de){console.error("Failed to fetch statistics:",de)}};p.useEffect(()=>{I(1),_()},[v]);const F=V=>{N(V),E(1)},G=V=>{I(V)},B=V=>{N(V),E(1),requestAnimationFrame(()=>{const Y=O.current;Y&&Y.scrollIntoView({behavior:"smooth",block:"start"})})};p.useEffect(()=>{const V=Y=>{K.current&&!K.current.contains(Y.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",V),()=>{document.removeEventListener("mousedown",V)}},[a]);const re=V=>{switch(V){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"}},ae=V=>{switch(V){case"ADMIN":return e.jsx(Va,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(Pt,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(St,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(X,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(le,{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(Jg,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx(je,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6",children:[e.jsx(X,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${v==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>B("ADMIN"),children:e.jsx(J,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Administrators"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"admin-count",children:b.admins}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1 font-semibold",children:v==="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(Va,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(X,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${v==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>B("MANAGEMENT"),children:e.jsx(J,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Management"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"management-count",children:b.management}),e.jsx("p",{className:"text-xs text-blue-700 mt-1 font-semibold",children:v==="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(Pt,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(X,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${v==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>B("USER"),children:e.jsx(J,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Regular Users"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"user-count",children:b.users}),e.jsx("p",{className:"text-xs text-gray-700 mt-1 font-semibold",children:v==="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(St,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(It,{}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"Assign User Role"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Search for a user in Okta and assign them a role"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",ref:K,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(ws,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(we,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:T,className:"pl-10 pr-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"user-search-input"}),n&&e.jsx(Je,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-re-green animate-spin"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Start with @ to search users (e.g., @john)"}),a.length>0&&e.jsxs("div",{className:"border border-purple-200 rounded-lg shadow-lg bg-white max-h-60 overflow-y-auto",children:[e.jsx("div",{className:"sticky top-0 bg-purple-50 px-4 py-2 border-b border-purple-100",children:e.jsxs("p",{className:"text-xs font-semibold text-purple-700",children:[a.length," user",a.length>1?"s":""," found"]})}),e.jsx("div",{className:"p-2",children:a.map(V=>e.jsxs("button",{onClick:()=>S(V),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${V.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:V.displayName||V.email}),e.jsx("p",{className:"text-xs text-gray-600",children:V.email}),V.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[V.department,V.designation?` • ${V.designation}`:""]})]},V.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(R,{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(Be,{value:c,onValueChange:V=>d(V),children:[e.jsx(Ve,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(Ue,{placeholder:"Select role"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(W,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(W,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Va,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(R,{onClick:D,disabled:!o||m,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"assign-role-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ls,{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(Ce,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Ie,{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(It,{}),e.jsxs("div",{ref:O,children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"User Management"}),e.jsxs("p",{className:"text-sm text-gray-600",children:["View and manage user roles (",y," ",v!=="ALL"&&v!=="ELEVATED"?v.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Be,{value:v,onValueChange:F,children:[e.jsx(Ve,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Ue,{placeholder:"Filter by role"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",b.admins+b.management,")"]})]})}),e.jsx(W,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Va,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",b.admins,")"]})]})}),e.jsx(W,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",b.management,")"]})]})}),e.jsx(W,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",b.users,")"]})]})}),e.jsx(W,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",b.admins+b.management+b.users,")"]})]})})]})]})})]}),e.jsx("div",{className:"pt-2",children:j?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Je,{className:"w-6 h-6 animate-spin text-purple-500 mb-2"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading users..."})]}):g.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(Pt,{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:v==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2","data-testid":"users-list",children:g.map(V=>e.jsx("div",{className:"border border-gray-200 hover:border-re-green hover:shadow-sm transition-all rounded-lg bg-white p-4","data-testid":`user-${V.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 ${re(V.role)} flex items-center justify-center shadow-sm`,children:ae(V.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:V.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:V.email}),V.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[V.department,V.designation?` • ${V.designation}`:""]})]})]}),e.jsx(se,{className:`${re(V.role)} shrink-0`,"data-testid":`role-badge-${V.role}`,children:V.role})]})},V.userId))}),P>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)*L+1," to ",Math.min(k*L,y)," of ",y," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{variant:"outline",size:"sm",onClick:()=>G(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,P)},(V,Y)=>{let Z;return P<=5||k<=3?Z=Y+1:k>=P-2?Z=P-4+Y:Z=k-2+Y,e.jsx(R,{variant:k===Z?"default":"outline",size:"sm",onClick:()=>G(Z),className:`w-9 h-9 p-0 ${k===Z?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${Z}-button`,children:Z},Z)})}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>G(k+1),disabled:k===P,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function Sk({open:t,onClose:s,success:a,message:r}){return e.jsx(nt,{open:t,onOpenChange:s,children:e.jsxs(tt,{className:"sm:max-w-md",children:[e.jsxs(it,{children:[e.jsxs(st,{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(Mt,{className:"sr-only",children:a?"Push notifications have been successfully enabled for your account.":"There was an error enabling push notifications. Please review the details below."})]}),e.jsx("div",{className:"py-6",children:e.jsx("div",{className:"flex flex-col items-center text-center",children:a?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mb-4",children:e.jsx(Ce,{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(yt,{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(Nt,{children:e.jsx(R,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const Ak=async()=>(await he.get("/user/preferences/notifications")).data.data,kk=async t=>(await he.put("/user/preferences/notifications",t)).data.data;function Tk({open:t,onClose:s}){const[a,r]=p.useState({emailNotificationsEnabled:!0,pushNotificationsEnabled:!0,inAppNotificationsEnabled:!0}),[n,i]=p.useState(!0),[o,l]=p.useState(null),[c,d]=p.useState(null),[m,u]=p.useState(null);p.useEffect(()=>{t&&h()},[t]);const h=async()=>{var g,f;try{i(!0),u(null);const j=await Ak();r(j)}catch(j){console.error("[NotificationPreferences] Failed to load preferences:",j),u(((f=(g=j.response)==null?void 0:g.data)==null?void 0:f.message)||"Failed to load notification preferences")}finally{i(!1)}},x=async(g,f)=>{var j,w;try{l(g),u(null),d(null);const b={[g]:f},C=await kk(b);r(C),d(`${g==="emailNotificationsEnabled"?"Email":g==="pushNotificationsEnabled"?"Push":"In-App"} notifications ${f?"enabled":"disabled"}`),setTimeout(()=>d(null),3e3)}catch(b){console.error("[NotificationPreferences] Failed to update preference:",b),u(((w=(j=b.response)==null?void 0:j.data)==null?void 0:w.message)||"Failed to update notification preference"),h()}finally{l(null)}};return e.jsx(nt,{open:t,onOpenChange:s,children:e.jsxs(tt,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(it,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-lg",children:e.jsx(ua,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(st,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(Mt,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx(It,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(Je,{className:"w-8 h-8 animate-spin text-gray-400"})}):e.jsxs("div",{className:"space-y-6",children:[c&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-green-50 border border-green-200 rounded-md animate-in fade-in slide-in-from-top-2",children:[e.jsx(Ce,{className:"w-4 h-4 text-green-600 shrink-0"}),e.jsx("p",{className:"text-sm text-green-800 font-medium",children:c})]}),m&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-md animate-in fade-in slide-in-from-top-2",children:[e.jsx(Ie,{className:"w-4 h-4 text-red-600 shrink-0"}),e.jsx("p",{className:"text-sm text-red-800 font-medium",children:m})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(aa,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(Q,{htmlFor:"email-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Email Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Receive important updates and alerts via email"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[o==="emailNotificationsEnabled"&&e.jsx(Je,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(us,{id:"email-notifications-modal",checked:a.emailNotificationsEnabled,onCheckedChange:g=>x("emailNotificationsEnabled",g),disabled:o==="emailNotificationsEnabled"})]})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(cs,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(Q,{htmlFor:"push-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Push Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Get instant browser notifications for real-time updates"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[o==="pushNotificationsEnabled"&&e.jsx(Je,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(us,{id:"push-notifications-modal",checked:a.pushNotificationsEnabled,onCheckedChange:g=>x("pushNotificationsEnabled",g),disabled:o==="pushNotificationsEnabled"})]})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(Ps,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(Q,{htmlFor:"inapp-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"In-App Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"View notifications in the notification center"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[o==="inAppNotificationsEnabled"&&e.jsx(Je,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(us,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>x("inAppNotificationsEnabled",g),disabled:o==="inAppNotificationsEnabled"})]})]})}),e.jsx(It,{}),e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-lg",children:e.jsxs("p",{className:"text-sm text-gray-700 leading-relaxed",children:[e.jsx("span",{className:"font-semibold",children:"Note:"})," These settings control your notification preferences across all channels. Critical system alerts and urgent notifications may still be delivered regardless of these settings to ensure important information reaches you."]})})]})]})})}function Dk(){const{user:t}=Gt(),s=Aa(t),[a,r]=p.useState(!1),[n,i]=p.useState(!1),[o,l]=p.useState(),[c,d]=p.useState(!1),[m,u]=p.useState(!1),[h,x]=p.useState(!1),[g,f]=p.useState(!0);p.useEffect(()=>{j()},[]);const j=async()=>{try{f(!0);const b=await $0();x(b.length>0)}catch(b){console.error("Failed to check subscription status:",b),x(!1)}finally{f(!1)}},w=async()=>{d(!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),d(!1);return}let b=Notification.permission;if(b==="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),d(!1);return}if(b==="default"&&(b=await Notification.requestPermission(),b==="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),d(!1);return}if(b!=="granted"){i(!1),l("Notification permission is required to enable push notifications. Please grant permission and try again."),r(!0),d(!1);return}await vk(),i(!0),l("Push notifications have been successfully enabled! You will now receive notifications for workflow updates, approvals, and TAT alerts."),r(!0),await j()}catch(b){console.error("[Settings] Error enabling notifications:",b),i(!1);const C=(b==null?void 0:b.message)||"Unknown error occurred";l(C.includes("permission")?"Notification permission was denied. Please enable notifications in your browser settings and try again.":C.includes("Service worker")?"Service worker registration failed. Please refresh the page and try again.":C.includes("token")?"Authentication required. Please log in again and try enabling notifications.":`Unable to enable push notifications: ${C}`),r(!0)}finally{d(!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(X,{className:"relative overflow-hidden shadow-2xl border-0 rounded-2xl",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,_var(--tw-gradient-stops))] from-yellow-400/20 via-transparent to-transparent"}),e.jsx(J,{className:"relative z-10 p-6 sm:p-8 lg:p-12",children:e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6",children:[e.jsx("div",{className:"w-14 h-14 sm:w-16 sm:h-16 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-2xl flex items-center justify-center shadow-xl transform hover:scale-105 transition-transform",children:e.jsx(ua,{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(Jr,{defaultValue:"user",className:"w-full",children:[e.jsxs(Qr,{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(gt,{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(ua,{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(gt,{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(ls,{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(gt,{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($m,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Configuration"}),e.jsx("span",{className:"sm:hidden",children:"Config"})]}),e.jsxs(gt,{value:"holidays",className:"flex items-center justify-center gap-2 py-3 rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-md transition-all",children:[e.jsx(qe,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Holidays"}),e.jsx("span",{className:"sm:hidden",children:"Holidays"})]})]}),e.jsxs("div",{className:"w-full min-h-[600px]",children:[e.jsx(ft,{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(X,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(le,{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(cs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(je,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(J,{children:e.jsxs("div",{className:"space-y-4",children:[g?e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-md flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Checking registration status..."})}):h?e.jsx("div",{className:"p-3 bg-green-50 border border-green-200 rounded-md",children:e.jsx("p",{className:"text-xs text-green-800 font-medium",children:"✓ This browser is already registered for push notifications."})}):e.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-md",children:e.jsx("p",{className:"text-xs text-blue-800",children:"Click below to register this browser for receiving push notifications. This needs to be done once per browser/device."})}),e.jsxs(R,{onClick:w,disabled:c||h,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(cs,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Registering...":h?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(X,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(le,{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(Ir,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(je,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(J,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Security settings will be available soon"})})})})]}),e.jsxs(X,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(le,{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(mc,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(je,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(J,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Appearance settings will be available soon"})})})})]}),e.jsxs(X,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(le,{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(ls,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(je,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(J,{children:e.jsxs(R,{onClick:()=>u(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(ls,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})}),e.jsx(ft,{value:"roles",className:"mt-0",children:e.jsx(Ck,{})}),e.jsx(ft,{value:"system",className:"mt-0",children:e.jsx(jk,{})}),e.jsx(ft,{value:"holidays",className:"mt-0",children:e.jsx(Nk,{})})]})]}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs(X,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(le,{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(cs,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg font-semibold text-gray-900",children:"Browser Push Setup"}),e.jsx(je,{className:"text-sm text-gray-600",children:"Register this browser for push notifications"})]})]})}),e.jsx(J,{children:e.jsxs("div",{className:"space-y-4",children:[g?e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-md flex items-center justify-center",children:e.jsx("p",{className:"text-sm text-gray-600",children:"Checking registration status..."})}):h?e.jsx("div",{className:"p-3 bg-green-50 border border-green-200 rounded-md",children:e.jsx("p",{className:"text-xs text-green-800 font-medium",children:"✓ This browser is already registered for push notifications."})}):e.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-md",children:e.jsx("p",{className:"text-xs text-blue-800",children:"Click below to register this browser for receiving push notifications. This needs to be done once per browser/device."})}),e.jsxs(R,{onClick:w,disabled:c||h,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(cs,{className:`w-4 h-4 mr-2 ${c?"animate-pulse":""}`}),c?"Registering...":h?"Already Registered":"Register Browser for Push"]})]})})]}),e.jsxs(X,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(le,{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(Ir,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg font-semibold text-gray-900",children:"Security"}),e.jsx(je,{className:"text-sm text-gray-600",children:"Password and security settings"})]})]})}),e.jsx(J,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Security settings will be available soon"})})})})]}),e.jsxs(X,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(le,{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(mc,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg font-semibold text-gray-900",children:"Appearance"}),e.jsx(je,{className:"text-sm text-gray-600",children:"Theme and display preferences"})]})]})}),e.jsx(J,{children:e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200",children:e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"Appearance settings will be available soon"})})})})]}),e.jsxs(X,{className:"shadow-lg hover:shadow-xl transition-all duration-300 border-0 rounded-md group",children:[e.jsx(le,{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(ls,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg font-semibold text-gray-900",children:"Preferences"}),e.jsx(je,{className:"text-sm text-gray-600",children:"Notification and application preferences"})]})]})}),e.jsx(J,{children:e.jsxs(R,{onClick:()=>u(!0),className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all",children:[e.jsx(ls,{className:"w-4 h-4 mr-2"}),"Manage Preferences"]})})]})]})})]}),e.jsx(Sk,{open:a,onClose:()=>r(!1),success:n,message:o}),e.jsx(Tk,{open:m,onClose:()=>u(!1)})]})}function Rk({onNavigate:t}){const[s,a]=p.useState([]),[r,n]=p.useState(!0),[i,o]=p.useState(1),[l,c]=p.useState(1),[d,m]=p.useState(0),[u,h]=p.useState("all"),[x,g]=p.useState(!1),f=20,j=async(M=i,y=u==="unread")=>{var A,L;try{n(M===1);const K=await da.list({page:M,limit:f,unreadOnly:y}),O=((A=K.data)==null?void 0:A.notifications)||[],$=((L=K.data)==null?void 0:L.total)||0;a(O),m($),c(Math.ceil($/f))}catch(K){console.error("[Notifications] Failed to fetch:",K)}finally{n(!1),g(!1)}};p.useEffect(()=>{j(1,u==="unread")},[u]);const w=async M=>{var y;try{if(M.isRead||(await da.markAsRead(M.notificationId),a(A=>A.map(L=>L.notificationId===M.notificationId?{...L,isRead:!0}:L))),M.actionUrl&&t){const A=(y=M.metadata)==null?void 0:y.requestNumber;if(A){let L=`request/${A}`;(M.notificationType==="mention"||M.notificationType==="comment"||M.notificationType==="worknote")&&(L+="?tab=worknotes"),t(L)}}}catch(A){console.error("[Notifications] Error handling notification click:",A)}},b=async()=>{try{g(!0),await da.markAllAsRead(),await j(i,u==="unread")}catch(M){console.error("[Notifications] Error marking all as read:",M),g(!1)}},C=async M=>{try{await da.delete(M),a(y=>y.filter(A=>A.notificationId!==M)),m(y=>y-1)}catch(y){console.error("[Notifications] Error deleting notification:",y)}},v=()=>{g(!0),j(i,u==="unread")},N=M=>{M<1||M>l||(o(M),j(M,u==="unread"))},k=M=>{const y="w-6 h-6";switch(M){case"mention":case"comment":return e.jsx(Ps,{className:`${y} text-blue-600`});case"worknote":return e.jsx(Ee,{className:`${y} text-purple-600`});case"assignment":return e.jsx(Ln,{className:`${y} text-indigo-600`});case"approval":return e.jsx(Ce,{className:`${y} text-green-600`});case"rejection":return e.jsx(yt,{className:`${y} text-red-600`});case"tat_alert":return e.jsx(He,{className:`${y} text-orange-600`});case"tat_breach":return e.jsx(Ie,{className:`${y} text-red-600`});case"tat_breach_initiator":return e.jsx(as,{className:`${y} text-amber-600`});default:return e.jsx(cs,{className:`${y} text-gray-600`})}},E=M=>{switch(M==null?void 0:M.toUpperCase()){case"URGENT":return"bg-red-100 text-red-800 border-red-200";case"HIGH":return"bg-orange-100 text-orange-800 border-orange-200";case"MEDIUM":return"bg-blue-100 text-blue-800 border-blue-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},P=s.filter(M=>!M.isRead).length;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-3xl font-bold text-gray-900 flex items-center gap-3",children:[e.jsx(cs,{className:"w-8 h-8 text-blue-600"}),"Notifications"]}),e.jsxs("p",{className:"text-gray-600 mt-1",children:[d," total notification",d!==1?"s":"",P>0&&` • ${P} unread`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:v,disabled:x,className:"gap-2",children:[e.jsx(Zt,{className:`w-4 h-4 ${x?"animate-spin":""}`}),"Refresh"]}),P>0&&e.jsxs(R,{variant:"outline",size:"sm",onClick:b,disabled:x,className:"gap-2",children:[e.jsx(Qg,{className:"w-4 h-4"}),"Mark All Read"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{variant:u==="all"?"default":"outline",size:"sm",onClick:()=>{h("all"),o(1)},children:"All Notifications"}),e.jsxs(R,{variant:u==="unread"?"default":"outline",size:"sm",onClick:()=>{h("unread"),o(1)},children:["Unread",P>0&&e.jsx(se,{className:"ml-2 bg-red-500 text-white",children:P})]})]}),e.jsxs(X,{children:[e.jsxs(le,{children:[e.jsx(ce,{children:"Recent Activity"}),e.jsx(je,{children:"Stay updated with all your workflow activities and mentions"})]}),e.jsx(J,{children:r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"})}):s.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(cs,{className:"w-16 h-16 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-lg font-medium text-gray-900 mb-2",children:"No notifications"}),e.jsx("p",{className:"text-sm text-gray-500",children:u==="unread"?"You're all caught up! No unread notifications.":"You don't have any notifications yet."})]}):e.jsx("div",{className:"space-y-2",children:s.map(M=>{var y;return e.jsx("div",{className:`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${M.isRead?"bg-white border-gray-200 hover:bg-gray-50":"bg-blue-50 border-blue-200 hover:bg-blue-100"}`,onClick:()=>w(M),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 mt-0.5",children:k(M.notificationType)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[e.jsx("h4",{className:`text-sm ${M.isRead?"font-semibold":"font-bold"} text-gray-900`,children:M.title}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[M.priority&&M.priority!=="LOW"&&e.jsx(se,{variant:"outline",className:`text-xs ${E(M.priority)}`,children:M.priority}),!M.isRead&&e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-600"})]})]}),e.jsx("p",{className:"text-sm text-gray-700 mb-2 line-clamp-2",children:M.message}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[Nm(new Date(M.createdAt),{addSuffix:!0}),((y=M.metadata)==null?void 0:y.requestNumber)&&e.jsxs("span",{className:"ml-2",children:["• ",M.metadata.requestNumber]})]}),e.jsx(R,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600",onClick:A=>{A.stopPropagation(),C(M.notificationId)},children:e.jsx(Do,{className:"w-3.5 h-3.5"})})]})]})]})},M.notificationId)})})})]}),!r&&l>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Showing ",(i-1)*f+1," to ",Math.min(i*f,d)," of ",d," notifications"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>N(i-1),disabled:i===1,children:[e.jsx(Lm,{className:"w-4 h-4"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,l)},(M,y)=>{let A;return l<=5||i<=3?A=y+1:i>=l-2?A=l-4+y:A=i-2+y,e.jsx(R,{variant:i===A?"default":"outline",size:"sm",className:"w-9 h-9 p-0",onClick:()=>N(A),children:A},A)})}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>N(i+1),disabled:i===l,children:["Next",e.jsx(ko,{className:"w-4 h-4"})]})]})]})]})}function Pk({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(R,{variant:"outline",onClick:t,className:"inline-flex items-center gap-2","data-testid":"back-button",children:[e.jsx(Rs,{className:"w-4 h-4 mr-2"}),"Back to Dashboard"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-purple-100 rounded-lg",children:e.jsx(Ee,{className:"h-6 w-6 text-purple-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Detailed Reports"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Comprehensive workflow and activity reports"})]})]})]})})}function kl({dateRange:t,customStartDate:s,customEndDate:a,showCustomDatePicker:r,tempCustomStartDate:n,tempCustomEndDate:i,onDateRangeChange:o,onShowCustomDatePickerChange:l,onStartDateChange:c,onEndDateChange:d,onApply:m,onCancel:u,testIdPrefix:h="date-filter"}){const x=s&&a?`${Ne(s,"MMM d, yyyy")} - ${Ne(a,"MMM d, yyyy")}`:"Select dates";return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${h}-container`,children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Be,{value:t,onValueChange:o,"data-testid":`${h}-select`,children:[e.jsx(Ve,{className:"w-[160px]",children:e.jsx(Ue,{placeholder:"Date Range"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"today",children:"Today"}),e.jsx(W,{value:"week",children:"This Week"}),e.jsx(W,{value:"month",children:"This Month"}),e.jsx(W,{value:"custom",children:"Custom Range"})]})]}),t==="custom"&&e.jsxs($s,{open:r,onOpenChange:l,children:[e.jsx(Bs,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2","data-testid":`${h}-custom-trigger`,children:[e.jsx(qe,{className:"w-4 h-4"}),x]})}),e.jsx(Us,{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(Q,{htmlFor:`${h}-start-date`,className:"text-sm font-medium",children:"Start Date"}),e.jsx(we,{id:`${h}-start-date`,type:"date",value:n?Ne(n,"yyyy-MM-dd"):"",onChange:g=>{const f=g.target.value?new Date(g.target.value):void 0;c(f)},max:Ne(new Date,"yyyy-MM-dd"),className:"w-full","data-testid":`${h}-start-input`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:`${h}-end-date`,className:"text-sm font-medium",children:"End Date"}),e.jsx(we,{id:`${h}-end-date`,type:"date",value:i?Ne(i,"yyyy-MM-dd"):"",onChange:g=>{const f=g.target.value?new Date(g.target.value):void 0;d(f)},min:n?Ne(n,"yyyy-MM-dd"):void 0,max:Ne(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(R,{size:"sm",onClick:m,disabled:!n||!i,className:"flex-1 bg-re-green hover:bg-re-green/90","data-testid":`${h}-apply-button`,children:"Apply"}),e.jsx(R,{size:"sm",variant:"outline",onClick:u,"data-testid":`${h}-cancel-button`,children:"Cancel"})]})]})})]})]})}function Ek(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 Hp(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 Wp(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 Ik(t){return t>=20?"bg-red-600":t>=10?"bg-orange-500":"bg-amber-500"}function Mk({lifecycleRequests:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,exporting:u,onDateRangeChange:h,onShowCustomDatePickerChange:x,onStartDateChange:g,onEndDateChange:f,onApplyCustomDate:j,onCancelCustomDate:w,onPageChange:b,onExport:C,onViewRequest:v}){return e.jsxs(X,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"request-lifecycle-report",children:[e.jsxs(le,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(Vt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg text-gray-900",children:"Request Lifecycle Report"}),e.jsx(je,{className:"text-gray-600",children:"End-to-end workflow status including all approval levels, approvers, dates, and TAT compliance"})]})]}),e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2",onClick:C,disabled:u,"data-testid":"export-lifecycle-button",children:[e.jsx(ss,{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(kl,{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:h,onShowCustomDatePickerChange:x,onStartDateChange:g,onEndDateChange:f,onApply:j,onCancel:w,testIdPrefix:"lifecycle"})})]}),e.jsxs(J,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"lifecycle-loading",children:[e.jsx(Je,{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(Ie,{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(N=>e.jsx("div",{className:"border rounded-xl overflow-hidden","data-testid":`lifecycle-request-${N.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:()=>v(N.requestId||N.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(),v(N.requestId||N.id)},className:"font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors","data-testid":`lifecycle-request-link-${N.id}`,children:N.id}),e.jsx(se,{className:Hp(N.priority),"data-testid":`lifecycle-priority-${N.id}`,children:N.priority}),e.jsx(se,{className:Wp(N.status),"data-testid":`lifecycle-status-${N.id}`,children:N.status})]}),e.jsx("p",{className:"text-sm text-gray-700",children:N.title}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Initiated by ",e.jsx("span",{className:"font-medium",children:N.initiator})," on ",N.initDate]}),N.currentStage&&!N.currentStage.includes("Level")&&e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["Stage: ",N.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:N.currentStage}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:["(Level ",N.currentLevel,"/",N.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:N.overallTAT}),N.breachCount>0&&e.jsxs("p",{className:"text-xs text-red-500 mt-0.5",children:[N.breachCount," breach",N.breachCount>1?"es":""]})]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>v(N.requestId||N.id),className:"gap-1.5","data-testid":`lifecycle-view-button-${N.id}`,children:e.jsx(ko,{className:"w-4 h-4"})})]})]})})},N.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(Je,{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(R,{variant:"outline",size:"sm",onClick:()=>b(n.page-1),disabled:n.page<=1||a,"data-testid":"lifecycle-pagination-prev",children:"Previous"}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>b(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"lifecycle-pagination-next",children:"Next"})]})]})]})]})}function Tl({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:ge("w-full caption-bottom text-sm",t),...s})})}function Dl({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:ge("[&_tr]:border-b",t),...s})}function Rl({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:ge("[&_tr:last-child]:border-0",t),...s})}function La({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:ge("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function $t({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:ge("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 _t({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:ge("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function Fk({activityLog:t,loading:s,loadingPage:a,error:r,pagination:n,dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,filterCategory:u,filterSeverity:h,exporting:x,onDateRangeChange:g,onShowCustomDatePickerChange:f,onStartDateChange:j,onEndDateChange:w,onApplyCustomDate:b,onCancelCustomDate:C,onCategoryChange:v,onSeverityChange:N,onClearFilters:k,onPageChange:E,onExport:P,onViewRequest:M}){const y=u!=="all"||h!=="all"||i!=="month"||o||l;return e.jsxs(X,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"user-activity-log-report",children:[e.jsxs(le,{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(qg,{className:"h-5 w-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg text-gray-900",children:"User Activity Log Report"}),e.jsx(je,{className:"text-gray-600",children:"Consolidated user actions and activity history"})]})]}),e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2",onClick:P,disabled:x,"data-testid":"export-activity-button",children:[e.jsx(ss,{className:"w-4 h-4"}),x?"Exporting...":"Download CSV"]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4 flex-wrap",children:[e.jsx(kl,{dateRange:i,customStartDate:o,customEndDate:l,showCustomDatePicker:c,tempCustomStartDate:d,tempCustomEndDate:m,onDateRangeChange:g,onShowCustomDatePickerChange:f,onStartDateChange:j,onEndDateChange:w,onApply:b,onCancel:C,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(Be,{value:u,onValueChange:v,"data-testid":"activity-category-filter",children:[e.jsx(Ve,{className:"w-40",children:e.jsx(Ue,{placeholder:"All Categories"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Categories"}),e.jsx(W,{value:"WORKFLOW",children:"Workflow"}),e.jsx(W,{value:"COLLABORATION",children:"Collaboration"}),e.jsx(W,{value:"DOCUMENT",children:"Document"}),e.jsx(W,{value:"AUTHENTICATION",children:"Authentication"}),e.jsx(W,{value:"SYSTEM",children:"System"}),e.jsx(W,{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(Be,{value:h,onValueChange:N,"data-testid":"activity-severity-filter",children:[e.jsx(Ve,{className:"w-40",children:e.jsx(Ue,{placeholder:"All Severities"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"all",children:"All Severities"}),e.jsx(W,{value:"INFO",children:"Info"}),e.jsx(W,{value:"WARNING",children:"Warning"}),e.jsx(W,{value:"ERROR",children:"Error"}),e.jsx(W,{value:"CRITICAL",children:"Critical"})]})]})]}),y&&e.jsx(R,{variant:"ghost",size:"sm",onClick:k,className:"text-xs","data-testid":"activity-clear-filters",children:"Clear Filters"})]})]}),e.jsx(J,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"activity-loading",children:[e.jsx(Je,{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(Ie,{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(Tl,{children:[e.jsx(Dl,{children:e.jsxs(La,{className:"bg-gray-50",children:[e.jsx($t,{className:"font-semibold",children:"Timestamp"}),e.jsx($t,{className:"font-semibold",children:"User"}),e.jsx($t,{className:"font-semibold",children:"Action"}),e.jsx($t,{className:"font-semibold",children:"Details"}),e.jsx($t,{className:"font-semibold",children:"IP Address"}),e.jsx($t,{className:"font-semibold",children:"Request ID"})]})}),e.jsx(Rl,{children:t.map((A,L)=>e.jsxs(La,{className:"hover:bg-gray-50","data-testid":`activity-row-${L}`,children:[e.jsx(_t,{className:"text-xs font-medium",children:A.timestamp}),e.jsx(_t,{className:"text-sm",children:A.user}),e.jsx(_t,{children:e.jsx(se,{className:Ek(A.action),"data-testid":`activity-action-${L}`,children:A.action})}),e.jsx(_t,{className:"text-sm text-gray-600",children:A.details}),e.jsx(_t,{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(_t,{children:A.requestId!=="-"&&A.requestId!=="System Login"?e.jsx("button",{onClick:()=>{const K=A.requestId;K&&M(K)},className:"hover:underline","data-testid":`activity-request-link-${L}`,children:e.jsx(se,{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:"-"})})]},L))})]}),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(Je,{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(R,{variant:"outline",size:"sm",onClick:()=>E(n.page-1),disabled:n.page<=1||a,"data-testid":"activity-pagination-prev",children:"Previous"}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>E(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"activity-pagination-next",children:"Next"})]})]})]})})]})}function _k({agingWorkflows:t,loading:s,loadingPage:a,error:r,pagination:n,threshold:i,thresholdError:o,dateRange:l,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:u,tempCustomEndDate:h,searchQuery:x,exporting:g,onThresholdChange:f,onThresholdBlur:j,onDateRangeChange:w,onShowCustomDatePickerChange:b,onStartDateChange:C,onEndDateChange:v,onApplyCustomDate:N,onCancelCustomDate:k,onSearchChange:E,onPageChange:P,onExport:M,onViewRequest:y}){return e.jsxs(X,{className:"shadow-lg hover:shadow-xl transition-shadow","data-testid":"workflow-aging-report",children:[e.jsxs(le,{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(To,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg text-gray-900",children:"Workflow Aging Report"}),e.jsx(je,{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(we,{type:"number",min:"1",value:i,onChange:A=>f(A.target.value),onBlur:j,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(se,{variant:"outline",className:"font-semibold","data-testid":"aging-total-badge",children:[n.totalRecords," workflows"]}),e.jsxs(R,{variant:"outline",size:"sm",className:"gap-2",onClick:M,disabled:g,"data-testid":"export-aging-button",children:[e.jsx(ss,{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(kl,{dateRange:l,customStartDate:c,customEndDate:d,showCustomDatePicker:m,tempCustomStartDate:u,tempCustomEndDate:h,onDateRangeChange:w,onShowCustomDatePickerChange:b,onStartDateChange:C,onEndDateChange:v,onApply:N,onCancel:k,testIdPrefix:"aging"}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(ws,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(we,{placeholder:"Search by Request ID, Title, or Initiator...",value:x,onChange:A=>E(A.target.value),className:"pl-10","data-testid":"aging-search-input"})]})]})]}),e.jsx(J,{children:s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"aging-loading",children:[e.jsx(Je,{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(Ie,{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(Tl,{children:[e.jsx(Dl,{children:e.jsxs(La,{className:"bg-gray-50",children:[e.jsx($t,{className:"font-semibold",children:"Request ID"}),e.jsx($t,{className:"font-semibold",children:"Title"}),e.jsx($t,{className:"font-semibold",children:"Initiator"}),e.jsx($t,{className:"font-semibold",children:"Start Date"}),e.jsx($t,{className:"font-semibold",children:"Days Open"}),e.jsx($t,{className:"font-semibold",children:"Current Stage"}),e.jsx($t,{className:"font-semibold",children:"Assigned To"}),e.jsx($t,{className:"font-semibold",children:"Priority"}),e.jsx($t,{className:"font-semibold",children:"Status"})]})}),e.jsx(Rl,{children:t.map(A=>e.jsxs(La,{className:"hover:bg-gray-50","data-testid":`aging-workflow-${A.id}`,children:[e.jsx(_t,{className:"font-medium text-sm",children:e.jsx("button",{onClick:()=>y(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(_t,{className:"text-sm",children:A.title}),e.jsx(_t,{className:"text-sm",children:A.initiator}),e.jsx(_t,{className:"text-sm text-gray-600",children:A.startDate}),e.jsx(_t,{children:e.jsxs(se,{className:`${Ik(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(_t,{className:"text-sm",children:A.currentStage}),e.jsx(_t,{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(_t,{children:e.jsx(se,{className:Hp(A.priority),"data-testid":`aging-priority-${A.id}`,children:A.priority})}),e.jsx(_t,{children:e.jsx(se,{className:Wp(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(Je,{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(R,{variant:"outline",size:"sm",onClick:()=>P(n.page-1),disabled:n.page<=1||a,"data-testid":"aging-pagination-prev",children:"Previous"}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>P(n.page+1),disabled:n.page>=n.totalPages||a,"data-testid":"aging-pagination-next",children:"Next"})]})]})]})})]})}function _i(t="month"){const[s,a]=p.useState(t),[r,n]=p.useState(void 0),[i,o]=p.useState(void 0),[l,c]=p.useState(!1),[d,m]=p.useState(void 0),[u,h]=p.useState(void 0),x=p.useCallback(v=>{const N=v;a(N),N!=="custom"?(n(void 0),o(void 0),m(void 0),h(void 0),c(!1)):(m(r),h(i),c(!0))},[r,i]),g=p.useCallback(()=>{if(d&&u){if(d>u){const v=d;n(u),o(v),m(u),h(v)}else n(d),o(u);c(!1)}},[d,u]),f=p.useCallback(()=>{c(!1),m(r),h(i),(!r||!i)&&(n(void 0),o(void 0),a("month"))},[r,i]),j=p.useCallback(v=>{v?(m(v),u&&v>u&&h(v)):m(void 0)},[u]),w=p.useCallback(v=>{v?(h(v),d&&vr&&i?`${Ne(r,"MMM d, yyyy")} - ${Ne(i,"MMM d, yyyy")}`:"Select dates",[r,i]),C=p.useCallback(()=>{a("month"),n(void 0),o(void 0),c(!1),m(void 0),h(void 0)},[]);return{dateRange:s,customStartDate:r,customEndDate:i,showCustomDatePicker:l,tempCustomStartDate:d,tempCustomEndDate:u,setShowCustomDatePicker:c,handleDateRangeChange:x,handleApplyCustomDate:g,handleCancelCustomDate:f,handleStartDateChange:j,handleEndDateChange:w,getDisplayDateRange:b,reset:C}}function Lk(t){if(!t&&t!==0)return"N/A";const s=8;if(t0?`${a}d ${Et(r)}`:`${a}d`}function Gp(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 Da(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 Kp(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 Ok=10;function $k({dateRange:t,customStartDate:s,customEndDate:a}){const[r,n]=p.useState([]),[i,o]=p.useState(!0),[l,c]=p.useState(!1),[d,m]=p.useState(null),[u,h]=p.useState({page:1,totalPages:1,totalRecords:0}),x=p.useRef(!0),g=p.useCallback(async(f=1)=>{const j=f===1&&x.current;try{j?o(!0):c(!0),m(null);const w=await xt.getLifecycleReport(f,Ok,t,s,a),b=w.lifecycleData.map(C=>{const v=Lk(C.overallTATHours);return{id:C.requestNumber,requestId:C.requestId,title:C.title,priority:C.priority||"medium",status:C.status,initiator:C.initiatorName||"Unknown",initDate:Gp(C.submissionDate),currentStage:C.currentStageName||`Level ${C.currentLevel}`,overallTAT:v,currentLevel:C.currentLevel,totalLevels:C.totalLevels,breachCount:C.breachCount||0}});n(b),h({page:w.pagination.currentPage,totalPages:w.pagination.totalPages,totalRecords:w.pagination.totalRecords})}catch(w){console.error("Failed to fetch lifecycle data:",w),m((w==null?void 0:w.message)||"Failed to load lifecycle data")}finally{j?o(!1):c(!1)}j&&(x.current=!1)},[t,s,a]);return p.useEffect(()=>{t==="custom"&&(!s||!a)||g(1)},[t,s,a]),{lifecycleRequests:r,loading:i,loadingPage:l,error:d,pagination:u,fetchData:g}}const Bk=20;function Uk({dateRange:t,customStartDate:s,customEndDate:a,filterCategory:r,filterSeverity:n}){const[i,o]=p.useState([]),[l,c]=p.useState(!0),[d,m]=p.useState(!1),[u,h]=p.useState(null),[x,g]=p.useState({page:1,totalPages:1,totalRecords:0}),f=p.useRef(!0),j=p.useCallback(async(w=1)=>{const b=w===1&&f.current;try{b?c(!0):m(!0),h(null);const C=await xt.getActivityLogReport(w,Bk,t,void 0,void 0,r&&r!=="all"?r:void 0,n&&n!=="all"?n:void 0,s,a),v=C.activities.map(N=>{const k=Kp(N.type||"",N.details),E=(N.type||"").toLowerCase()==="login"||N.requestId==="00000000-0000-0000-0000-000000000001"||N.requestId==="SYSTEM_LOGIN",P=E?N.details||"User login":N.requestTitle||N.requestNumber||N.details||"N/A";return{timestamp:N.timestamp?Gp(N.timestamp):"N/A",user:N.userName||"Unknown",action:k,details:P,ip:N.ipAddress||"N/A",userAgent:N.userAgent||null,requestId:E?"System Login":N.requestNumber||N.requestId||"-",userId:N.userId}});o(v),g({page:C.pagination.currentPage,totalPages:C.pagination.totalPages,totalRecords:C.pagination.totalRecords})}catch(C){console.error("Failed to fetch activity data:",C),h((C==null?void 0:C.message)||"Failed to load activity data")}finally{b?c(!1):m(!1)}b&&(f.current=!1)},[r,n,t,s,a]);return p.useEffect(()=>{t==="custom"&&(!s||!a)||j(1)},[r,n,t,s,a]),{activityLog:i,loading:l,loadingPage:d,error:u,pagination:x,fetchData:j}}const Vk=20;function zk({threshold:t,dateRange:s,customStartDate:a,customEndDate:r,searchQuery:n=""}){const[i,o]=p.useState([]),[l,c]=p.useState(!0),[d,m]=p.useState(!1),[u,h]=p.useState(null),[x,g]=p.useState({page:1,totalPages:1,totalRecords:0}),f=p.useRef(!0),j=p.useCallback(async(b=1)=>{const C=b===1&&f.current;try{C?c(!0):m(!0),h(null);const v=parseInt(t,10);if(isNaN(v)||v<1){h("Please enter a valid threshold (minimum 1 day)");return}const N=await xt.getWorkflowAgingReport(v,b,Vk,s,a,r),k=N.agingData.map(E=>({id:E.requestNumber||E.requestId,requestId:E.requestId,title:E.title,initiator:E.initiatorName||"Unknown",startDate:E.submissionDate?new Date(E.submissionDate).toLocaleDateString():"N/A",daysOpen:E.daysOpen,currentStage:E.currentStageName||`Level ${E.currentLevel}`,assignedTo:E.currentApproverName||"N/A",priority:E.priority||"medium",status:E.status||"pending"}));o(k),g({page:N.pagination.currentPage,totalPages:N.pagination.totalPages,totalRecords:N.pagination.totalRecords})}catch(v){console.error("Failed to fetch aging data:",v),h((v==null?void 0:v.message)||"Failed to load aging data")}finally{C?c(!1):m(!1)}C&&(f.current=!1)},[t,s,a,r]),w=p.useMemo(()=>i.filter(b=>{var v,N,k;if(!n)return!0;const C=n.toLowerCase();return((v=b.id)==null?void 0:v.toLowerCase().includes(C))||((N=b.title)==null?void 0:N.toLowerCase().includes(C))||((k=b.initiator)==null?void 0:k.toLowerCase().includes(C))}),[i,n]);return p.useEffect(()=>{s==="custom"&&(!a||!r)||j(1)},[t,s,a,r]),{agingWorkflows:w,loading:l,loadingPage:d,error:u,pagination:x,fetchData:j}}function Hk(t="7"){const[s,a]=p.useState(t),[r,n]=p.useState(null),i=p.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=p.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 Wk(t,s,a){const r=await xt.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?Da(i.submissionDate):"N/A",c=i.closureDate?Da(i.closureDate):"N/A",d=i.overallTATHours||0,m=d>0?(d/8).toFixed(2):"0",u=i.totalLevels||1,h=Math.min(Math.max(1,i.currentLevel||1),u),x=(o==null?void 0:o.approvals)||[];if(x.length===0){const g=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,l,c,u.toString(),h.toString(),d.toString(),m,(i.breachCount||0).toString(),"N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(g.join(","))}else x.forEach(g=>{const f=g.levelStartTime?Da(g.levelStartTime):"N/A",j=g.levelEndTime||g.completedAt?Da(g.levelEndTime||g.completedAt):"N/A",w=g.tatHours||0,b=g.tatDays||(w>0?(w/8).toFixed(2):"0");let C="N/A",v="N/A",N="N/A",k="N/A";if(g.levelStartTime){const P=new Date(g.levelStartTime);if(v=(((g.levelEndTime||g.completedAt?new Date(g.levelEndTime||g.completedAt):new Date).getTime()-P.getTime())/(1e3*60*60)).toFixed(2),w>0){const A=parseFloat(v);N=Math.max(0,w-A).toFixed(2),k=(A/w*100).toFixed(2),g.status==="APPROVED"||g.status==="REJECTED"?C=A<=w?"Compliant":"Breached":g.status==="IN_PROGRESS"||g.status==="PENDING"?C=A<=w?"On Track":"At Risk":C="N/A"}}const E=[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(),d.toString(),m,(i.breachCount||0).toString(),(g.levelNumber||"").toString(),`"${(g.levelName||`Level ${g.levelNumber}`).replace(/"/g,'""')}"`,`"${(g.approverName||"N/A").replace(/"/g,'""')}"`,`"${(g.approverEmail||"N/A").replace(/"/g,'""')}"`,g.status||"PENDING",f,j,w.toString(),b.toString(),C,v,N,k];n.push(E.join(","))})}catch(o){console.error(`Failed to fetch details for request ${i.requestNumber}:`,o);const l=i.submissionDate?Da(i.submissionDate):"N/A",c=i.overallTATHours||0,d=c>0?(c/8).toFixed(2):"0",m=i.totalLevels||1,u=Math.min(Math.max(1,i.currentLevel||1),m),h=[i.requestNumber||"",`"${(i.title||"").replace(/"/g,'""')}"`,i.priority||"medium",i.status||"",`"${(i.initiatorName||"Unknown").replace(/"/g,'""')}"`,l,"N/A",m.toString(),u.toString(),c.toString(),d,(i.breachCount||0).toString(),"Error","Error fetching details","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A"];n.push(h.join(","))}Pl(n,`lifecycle-report-end-to-end-${new Date().toISOString().split("T")[0]}.csv`)}async function Gk(t,s,a,r,n){const i=await xt.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=Kp(l.type||"",l.details),m=[l.timestamp?Da(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(m.join(","))}),Pl(o,`activity-log-report-${new Date().toISOString().split("T")[0]}.csv`)}async function Kk(t,s,a,r){const n=await xt.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?Da(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(","))}),Pl(i,`workflow-aging-report-${new Date().toISOString().split("T")[0]}.csv`)}function Pl(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 Yk(){const[t,s]=p.useState(!1),[a,r]=p.useState(!1),[n,i]=p.useState(!1),o=p.useCallback(async(d,m,u)=>{try{s(!0),await Wk(d,m,u)}catch(h){console.error("Failed to export lifecycle data:",h),alert("Failed to export lifecycle data. Please try again.")}finally{s(!1)}},[]),l=p.useCallback(async(d,m,u,h,x)=>{try{r(!0),await Gk(d,m,u,h,x)}catch(g){console.error("Failed to export activity data:",g),alert("Failed to export activity data. Please try again.")}finally{r(!1)}},[]),c=p.useCallback(async(d,m,u,h)=>{try{i(!0),await Kk(d,m,u,h)}catch(x){console.error("Failed to export aging data:",x),alert("Failed to export aging data. Please try again.")}finally{i(!1)}},[]);return{exportingLifecycle:t,exportingActivity:a,exportingAging:n,handleExportLifecycle:o,handleExportActivity:l,handleExportAging:c}}function Zk({onBack:t}){const s=ya(),[a,r]=p.useState(""),[n,i]=p.useState("all"),[o,l]=p.useState("all"),c=_i("month"),d=_i("month"),m=_i("month"),u=Hk("7"),h=$k({dateRange:c.dateRange,customStartDate:c.customStartDate,customEndDate:c.customEndDate}),x=Uk({dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,filterCategory:n,filterSeverity:o}),g=zk({threshold:u.threshold,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,searchQuery:a}),f=Yk(),j=p.useCallback(()=>{t?t():s("/dashboard")},[t,s]),w=p.useCallback(k=>{const{navigateToRequest:E}=require("@/utils/requestNavigation");E({requestId:k,navigate:s})},[s]),b=p.useCallback(()=>{f.handleExportLifecycle(c.dateRange,c.customStartDate,c.customEndDate)},[f,c]),C=p.useCallback(()=>{f.handleExportActivity(d.dateRange,d.customStartDate,d.customEndDate,n,o)},[f,d,n,o]),v=p.useCallback(()=>{const k=parseInt(u.threshold,10);!isNaN(k)&&k>=1&&f.handleExportAging(k,m.dateRange,m.customStartDate,m.customEndDate)},[f,u.threshold,m]),N=p.useCallback(()=>{i("all"),l("all"),d.reset()},[d]);return e.jsx("div",{className:"flex-1 p-3 lg:p-6 overflow-auto min-w-0","data-testid":"detailed-reports",children:e.jsxs("div",{className:"space-y-6 max-w-7xl mx-auto p-4",children:[e.jsx(Pk,{onBack:j}),e.jsx(Mk,{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:b,onViewRequest:w}),e.jsx(Fk,{activityLog:x.activityLog,loading:x.loading,loadingPage:x.loadingPage,error:x.error,pagination:x.pagination,dateRange:d.dateRange,customStartDate:d.customStartDate,customEndDate:d.customEndDate,showCustomDatePicker:d.showCustomDatePicker,tempCustomStartDate:d.tempCustomStartDate,tempCustomEndDate:d.tempCustomEndDate,filterCategory:n,filterSeverity:o,exporting:f.exportingActivity,onDateRangeChange:d.handleDateRangeChange,onShowCustomDatePickerChange:d.setShowCustomDatePicker,onStartDateChange:d.handleStartDateChange,onEndDateChange:d.handleEndDateChange,onApplyCustomDate:d.handleApplyCustomDate,onCancelCustomDate:d.handleCancelCustomDate,onCategoryChange:i,onSeverityChange:l,onClearFilters:N,onPageChange:x.fetchData,onExport:C,onViewRequest:w}),e.jsx(_k,{agingWorkflows:g.agingWorkflows,loading:g.loading,loadingPage:g.loadingPage,error:g.error,pagination:g.pagination,threshold:u.threshold,thresholdError:u.thresholdError,dateRange:m.dateRange,customStartDate:m.customStartDate,customEndDate:m.customEndDate,showCustomDatePicker:m.showCustomDatePicker,tempCustomStartDate:m.tempCustomStartDate,tempCustomEndDate:m.tempCustomEndDate,searchQuery:a,exporting:f.exportingAging,onThresholdChange:u.handleThresholdChange,onThresholdBlur:u.handleThresholdBlur,onDateRangeChange:m.handleDateRangeChange,onShowCustomDatePickerChange:m.setShowCustomDatePicker,onStartDateChange:m.handleStartDateChange,onEndDateChange:m.handleEndDateChange,onApplyCustomDate:m.handleApplyCustomDate,onCancelCustomDate:m.handleCancelCustomDate,onSearchChange:r,onPageChange:g.fetchData,onExport:v,onViewRequest:w})]})})}function Xk({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(Q,{htmlFor:"default-period",children:"Default Reporting Period"}),e.jsxs(Be,{value:t,onValueChange:a,children:[e.jsx(Ve,{id:"default-period",children:e.jsx(Ue,{})}),e.jsx(ze,{children:n.map(i=>e.jsx(W,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"refresh-interval",children:"Auto-Refresh Interval (minutes)"}),e.jsx(we,{id:"refresh-interval",type:"number",min:"1",max:"60",value:s,onChange:i=>r(parseInt(i.target.value)||5)})]})]})}function Jk({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(us,{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(us,{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(us,{checked:a,onCheckedChange:i})]})]})}const Qk=["CSV","Excel","PDF","JSON"];function qk({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(Q,{children:"Allowed Export Formats"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:Qk.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(bl,{id:`export-${r}`,checked:t.includes(r),onCheckedChange:n=>a(r,n)}),e.jsx(Q,{htmlFor:`export-${r}`,className:"text-sm cursor-pointer",children:r})]},r))})]})}function eT({dataRetention:t,onDataRetentionChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"data-retention",children:"Historical Data Retention (months)"}),e.jsx(we,{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 tT(){const[t,s]=p.useState({defaultPeriod:"This Month",refreshInterval:5,autoRefresh:!0,realTimeUpdates:!0,dataExport:!0,exportFormats:["CSV","Excel","PDF"],dataRetention:24}),a=()=>{ne.success("Analytics configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(X,{children:[e.jsxs(le,{children:[e.jsx(ce,{children:"Analytics & Reporting Configuration"}),e.jsx(je,{children:"Configure default reporting periods, auto-refresh, export settings, and data retention"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(Xk,{defaultPeriod:t.defaultPeriod,refreshInterval:t.refreshInterval,onDefaultPeriodChange:n=>r({defaultPeriod:n}),onRefreshIntervalChange:n=>r({refreshInterval:n})}),e.jsx(It,{}),e.jsx(Jk,{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(It,{}),e.jsx(qk,{exportFormats:t.exportFormats,onExportFormatsChange:n=>r({exportFormats:n})}),e.jsx(eT,{dataRetention:t.dataRetention,onDataRetentionChange:n=>r({dataRetention:n})}),e.jsxs(R,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(fa,{className:"w-4 h-4 mr-2"}),"Save Analytics Configuration"]})]})]})}const sT=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"}},aT=t=>t.split(" ").map(s=>s[0]).join("").toUpperCase().substring(0,2);function rT({users:t,onEdit:s,onToggleStatus:a,onDelete:r}){return e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Tl,{children:[e.jsx(Dl,{children:e.jsxs(La,{children:[e.jsx($t,{children:"User"}),e.jsx($t,{children:"Role"}),e.jsx($t,{children:"Department"}),e.jsx($t,{children:"Status"}),e.jsx($t,{className:"text-right",children:"Actions"})]})}),e.jsx(Rl,{children:t.length===0?e.jsx(La,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):t.map(n=>e.jsxs(La,{className:"hover:bg-muted/50",children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Bt,{className:"size-10",children:e.jsx(Ut,{className:"bg-re-green text-white",children:aT(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(_t,{children:e.jsx(se,{className:sT(n.role),children:n.role})}),e.jsx(_t,{children:n.department}),e.jsx(_t,{children:e.jsxs(se,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Er,{className:"w-3 h-3 mr-1"}),n.status]})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>s(n.id),className:"h-8",children:e.jsx($n,{className:"w-4 h-4"})}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>a(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8",children:e.jsx(ef,{className:"w-4 h-4"})}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>r(n.id),disabled:n.role.toUpperCase()==="ADMIN",className:"h-8 text-destructive hover:text-destructive",children:e.jsx(Do,{className:"w-4 h-4"})})]})})]},n.id))})]})})}function nT({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 iT(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function oT(){const[t,s]=p.useState(""),[a,r]=p.useState([]),[n,i]=p.useState(!1),[o,l]=p.useState(null),[c,d]=p.useState("USER"),[m,u]=p.useState(!1),[h,x]=p.useState(!1),[g,f]=p.useState(null),[j,w]=p.useState([]),[b,C]=p.useState(!1),[v,N]=p.useState({admins:0,management:0,users:0,total:0,active:0,inactive:0}),[k,E]=p.useState("ELEVATED"),[P,M]=p.useState(1),[y,A]=p.useState(1),[L,K]=p.useState(0),O=10,$=p.useRef(null),T=p.useCallback(iT(async U=>{var ee,ie,de;if(!U||!U.startsWith("@")||U.length<2){r([]),i(!1);return}i(!0);try{const Ae=U.slice(1),Se=((ee=(await js.searchUsers(Ae,20)).data)==null?void 0:ee.data)||[];r(Se)}catch(Ae){console.error("Search failed:",Ae),f({type:"error",text:((de=(ie=Ae.response)==null?void 0:ie.data)==null?void 0:de.message)||"Failed to search users"})}finally{i(!1)}},300),[]),S=U=>{const ee=U.target.value;s(ee),T(ee)},D=async U=>{var ee,ie;try{const de=j.find(Ye=>Ye.email.toLowerCase()===U.toLowerCase());if(de)return de.role;const Se=(((ie=(ee=(await js.getUsersByRole("ALL",1,1e3)).data)==null?void 0:ee.data)==null?void 0:ie.users)||[]).find(Ye=>{var Ge;return((Ge=Ye.email)==null?void 0:Ge.toLowerCase())===U.toLowerCase()});return Se&&Se.role?Se.role:null}catch(de){return console.error("Failed to fetch user role:",de),null}},I=async U=>{l(U),s(U.email),r([]),x(!0);try{const ee=await D(U.email);d(ee||"USER")}catch(ee){console.error("Failed to fetch user role:",ee),d("USER")}finally{x(!1)}},_=async()=>{var U,ee;if(!o||!c){f({type:"error",text:"Please select a user and role"});return}u(!0),f(null);try{await js.assignRole(o.email,c),f({type:"success",text:`Successfully assigned ${c} role to ${o.displayName||o.email}`}),l(null),s(""),d("USER"),await F(),await G(),ne.success("Role assigned successfully")}catch(ie){console.error("Role assignment failed:",ie);const de=((ee=(U=ie.response)==null?void 0:U.data)==null?void 0:ee.error)||"Failed to assign role";f({type:"error",text:de}),ne.error(de)}finally{u(!1)}},F=async(U=P)=>{var ee,ie,de,Ae,We,Se;C(!0);try{const Ye=await js.getUsersByRole(k,U,O),Ge=((ie=(ee=Ye.data)==null?void 0:ee.data)==null?void 0:ie.users)||[],Oe=(Ae=(de=Ye.data)==null?void 0:de.data)==null?void 0:Ae.pagination,ct=(Se=(We=Ye.data)==null?void 0:We.data)==null?void 0:Se.summary;w(Ge.map(te=>({userId:te.userId,email:te.email,displayName:te.displayName||te.email,role:te.role||"USER",department:te.department,designation:te.designation,isActive:te.isActive!==!1}))),Oe&&(M(Oe.currentPage),A(Oe.totalPages),K(Oe.totalUsers)),ct&&N(te=>({...te,admins:ct.ADMIN||0,management:ct.MANAGEMENT||0,users:ct.USER||0,total:(ct.ADMIN||0)+(ct.MANAGEMENT||0)+(ct.USER||0)}))}catch(Ye){console.error("Failed to fetch users:",Ye),ne.error("Failed to load users")}finally{C(!1)}},G=async()=>{var U,ee,ie,de,Ae,We;try{const Se=await js.getRoleStatistics(),Ye=((ee=(U=Se.data)==null?void 0:U.data)==null?void 0:ee.statistics)||((ie=Se.data)==null?void 0:ie.statistics)||[],Ge={admins:parseInt(((de=Ye.find(Oe=>Oe.role==="ADMIN"))==null?void 0:de.count)||"0"),management:parseInt(((Ae=Ye.find(Oe=>Oe.role==="MANAGEMENT"))==null?void 0:Ae.count)||"0"),users:parseInt(((We=Ye.find(Oe=>Oe.role==="USER"))==null?void 0:We.count)||"0")};N(Oe=>({...Oe,...Ge,total:Ge.admins+Ge.management+Ge.users,active:Oe.active||Ge.admins+Ge.management+Ge.users,inactive:Oe.inactive||0}))}catch(Se){console.error("Failed to fetch statistics:",Se)}};p.useEffect(()=>{F(1),G()},[k]);const B=U=>{E(U),M(1)},re=U=>{F(U)},ae=async(U,ee)=>{var ie,de;try{await js.updateUserRole(U,ee),ne.success("User role updated successfully"),await F(),await G()}catch(Ae){console.error("Failed to update user role:",Ae),ne.error(((de=(ie=Ae.response)==null?void 0:ie.data)==null?void 0:de.error)||"Failed to update user role")}},V=async U=>{j.find(ie=>ie.userId===U)&&ne.info("User status toggle functionality coming soon")},Y=async U=>{const ee=j.find(ie=>ie.userId===U);if(ee){if(ee.role==="ADMIN"){ne.error("Cannot delete admin user");return}ne.info("User deletion functionality coming soon")}};p.useEffect(()=>{const U=ee=>{$.current&&!$.current.contains(ee.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",U),()=>{document.removeEventListener("mousedown",U)}},[a]);const Z={total:v.total,active:v.active,inactive:v.inactive,admins:v.admins};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(nT,{stats:Z}),e.jsxs(X,{children:[e.jsx(le,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Assign User Role"}),e.jsx(je,{children:"Search for a user in Okta and assign them a role"})]}),e.jsx(R,{onClick:_,disabled:!o||m,className:"bg-re-green hover:bg-re-green/90",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ws,{className:"w-4 h-4 mr-2"}),"Assign Role"]})})]})}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",ref:$,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ws,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(we,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:S,className:"pl-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),n&&e.jsx(Je,{className:"absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-re-green animate-spin"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Start with @ to search users (e.g., @john)"}),a.length>0&&e.jsxs("div",{className:"border rounded-lg shadow-lg bg-white max-h-60 overflow-y-auto",children:[e.jsx("div",{className:"sticky top-0 bg-muted px-4 py-2 border-b",children:e.jsxs("p",{className:"text-xs font-semibold text-muted-foreground",children:[a.length," user",a.length>1?"s":""," found"]})}),e.jsx("div",{className:"p-3",children:a.map(U=>e.jsxs("button",{onClick:()=>I(U),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:U.displayName||U.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:U.email}),U.department&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[U.department,U.designation?` • ${U.designation}`:""]})]},U.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(Je,{className:"w-3 h-3 animate-spin"}),"Checking current role..."]})]})]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>{l(null),s(""),d("USER"),x(!1)},children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Select Role"}),e.jsxs(Be,{value:c,onValueChange:U=>d(U),disabled:h,children:[e.jsx(Ve,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ue,{placeholder:h?"Loading current role...":"Select role"})}),e.jsxs(ze,{className:"rounded-lg",children:[e.jsx(W,{value:"USER",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(W,{value:"MANAGEMENT",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(W,{value:"ADMIN",className:"p-3 rounded-lg my-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Va,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),g&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${g.type==="success"?"border-green-200 bg-green-50":"border-red-200 bg-red-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[g.type==="success"?e.jsx(Ce,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(Ie,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${g.type==="success"?"text-green-800":"text-red-800"}`,children:g.text})]})})]})]}),e.jsxs(X,{children:[e.jsx(le,{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(ce,{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-5 h-5 text-re-green"}),"User Management"]}),e.jsxs(je,{children:["View and manage user accounts and roles (",L," ",k!=="ALL"&&k!=="ELEVATED"?k.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(Be,{value:k,onValueChange:B,children:[e.jsx(Ve,{className:"w-[200px] border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ue,{placeholder:"Filter by role"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",v.admins+v.management,")"]})]})}),e.jsx(W,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Va,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",v.admins,")"]})]})}),e.jsx(W,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",v.management,")"]})]})}),e.jsx(W,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",v.users,")"]})]})}),e.jsx(W,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",v.admins+v.management+v.users,")"]})]})})]})]})})]})}),e.jsx(J,{className:"pt-6",children:b?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Je,{className:"w-6 h-6 animate-spin text-re-green mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading users..."})]}):j.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(Pt,{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(rT,{users:j.map(U=>({id:U.userId,name:U.displayName,email:U.email,role:U.role,department:U.department||"N/A",status:U.isActive?"active":"inactive"})),onEdit:U=>{const ee=j.find(ie=>ie.userId===U);if(ee){const ie=ee.role==="USER"?"MANAGEMENT":ee.role==="MANAGEMENT"?"ADMIN":"USER";ae(U,ie)}},onToggleStatus:V,onDelete:Y}),y>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 ",(P-1)*O+1," to ",Math.min(P*O,L)," of ",L," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{variant:"outline",size:"sm",onClick:()=>re(P-1),disabled:P===1,children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,y)},(U,ee)=>{let ie;return y<=5||P<=3?ie=ee+1:P>=y-2?ie=y-4+ee:ie=P-2+ee,e.jsx(R,{variant:P===ie?"default":"outline",size:"sm",onClick:()=>re(ie),className:`w-9 h-9 p-0 ${P===ie?"bg-re-green hover:bg-re-green/90":""}`,children:ie},ie)})}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>re(P+1),disabled:P===y,children:"Next"})]})]})]})})]})]})}function lT({expressHours:t,standardHours:s,onExpressChange:a,onStandardChange:r}){return e.jsxs(X,{className:"border-0 shadow-sm",children:[e.jsxs(le,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wo,{className:"w-5 h-5 text-re-green"}),e.jsx(ce,{className:"text-base font-semibold",children:"Priority TAT Settings"})]}),e.jsx(je,{className:"text-sm",children:"Set default turnaround time in hours for each priority level"})]}),e.jsx(J,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"tat-express",className:"text-sm font-medium",children:"Express Priority (hours)"}),e.jsx(we,{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(He,{className:"w-3 h-3"}),"Critical/Emergency requests (24/7, includes weekends)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"tat-standard",className:"text-sm font-medium",children:"Standard Priority (hours)"}),e.jsx(we,{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(He,{className:"w-3 h-3"}),"Regular priority requests (working hours only, excludes weekends & holidays)"]})]})]})})]})}function cT({reminderThreshold1:t,reminderThreshold2:s,onReminderThreshold1Change:a,onReminderThreshold2Change:r}){return e.jsxs(X,{className:"border-0 shadow-sm",children:[e.jsxs(le,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-5 h-5 text-re-green"}),e.jsx(ce,{className:"text-base font-semibold",children:"Auto-Reminder & Escalation"})]}),e.jsx(je,{className:"text-sm",children:"Configure automatic reminder thresholds based on TAT percentage"})]}),e.jsx(J,{className:"space-y-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Q,{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(xo,{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(cs,{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(Q,{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(xo,{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 wr=[{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 dT({workStartHour:t,workEndHour:s,workStartDay:a,workEndDay:r,onWorkStartHourChange:n,onWorkEndHourChange:i,onWorkStartDayChange:o,onWorkEndDayChange:l}){var c,d,m;return e.jsxs(X,{className:"border-0 shadow-sm",children:[e.jsxs(le,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-5 h-5 text-re-green"}),e.jsx(ce,{className:"text-base font-semibold",children:"Working Hours Configuration"})]}),e.jsx(je,{className:"text-sm",children:"Define your organization's working hours and days for TAT calculations"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"work-start-hour",className:"text-sm font-medium",children:"Working Day Start Hour"}),e.jsx(we,{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(He,{className:"w-3 h-3"}),"24-hour format (0-23). Default: 9 AM"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"work-end-hour",className:"text-sm font-medium",children:"Working Day End Hour"}),e.jsx(we,{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(He,{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(Q,{htmlFor:"work-start-day",className:"text-sm font-medium",children:"Working Week Start Day"}),e.jsxs(Be,{value:a.toString(),onValueChange:u=>o(parseInt(u)),children:[e.jsx(Ve,{id:"work-start-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ue,{placeholder:"Select start day"})}),e.jsx(ze,{children:wr.map(u=>e.jsx(W,{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(Q,{htmlFor:"work-end-day",className:"text-sm font-medium",children:"Working Week End Day"}),e.jsxs(Be,{value:r.toString(),onValueChange:u=>l(parseInt(u)),children:[e.jsx(Ve,{id:"work-end-day",className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20",children:e.jsx(Ue,{placeholder:"Select end day"})}),e.jsx(ze,{children:wr.map(u=>e.jsx(W,{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=wr.find(u=>u.value===a))==null?void 0:c.label} only`:` ${(d=wr.find(u=>u.value===a))==null?void 0:d.label} to ${(m=wr.find(u=>u.value===r))==null?void 0:m.label}`]})})]})]})}function mT(){const[t,s]=p.useState(!0),[a,r]=p.useState(!1),[n,i]=p.useState({expressHours:24,standardHours:72,reminderThreshold1:50,reminderThreshold2:75,workStartHour:9,workEndHour:18,workStartDay:1,workEndDay:5});p.useEffect(()=>{o()},[]);const o=async()=>{try{s(!0);const d=await Yn("TAT_SETTINGS"),m={};d.forEach(u=>{m[u.configKey]=u.configValue}),i({expressHours:parseInt(m.DEFAULT_TAT_EXPRESS_HOURS||"24"),standardHours:parseInt(m.DEFAULT_TAT_STANDARD_HOURS||"72"),reminderThreshold1:parseInt(m.TAT_REMINDER_THRESHOLD_1||"50"),reminderThreshold2:parseInt(m.TAT_REMINDER_THRESHOLD_2||"75"),workStartHour:parseInt(m.WORK_START_HOUR||"9"),workEndHour:parseInt(m.WORK_END_HOUR||"18"),workStartDay:parseInt(m.WORK_START_DAY||"1"),workEndDay:parseInt(m.WORK_END_DAY||"5")})}catch(d){console.error("Failed to load TAT configurations:",d),ne.error("Failed to load TAT configurations")}finally{s(!1)}},l=async()=>{var d,m;try{r(!0),await Promise.all([os("DEFAULT_TAT_EXPRESS_HOURS",n.expressHours.toString()),os("DEFAULT_TAT_STANDARD_HOURS",n.standardHours.toString()),os("TAT_REMINDER_THRESHOLD_1",n.reminderThreshold1.toString()),os("TAT_REMINDER_THRESHOLD_2",n.reminderThreshold2.toString()),os("WORK_START_HOUR",n.workStartHour.toString()),os("WORK_END_HOUR",n.workEndHour.toString()),os("WORK_START_DAY",n.workStartDay.toString()),os("WORK_END_DAY",n.workEndDay.toString())]),ne.success("TAT configuration saved successfully"),await o()}catch(u){console.error("Failed to save TAT configuration:",u),ne.error(((m=(d=u.response)==null?void 0:d.data)==null?void 0:m.error)||"Failed to save TAT configuration")}finally{r(!1)}},c=d=>{i(m=>({...m,...d}))};return t?e.jsx(X,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(J,{className:"p-12 text-center",children:[e.jsx(Je,{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(X,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(le,{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(He,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg font-semibold text-gray-900",children:"Turn Around Time (TAT) Configuration"}),e.jsx(je,{className:"text-sm text-gray-600",children:"Set default TAT hours per priority level, working hours, and configure auto-escalation thresholds"})]})]})}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(lT,{expressHours:n.expressHours,standardHours:n.standardHours,onExpressChange:d=>c({expressHours:d}),onStandardChange:d=>c({standardHours:d})}),e.jsx(It,{}),e.jsx(dT,{workStartHour:n.workStartHour,workEndHour:n.workEndHour,workStartDay:n.workStartDay,workEndDay:n.workEndDay,onWorkStartHourChange:d=>c({workStartHour:d}),onWorkEndHourChange:d=>c({workEndHour:d}),onWorkStartDayChange:d=>c({workStartDay:d}),onWorkEndDayChange:d=>c({workEndDay:d})}),e.jsx(It,{}),e.jsx(cT,{reminderThreshold1:n.reminderThreshold1,reminderThreshold2:n.reminderThreshold2,onReminderThreshold1Change:d=>c({reminderThreshold1:d}),onReminderThreshold2Change:d=>c({reminderThreshold2:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(R,{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(Je,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(fa,{className:"w-4 h-4 mr-2"}),"Save TAT Settings"]})})})]})]})}function uT({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(us,{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(us,{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(us,{checked:a,onCheckedChange:i})]})]})}function hT({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(Q,{htmlFor:"notification-frequency",children:"Notification Frequency"}),e.jsxs(Be,{value:t,onValueChange:a,children:[e.jsx(Ve,{id:"notification-frequency",children:e.jsx(Ue,{placeholder:"Select frequency"})}),e.jsxs(ze,{children:[e.jsx(W,{value:"Immediate",children:"Immediate"}),e.jsx(W,{value:"Hourly",children:"Hourly"}),e.jsx(W,{value:"Daily",children:"Daily"}),e.jsx(W,{value:"Weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"reminder-frequency",children:"Reminder Frequency (hours)"}),e.jsx(we,{id:"reminder-frequency",type:"number",min:"1",max:"168",value:s,onChange:n=>r(parseInt(n.target.value)||12)})]})]})}function pT({emailTemplate:t,onEmailTemplateChange:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"email-template",children:"Email Template Message"}),e.jsx(ns,{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 xT(){const[t,s]=p.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=()=>{ne.success("Notification configuration saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(X,{children:[e.jsxs(le,{children:[e.jsx(ce,{children:"Notification Configuration"}),e.jsx(je,{children:"Configure notification channels, frequency, and message templates"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(uT,{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(It,{}),e.jsx(hT,{notificationFrequency:t.notificationFrequency,reminderFrequency:t.reminderFrequency,onNotificationFrequencyChange:n=>r({notificationFrequency:n}),onReminderFrequencyChange:n=>r({reminderFrequency:n})}),e.jsx(pT,{emailTemplate:t.emailTemplate,onEmailTemplateChange:n=>r({emailTemplate:n})}),e.jsxs(R,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(fa,{className:"w-4 h-4 mr-2"}),"Save Notification Settings"]})]})]})}function gT({maxFileSizeMB:t,retentionDays:s,onMaxFileSizeChange:a,onRetentionDaysChange:r}){const n=Math.round(s/365*10)/10;return e.jsxs(X,{className:"border-0 shadow-sm",children:[e.jsxs(le,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{className:"w-5 h-5 text-re-green"}),e.jsx(ce,{className:"text-base font-semibold",children:"Upload & Retention Settings"})]}),e.jsx(je,{className:"text-sm",children:"Configure file size limits and document retention period"})]}),e.jsx(J,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"max-upload",className:"text-sm font-medium",children:"Maximum Upload Size (MB)"}),e.jsx(we,{id:"max-upload",type:"number",min:"1",max:"100",value:t,onChange:i=>a(parseInt(i.target.value)||10),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ys,{className:"w-3 h-3"}),"Maximum allowed file size for document uploads"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"retention",className:"text-sm font-medium",children:"Retention Period (Days)"}),e.jsx(we,{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(Bn,{className:"w-3 h-3"}),"Days to retain documents after workflow closure (",n," years)"]})]})]})})]})}const fT=[{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 yT({allowedFileTypes:t,onAllowedFileTypesChange:s}){const a=t.split(",").map(o=>o.trim().toLowerCase()),r=(o,l)=>{const c=new Set(a);l?o.forEach(d=>c.add(d)):o.forEach(d=>c.delete(d)),s(Array.from(c).join(","))},n=o=>o.some(l=>a.includes(l)),i=o=>{s(o)};return e.jsxs(X,{className:"border-0 shadow-sm",children:[e.jsxs(le,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ao,{className:"w-5 h-5 text-re-green"}),e.jsx(ce,{className:"text-base font-semibold",children:"Allowed File Types"})]}),e.jsx(je,{className:"text-sm",children:"Select which file types are allowed for upload"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:fT.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(Q,{htmlFor:"file-types-manual",className:"text-sm font-medium",children:"File Extensions (comma-separated)"}),e.jsx(we,{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 bT(){const[t,s]=p.useState(!0),[a,r]=p.useState(!1),[n,i]=p.useState({maxFileSizeMB:10,retentionDays:365,allowedFileTypes:"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"});p.useEffect(()=>{o()},[]);const o=async()=>{try{s(!0);const d=await Yn("DOCUMENT_POLICY"),m={};d.forEach(u=>{m[u.configKey]=u.configValue}),i({maxFileSizeMB:parseInt(m.MAX_FILE_SIZE_MB||"10"),retentionDays:parseInt(m.DOCUMENT_RETENTION_DAYS||"365"),allowedFileTypes:m.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif"})}catch(d){console.error("Failed to load document configurations:",d),ne.error("Failed to load document configurations")}finally{s(!1)}},l=async()=>{var d,m;try{r(!0),await Promise.all([os("MAX_FILE_SIZE_MB",n.maxFileSizeMB.toString()),os("DOCUMENT_RETENTION_DAYS",n.retentionDays.toString()),os("ALLOWED_FILE_TYPES",n.allowedFileTypes)]),ne.success("Document policy saved successfully"),await o()}catch(u){console.error("Failed to save document configuration:",u),ne.error(((m=(d=u.response)==null?void 0:d.data)==null?void 0:m.error)||"Failed to save document configuration")}finally{r(!1)}},c=d=>{i(m=>({...m,...d}))};return t?e.jsx(X,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(J,{className:"p-12 text-center",children:[e.jsx(Je,{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(X,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(le,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx(Ee,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg font-semibold text-gray-900",children:"Document Upload Policy"}),e.jsx(je,{className:"text-sm text-gray-600",children:"Configure file upload limits, allowed types, and retention policies"})]})]})}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(gT,{maxFileSizeMB:n.maxFileSizeMB,retentionDays:n.retentionDays,onMaxFileSizeChange:d=>c({maxFileSizeMB:d}),onRetentionDaysChange:d=>c({retentionDays:d})}),e.jsx(It,{}),e.jsx(yT,{allowedFileTypes:n.allowedFileTypes,onAllowedFileTypesChange:d=>c({allowedFileTypes:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(R,{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(Je,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(fa,{className:"w-4 h-4 mr-2"}),"Save Document Policy"]})})})]})]})}function vT(){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 jT=["Total Requests","Open Requests","Approved Requests","Rejected Requests","My Pending Actions","TAT Compliance","Delayed Workflows","Average Cycle Time"],NT=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 wT({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(se,{className:NT(t),children:[t," Dashboard"]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 ml-4",children:jT.map(r=>e.jsxs("div",{className:"flex items-center space-x-2 p-2 bg-muted/50 rounded",children:[e.jsx(bl,{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 CT(){const[t,s]=p.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=()=>{ne.success("Dashboard layout saved successfully")},r=(i,o,l)=>{s(c=>({...c,[i]:{...c[i],[o]:l}}))},n=["Initiator","Approver","Spectator"];return e.jsxs(X,{children:[e.jsxs(le,{children:[e.jsx(ce,{children:"Dashboard Layout Configuration"}),e.jsx(je,{children:"Control which KPI cards are visible for each user role"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsx(vT,{}),e.jsx("div",{className:"space-y-6",children:n.map(i=>e.jsx(wT,{role:i,kpis:t[i]||{},onKPIToggle:(o,l)=>r(i,o,l)},i))}),e.jsxs(R,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(fa,{className:"w-4 h-4 mr-2"}),"Save Dashboard Layout"]})]})]})}function ST({aiEnabled:t,onAiEnabledChange:s}){return e.jsxs(X,{className:"border-0 shadow-sm",children:[e.jsxs(le,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bm,{className:"w-5 h-5 text-re-green"}),e.jsx(ce,{className:"text-base font-semibold",children:"Vertex AI Gemini Configuration"})]}),e.jsx(je,{className:"text-sm",children:"Configure AI features. Model and region are configured via environment variables."})]}),e.jsx(J,{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-md",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Enable AI Features"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Master toggle to enable/disable all AI-powered features"})]}),e.jsx(us,{checked:t,onCheckedChange:s})]})})]})}function AT({aiRemarkGeneration:t,onRemarkGenerationChange:s}){return e.jsxs(X,{className:"border-0 shadow-sm",children:[e.jsxs(le,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fn,{className:"w-5 h-5 text-re-green"}),e.jsx(ce,{className:"text-base font-semibold",children:"AI Features"})]}),e.jsx(je,{className:"text-sm",children:"Enable/disable specific AI-powered features"})]}),e.jsx(J,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-md hover:bg-gray-100 transition-colors",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"AI Remark Generation"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatically generate conclusion remarks for workflow closures"})]}),e.jsx(us,{checked:t,onCheckedChange:s})]})})})]})}function kT({maxRemarkChars:t,onMaxRemarkCharsChange:s}){return e.jsxs(X,{className:"border-0 shadow-sm",children:[e.jsxs(le,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($m,{className:"w-5 h-5 text-re-green"}),e.jsx(ce,{className:"text-base font-semibold",children:"AI Parameters"})]}),e.jsx(je,{className:"text-sm",children:"Configure AI generation parameters"})]}),e.jsx(J,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"max-remark-chars",className:"text-sm font-medium",children:"Maximum Remark Length"}),e.jsx(we,{id:"max-remark-chars",type:"number",min:"500",max:"5000",value:t,onChange:a=>s(parseInt(a.target.value)||2e3),className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Maximum character length for AI-generated conclusion remarks (500-5000 characters)"})]})})]})}function TT(){const[t,s]=p.useState(!0),[a,r]=p.useState(!1),[n,i]=p.useState({aiEnabled:!0,aiRemarkGeneration:!0,maxRemarkChars:2e3});p.useEffect(()=>{o()},[]);const o=async()=>{try{s(!0);const d=await Yn("AI_CONFIGURATION"),m={};d.forEach(u=>{m[u.configKey]=u.configValue}),i({aiEnabled:m.AI_ENABLED==="true",aiRemarkGeneration:m.AI_REMARK_GENERATION_ENABLED==="true",maxRemarkChars:parseInt(m.AI_MAX_REMARK_LENGTH||"2000")})}catch(d){console.error("Failed to load AI configurations:",d),ne.error("Failed to load AI configurations")}finally{s(!1)}},l=async()=>{var d,m;try{r(!0),await Promise.all([os("AI_ENABLED",n.aiEnabled.toString()),os("AI_REMARK_GENERATION_ENABLED",n.aiRemarkGeneration.toString()),os("AI_MAX_REMARK_LENGTH",n.maxRemarkChars.toString())]),ne.success("AI configuration saved successfully"),await o()}catch(u){console.error("Failed to save AI configuration:",u),ne.error(((m=(d=u.response)==null?void 0:d.data)==null?void 0:m.error)||"Failed to save AI configuration")}finally{r(!1)}},c=d=>{i(m=>({...m,...d}))};return t?e.jsx(X,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(J,{className:"p-12 text-center",children:[e.jsx(Je,{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(X,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(le,{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(Fn,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-lg font-semibold text-gray-900",children:"AI Features Configuration"}),e.jsx(je,{className:"text-sm text-gray-600",children:"Configure Vertex AI Gemini settings and enable/disable AI-powered features"})]})]})}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(ST,{aiEnabled:n.aiEnabled,onAiEnabledChange:d=>c({aiEnabled:d})}),e.jsx(It,{}),e.jsx(AT,{aiRemarkGeneration:n.aiRemarkGeneration,onRemarkGenerationChange:d=>c({aiRemarkGeneration:d})}),e.jsx(It,{}),e.jsx(kT,{maxRemarkChars:n.maxRemarkChars,onMaxRemarkCharsChange:d=>c({maxRemarkChars:d})}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(R,{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(Je,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(fa,{className:"w-4 h-4 mr-2"}),"Save AI Configuration"]})})})]})]})}const nm=["Admin Only","Initiator Only","Approver Only","Initiator & Approver","Admin & Initiator","Admin & Approver","All Roles"];function DT({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(Q,{htmlFor:"spectator-permission",children:"Spectator Addition Permission"}),e.jsxs(Be,{value:t,onValueChange:a,children:[e.jsx(Ve,{id:"spectator-permission",children:e.jsx(Ue,{placeholder:"Select permission"})}),e.jsx(ze,{children:nm.map(n=>e.jsx(W,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"link-sharing-permission",children:"Link Sharing Permission"}),e.jsxs(Be,{value:s,onValueChange:r,children:[e.jsx(Ve,{id:"link-sharing-permission",children:e.jsx(Ue,{placeholder:"Select permission"})}),e.jsx(ze,{children:nm.map(n=>e.jsx(W,{value:n,children:n},n))})]})]})]})}function RT({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(us,{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(us,{checked:s,onCheckedChange:r})]})]})}function PT(){const[t,s]=p.useState({spectatorPermission:"Initiator & Approver",linkSharingPermission:"Admin & Initiator",requirePassword:!0,allowExternalSharing:!1}),a=()=>{ne.success("Sharing policy saved successfully")},r=n=>{s(i=>({...i,...n}))};return e.jsxs(X,{children:[e.jsxs(le,{children:[e.jsx(ce,{children:"Workflow Sharing Policy"}),e.jsx(je,{children:"Control who can add spectators and share workflow links"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(DT,{spectatorPermission:t.spectatorPermission,linkSharingPermission:t.linkSharingPermission,onSpectatorPermissionChange:n=>r({spectatorPermission:n}),onLinkSharingPermissionChange:n=>r({linkSharingPermission:n})}),e.jsx(It,{}),e.jsx(RT,{requirePassword:t.requirePassword,allowExternalSharing:t.allowExternalSharing,onRequirePasswordChange:n=>r({requirePassword:n}),onAllowExternalSharingChange:n=>r({allowExternalSharing:n})}),e.jsxs(R,{onClick:a,className:"bg-re-green hover:bg-re-green/90",children:[e.jsx(fa,{className:"w-4 h-4 mr-2"}),"Save Sharing Policy"]})]})]})}function ET(){const{user:t}=Gt(),[s,a]=p.useState(""),[r,n]=p.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(d=>({...d,kpis:d.kpis.filter(m=>m.title.toLowerCase().includes(s.toLowerCase())||m.description.toLowerCase().includes(s.toLowerCase())||m.category.toLowerCase().includes(s.toLowerCase()))})).filter(d=>d.kpis.length>0),l=i.reduce((d,m)=>d+m.count,0),c=d=>{switch(d){case"Initiator":return"bg-blue-100 text-blue-800 border-blue-200";case"Management":return"bg-orange-100 text-orange-800 border-orange-200";case"Admin":return"bg-purple-100 text-purple-800 border-purple-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-re-black flex items-center gap-2",children:[e.jsx(ls,{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(se,{className:"bg-re-green/10 text-re-green border-re-green/20 px-4 py-2",children:[e.jsx(ls,{className:"w-4 h-4 mr-2"}),"Administrator: ",(t==null?void 0:t.displayName)||"Admin User"]})]}),e.jsx(It,{}),e.jsxs(Jr,{value:r,onValueChange:n,className:"flex flex-col gap-2 space-y-4",children:[e.jsxs(Qr,{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(gt,{value:"kpi",className:"flex items-center gap-2",children:[e.jsx(Om,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KPI Config"})]}),e.jsxs(gt,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(Zs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Analytics"})]}),e.jsxs(gt,{value:"users",className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(gt,{value:"tat",className:"flex items-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"TAT"})]}),e.jsxs(gt,{value:"notifications",className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Notify"})]}),e.jsxs(gt,{value:"documents",className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Docs"})]}),e.jsxs(gt,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(tf,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(gt,{value:"ai",className:"flex items-center gap-2",children:[e.jsx(Bm,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"AI"})]}),e.jsxs(gt,{value:"sharing",className:"flex items-center gap-2",children:[e.jsx(qa,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sharing"})]})]}),e.jsx(ft,{value:"kpi",className:"flex-1 outline-none space-y-4",children:e.jsxs(X,{children:[e.jsx(le,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"KPI Configuration"}),e.jsx(je,{children:"Configure which KPIs are enabled, visible to specific roles, and set alert thresholds"})]}),e.jsxs(se,{className:"bg-blue-50 text-blue-700",children:[l," / ",l," KPIs Active"]})]})}),e.jsxs(J,{className:"space-y-6",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ws,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(we,{placeholder:"Search KPIs by name, description, or category...",value:s,onChange:d=>a(d.target.value),className:"pl-10"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:i.map(d=>e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:d.name}),e.jsx("p",{className:"text-2xl font-semibold",children:d.count})]},d.name))}),o.map(d=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"w-5 h-5 text-re-green"}),e.jsx("h3",{className:"font-semibold",children:d.name}),e.jsxs(se,{variant:"outline",className:"ml-auto",children:[d.kpis.length," Active"]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:d.kpis.map(m=>e.jsx("div",{className:`p-4 border rounded-lg ${m.bgColor} ${m.borderColor} transition-all hover:shadow-md ${m.thresholdBreached?"ring-2 ring-orange-500":""}`,children:e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-medium text-sm mb-1",children:m.title}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:m.description})]}),e.jsx(se,{className:"bg-green-100 text-green-800 text-xs",children:"Active"})]}),e.jsxs("div",{className:"flex items-end gap-3 py-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-4xl font-bold text-re-black",children:m.value}),m.unit&&e.jsx("span",{className:"text-lg text-muted-foreground",children:m.unit})]})}),m.change!==void 0&&e.jsxs("div",{className:`flex items-center gap-1 text-xs px-2 py-1 rounded ${m.changeType==="up"?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:[m.changeType==="up"?e.jsx(sf,{className:"w-3 h-3"}):e.jsx(af,{className:"w-3 h-3"}),e.jsxs("span",{className:"font-semibold",children:[Math.abs(m.change),"%"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Visible:"}),m.visibleTo.map(u=>e.jsx(se,{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: ",m.period]}),m.thresholdBreached&&e.jsxs("div",{className:"flex items-center gap-1 text-orange-600",children:[e.jsx(Ie,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium",children:"Threshold Breached!"})]})]})]})]})})},m.id))})]},d.name))]})]})}),e.jsx(ft,{value:"analytics",className:"flex-1 outline-none space-y-4",children:e.jsx(tT,{})}),e.jsx(ft,{value:"users",className:"flex-1 outline-none space-y-4",children:e.jsx(oT,{})}),e.jsx(ft,{value:"tat",className:"flex-1 outline-none space-y-4",children:e.jsx(mT,{})}),e.jsx(ft,{value:"notifications",className:"flex-1 outline-none space-y-4",children:e.jsx(xT,{})}),e.jsx(ft,{value:"documents",className:"flex-1 outline-none space-y-4",children:e.jsx(bT,{})}),e.jsx(ft,{value:"dashboard",className:"flex-1 outline-none space-y-4",children:e.jsx(CT,{})}),e.jsx(ft,{value:"ai",className:"flex-1 outline-none space-y-4",children:e.jsx(TT,{})}),e.jsx(ft,{value:"sharing",className:"flex-1 outline-none space-y-4",children:e.jsx(PT,{})})]})]})}function IT({isOpen:t,onClose:s,action:a,requestId:r,requestTitle:n,onSubmit:i}){const[o,l]=p.useState(""),[c,d]=p.useState(!1),m=async()=>{if(!(!o.trim()||o.length>500)){d(!0);try{await i(a,o.trim()),l(""),s()}catch(f){console.error("Error submitting approval action:",f)}finally{d(!1)}}},u=()=>{l(""),s()},x=a==="approve"?{title:"Approve Request",description:"Please provide your approval comments and remarks",icon:Ce,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:yt,iconColor:"text-red-600",buttonColor:"bg-red-600 hover:bg-red-700",badgeColor:"bg-red-100 text-red-800 border-red-200",placeholder:"Enter detailed reasons for rejection and any suggestions for improvement..."},g=x.icon;return e.jsx(nt,{open:t,onOpenChange:u,children:e.jsxs(tt,{className:"max-w-2xl bg-white",children:[e.jsxs(it,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:`p-2 rounded-lg ${a==="approve"?"bg-green-100":"bg-red-100"}`,children:e.jsx(g,{className:`w-6 h-6 ${x.iconColor}`})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(st,{className:"text-xl",children:x.title}),e.jsx(Mt,{className:"mt-1",children:x.description})]})]}),e.jsxs("div",{className:"space-y-3 p-4 bg-gray-50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-gray-900",children:"Request ID:"}),e.jsx(se,{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(se,{className:x.badgeColor,variant:"outline",children:[e.jsx(g,{className:"w-3 h-3 mr-1"}),a==="approve"?"APPROVE":"REJECT"]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"comment",className:"text-sm font-semibold text-gray-900",children:"Comments & Remarks *"}),e.jsx(ns,{id:"comment",placeholder:x.placeholder,value:o,onChange:f=>l(f.target.value.slice(0,500)),className:"min-h-[120px] resize-none",rows:6}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(as,{className:"w-3 h-3"}),"Comments are required and will be visible to all participants"]}),e.jsxs("span",{children:[o.length,"/500"]})]})]}),a==="reject"&&e.jsx("div",{className:"p-3 bg-orange-50 border border-orange-200 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(as,{className:"w-4 h-4 text-orange-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium text-orange-800",children:"Rejection Guidelines"}),e.jsx("p",{className:"text-orange-700 mt-1",children:"Please provide specific, actionable feedback to help the initiator improve their request."})]})]})}),a==="approve"&&e.jsx("div",{className:"p-3 bg-green-50 border border-green-200 rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ce,{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(Nt,{className:"gap-2",children:[e.jsx(R,{variant:"outline",onClick:u,disabled:c,children:"Cancel"}),e.jsx(R,{onClick:m,disabled:!o.trim()||c||o.length>500,className:x.buttonColor,children:c?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(g,{className:"w-4 h-4 mr-2"}),a==="approve"?"Approve Request":"Reject Request"]})})]})]})})}var MT=(t,s,a,r,n,i,o,l)=>{let c=document.documentElement,d=["light","dark"];function m(x){(Array.isArray(t)?t:[t]).forEach(g=>{let f=g==="class",j=f&&i?n.map(w=>i[w]||w):n;f?(c.classList.remove(...j),c.classList.add(i&&i[x]?i[x]:x)):c.setAttribute(g,x)}),u(x)}function u(x){l&&d.includes(x)&&(c.style.colorScheme=x)}function h(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let x=localStorage.getItem(s)||a,g=o&&x==="system"?h():x;m(g)}catch{}},FT=p.createContext(void 0),_T={setTheme:t=>{},themes:[]},LT=()=>{var t;return(t=p.useContext(FT))!=null?t:_T};p.memo(({forcedTheme:t,storageKey:s,attribute:a,enableSystem:r,enableColorScheme:n,defaultTheme:i,value:o,themes:l,nonce:c,scriptProps:d})=>{let m=JSON.stringify([a,s,i,t,l,o,r,n]).slice(1,-1);return p.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?c:"",dangerouslySetInnerHTML:{__html:`(${MT.toString()})(${m})`}})});const OT=({...t})=>{const{theme:s="system"}=LT();return e.jsx(rf,{theme:s,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function $T({open:t,onClose:s,onSelect:a,managers:r=[],errorType:n,message:i,isLoading:o=!1}){const l=c=>{a(c)};return e.jsx(nt,{open:t,onOpenChange:s,children:e.jsxs(tt,{className:"sm:max-w-[600px]",children:[e.jsxs(it,{children:[e.jsx(st,{className:"flex items-center gap-2",children:n==="NO_MANAGER_FOUND"?e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-5 h-5 text-amber-500"}),"Manager Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Er,{className:"w-5 h-5 text-blue-500"}),"Select Your Manager"]})}),e.jsx(Mt,{children:n==="NO_MANAGER_FOUND"?e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-sm text-gray-600",children:i||"No reporting manager found in the system. Please ensure your manager is correctly configured in your profile."}),e.jsx("p",{className:"text-sm text-gray-500 mt-2",children:"Please contact your administrator to update your manager information, or try again later."})]}):e.jsx("div",{className:"mt-2",children:e.jsx("p",{className:"text-sm text-gray-600",children:i||"Multiple managers were found with the same name. Please select the correct manager from the list below."})})})]}),e.jsx("div",{className:"mt-4",children:n==="NO_MANAGER_FOUND"?e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ie,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-amber-900",children:"Unable to Proceed"}),e.jsx("p",{className:"text-sm text-amber-700 mt-1",children:"We couldn't find your reporting manager in the system. The claim request cannot be created without a valid manager assigned."})]})]})}):e.jsx("div",{className:"space-y-3 max-h-[400px] overflow-y-auto",children:r.map(c=>e.jsx("div",{className:"border rounded-lg p-4 hover:bg-gray-50 transition-colors cursor-pointer",onClick:()=>!o&&l(c.email),children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-1",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(St,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsx("p",{className:"font-medium text-gray-900",children:c.displayName||`${c.firstName||""} ${c.lastName||""}`.trim()||"Unknown"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[e.jsx(aa,{className:"w-4 h-4"}),e.jsx("span",{className:"truncate",children:c.email})]}),c.department&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(No,{className:"w-4 h-4"}),e.jsx("span",{children:c.department})]})]})]})]}),e.jsx(R,{onClick:d=>{d.stopPropagation(),l(c.email)},disabled:o,className:"flex-shrink-0",size:"sm",children:"Select"})]})},c.userId))})}),e.jsx("div",{className:"flex justify-end gap-3 mt-6",children:n==="NO_MANAGER_FOUND"?e.jsx(R,{onClick:s,variant:"outline",children:"Close"}):e.jsx(e.Fragment,{children:e.jsx(R,{onClick:s,variant:"outline",disabled:o,children:"Cancel"})})})]})})}function BT({onViewRequest:t}){const{user:s}=Gt();return Un(s)?e.jsx(QA,{onViewRequest:t}):e.jsx(tk,{onViewRequest:t})}function UT({onLogout:t}){const s=ya(),[a,r]=p.useState(null),[n,i]=p.useState([]),[o,l]=p.useState(""),[c,d]=p.useState(""),[m,u]=p.useState(!1),[h,x]=p.useState(null);p.useEffect(()=>{const k=localStorage.getItem("dynamicRequests");if(k)try{const E=JSON.parse(k);i(E)}catch(E){console.error("Error parsing dynamic requests:",E)}},[]),p.useEffect(()=>{n.length>0&&localStorage.setItem("dynamicRequests",JSON.stringify(n))},[n]);const g=k=>{if(k==="profile"){s("/profile");return}if(k==="settings"){s("/settings");return}k.startsWith("/")?s(k):s(`/${k}`)},f=async(k,E,P,M)=>{l(k),d(E||"Unknown Request");const{navigateToRequest:y}=await pn(async()=>{const{navigateToRequest:A}=await import("./requestNavigation-DjrXcYns.js");return{navigateToRequest:A}},__vite__mapDeps([8,1,2,3,4,5,6,7]));y({requestId:k,requestTitle:E,status:P,request:M,navigate:s})},j=()=>{s(-1)},w=()=>{s("/new-request")},b=k=>{var M,y,A,L,K,O,$,T,S,D,I;if(k.templateType){k.templateType==="claim-management"&&s("/claim-management");return}const E=`RE-REQ-2024-${String(Object.keys(xu).length+n.length+1).padStart(3,"0")}`,P={id:E,title:k.title,description:k.description||"",category:k.category||"General",subcategory:k.subcategory||"",status:"pending",priority:k.priority||"standard",amount:k.budget||"N/A",slaProgress:0,slaRemaining:"5 days",slaEndDate:new Date(Date.now()+5*24*60*60*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),currentStep:1,totalSteps:((M=k.approvers)==null?void 0:M.length)||1,currentApprover:((A=(y=k.approvers)==null?void 0:y[0])==null?void 0:A.name)||((O=(K=(L=k.approvers)==null?void 0:L[0])==null?void 0:K.email)==null?void 0:O.split("@")[0])||"Pending Assignment",approverLevel:`1 of ${(($=k.approvers)==null?void 0:$.length)||1}`,template:"custom",initiator:{name:"Current User",role:k.initiatorRole||"Employee",department:k.department||"General",email:"current.user@royalenfield.com",phone:"+91 98765 43290",avatar:"CU"},department:k.department||"General",createdAt:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),updatedAt:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),dueDate:new Date(Date.now()+5*24*60*60*1e3).toISOString(),submittedDate:new Date().toISOString(),estimatedCompletion:new Date(Date.now()+5*24*60*60*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),conclusionRemark:"",approvalFlow:(k.approvers||[]).filter(_=>_).map((_,F)=>{var re;const G=(_==null?void 0:_.name)||((re=_==null?void 0:_.email)==null?void 0:re.split("@")[0])||`Approver ${F+1}`,B=(_==null?void 0:_.email)||"";return{step:F+1,approver:`${G}${B?` (${B})`:""}`,role:(_==null?void 0:_.role)||`Level ${(_==null?void 0:_.level)||F+1} Approver`,status:F===0?"pending":"waiting",tatHours:_!=null&&_.tat?typeof _.tat=="string"?parseInt(_.tat):_.tat:48,elapsedHours:0,assignedAt:F===0?new Date().toISOString():null,comment:null,timestamp:null}}),documents:[],spectators:(k.spectators||[]).filter(_=>_&&(_.name||_.email)).map(_=>{var G;const F=(_==null?void 0:_.name)||((G=_==null?void 0:_.email)==null?void 0:G.split("@")[0])||"Observer";return{name:F,role:(_==null?void 0:_.role)||(_==null?void 0:_.department)||"Observer",avatar:F.split(" ").map(B=>B[0]).join("").toUpperCase().slice(0,2)||"OB"}}),auditTrail:[{type:"created",action:"Request Created",details:`Custom request "${k.title}" created`,user:"Current User",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})},{type:"assignment",action:"Assigned to Approver",details:`Request assigned to ${((S=(T=k.approvers)==null?void 0:T[0])==null?void 0:S.name)||((I=(D=k.approvers)==null?void 0:D[0])==null?void 0:I.email)||"first approver"}`,user:"System",timestamp:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0})}],tags:k.tags||["custom-request"]};i([...n,P]),s("/my-requests"),ne.success("Request Submitted Successfully!",{description:`Your request "${k.title}" (${E}) has been created and sent for approval.`,duration:5e3})},C=(k,E)=>new Promise(P=>{setTimeout(()=>{k==="approve"?ne.success("Request Approved",{description:"The request has been approved and forwarded to the next step.",duration:5e3}):ne.error("Request Rejected",{description:"The request has been rejected and returned to the initiator.",duration:5e3}),r(null),P(!0)},1e3)}),v=()=>{r(null)},N=async(k,E)=>{var P,M,y,A,L,K,O;try{const $={activityName:k.activityName,activityType:k.activityType,dealerCode:k.dealerCode,dealerName:k.dealerName,dealerEmail:k.dealerEmail||void 0,dealerPhone:k.dealerPhone||void 0,dealerAddress:k.dealerAddress||void 0,activityDate:k.activityDate?new Date(k.activityDate).toISOString():void 0,location:k.location,requestDescription:k.requestDescription,periodStartDate:k.periodStartDate?new Date(k.periodStartDate).toISOString():void 0,periodEndDate:k.periodEndDate?new Date(k.periodEndDate).toISOString():void 0,estimatedBudget:k.estimatedBudget||void 0,selectedManagerEmail:E||void 0},T=await t2($);if(!T||!T.request)throw new Error("Invalid response from server: Request object not found");const S=T.request;if(!S.requestNumber&&!S.requestId)throw new Error("Invalid response from server: Request identifier not found");u(!1),x(null),ne.success("Claim Request Submitted",{description:"Your claim management request has been created successfully."}),S.requestNumber?s(`/request/${S.requestNumber}`):S.requestId?s(`/request/${S.requestId}`):s("/my-requests")}catch($){console.error("[App] Error creating claim request:",$);const T=(P=$==null?void 0:$.response)==null?void 0:P.data,S=(T==null?void 0:T.code)||((M=T==null?void 0:T.error)==null?void 0:M.code);if(S==="NO_MANAGER_FOUND"){x({errorType:"NO_MANAGER_FOUND",message:(T==null?void 0:T.message)||((y=T==null?void 0:T.error)==null?void 0:y.message)||"No reporting manager found. Please ensure your manager is correctly configured in the system.",pendingClaimData:k}),u(!0);return}if(S==="MULTIPLE_MANAGERS_FOUND"){const I=(T==null?void 0:T.managers)||((A=T==null?void 0:T.error)==null?void 0:A.managers)||[];x({errorType:"MULTIPLE_MANAGERS_FOUND",managers:I,message:(T==null?void 0:T.message)||((L=T==null?void 0:T.error)==null?void 0:L.message)||"Multiple managers found. Please select one.",pendingClaimData:k}),u(!0);return}const D=((O=(K=$==null?void 0:$.response)==null?void 0:K.data)==null?void 0:O.message)||($==null?void 0:$.message)||"Failed to create claim request";ne.error("Failed to Submit Claim Request",{description:D})}};return e.jsxs("div",{className:"min-h-screen h-screen flex flex-col overflow-hidden bg-background",children:[e.jsxs(cf,{children:[e.jsx(Lt,{path:"/login/callback",element:e.jsx(eu,{})}),e.jsx(Lt,{path:"/",element:e.jsx(es,{currentPage:"dashboard",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(Sc,{onNavigate:g,onNewRequest:w})})}),e.jsx(Lt,{path:"/dashboard",element:e.jsx(es,{currentPage:"dashboard",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(Sc,{onNavigate:g,onNewRequest:w})})}),e.jsx(Lt,{path:"/open-requests",element:e.jsx(es,{currentPage:"open-requests",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(lb,{onViewRequest:f})})}),e.jsx(Lt,{path:"/closed-requests",element:e.jsx(es,{currentPage:"closed-requests",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(Rb,{onViewRequest:f})})}),e.jsx(Lt,{path:"/shared-summaries",element:e.jsx(es,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(cA,{})})}),e.jsx(Lt,{path:"/shared-summaries/:sharedSummaryId",element:e.jsx(es,{currentPage:"shared-summaries",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(dA,{})})}),e.jsx(Lt,{path:"/my-requests",element:e.jsx(es,{currentPage:"my-requests",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(TA,{onViewRequest:f,dynamicRequests:n})})}),e.jsx(Lt,{path:"/requests",element:e.jsx(es,{currentPage:"requests",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(BT,{onViewRequest:f})})}),e.jsx(Lt,{path:"/approver-performance",element:e.jsx(es,{currentPage:"approver-performance",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(xk,{})})}),e.jsx(Lt,{path:"/request/:requestId",element:e.jsx(es,{currentPage:"request-detail",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(lA,{requestId:"",onBack:j,dynamicRequests:n})})}),e.jsx(Lt,{path:"/work-notes/:requestId",element:e.jsx(mA,{})}),e.jsx(Lt,{path:"/new-request",element:e.jsx(Zd,{onBack:j,onSubmit:b})}),e.jsx(Lt,{path:"/edit-request/:requestId",element:e.jsx(Zd,{onBack:j,onSubmit:b,requestId:void 0,isEditMode:!0})}),e.jsx(Lt,{path:"/claim-management",element:e.jsx(YS,{onBack:j,onSubmit:N})}),e.jsx(Lt,{path:"/profile",element:e.jsx(es,{currentPage:"profile",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(gk,{})})}),e.jsx(Lt,{path:"/settings",element:e.jsx(es,{currentPage:"settings",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(Dk,{})})}),e.jsx(Lt,{path:"/notifications",element:e.jsx(es,{currentPage:"notifications",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(Rk,{onNavigate:g})})}),e.jsx(Lt,{path:"/detailed-reports",element:e.jsx(es,{currentPage:"detailed-reports",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(Zk,{})})}),e.jsx(Lt,{path:"/admin",element:e.jsx(es,{currentPage:"admin",onNavigate:g,onNewRequest:w,onLogout:t,children:e.jsx(ET,{})})})]}),e.jsx(OT,{position:"top-right",toastOptions:{style:{background:"var(--card)",color:"var(--card-foreground)",border:"1px solid var(--border)"}}}),e.jsx($T,{open:m,onClose:()=>{u(!1),x(null)},onSelect:async k=>{h!=null&&h.pendingClaimData&&await N(h.pendingClaimData,k)},managers:h==null?void 0:h.managers,errorType:(h==null?void 0:h.errorType)||"NO_MANAGER_FOUND",message:h==null?void 0:h.message,isLoading:!1}),a&&e.jsx(IT,{isOpen:!!a,onClose:v,action:a,requestId:o,requestTitle:c,onSubmit:C})]})}function VT(t){const{onLogout:s}=t||{};return e.jsx(lf,{children:e.jsx(UT,{onLogout:s})})}function zT(){const{isAuthenticated:t,isLoading:s,error:a,user:r,logout:n}=Gt(),[i,o]=p.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(d){console.error("🔵 Logout error in handleLogout:",d);try{localStorage.clear(),sessionStorage.clear(),window.location.href="/"}catch(m){console.error("🔵 Error during emergency cleanup:",m)}}};return p.useEffect(()=>{},[t,s,a,r]),l?e.jsx(eu,{}):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(VT,{onLogout:c}),i&&e.jsx(T0,{isOpen:i,onClose:()=>o(!1)})]}):e.jsx(A0,{})}const jn=()=>{try{return!0}catch{return!1}},HT=()=>{if(jn())return null;try{return localStorage.getItem("token")}catch{return null}},WT={user:null,token:HT(),isAuthenticated:!1,isLoading:!1,error:null},Yp=tr({name:"auth",initialState:WT,reducers:{loginStart:t=>{t.isLoading=!0,t.error=null},loginSuccess:(t,s)=>{if(t.isLoading=!1,t.isAuthenticated=!0,t.user=s.payload.user,t.token=s.payload.token,t.error=null,!jn())try{localStorage.setItem("token",s.payload.token)}catch{}},loginFailure:(t,s)=>{if(t.isLoading=!1,t.isAuthenticated=!1,t.user=null,t.token=null,t.error=s.payload,!jn())try{localStorage.removeItem("token")}catch{}},logout:t=>{if(t.isAuthenticated=!1,t.user=null,t.token=null,t.error=null,!jn())try{localStorage.removeItem("token")}catch{}},clearError:t=>{t.error=null},updateUser:(t,s)=>{t.user=s.payload}}}),{loginStart:n4,loginSuccess:i4,loginFailure:o4,logout:l4,clearError:c4,updateUser:d4}=Yp.actions,GT=of({reducer:{auth:Yp.reducer,dashboard:ru.reducer,requests:_p.reducer,myRequests:Ep.reducer,openRequests:iu.reducer,closedRequests:pu.reducer},middleware:t=>t({serializableCheck:{ignoredActions:["persist/PERSIST"]}}),devTools:!1});Ui.createRoot(document.getElementById("root")).render(e.jsx(rg.StrictMode,{children:e.jsx(Df,{store:GT,children:e.jsx(Kf,{children:e.jsx(zT,{})})})}));export{he as a,t4 as g}; //# sourceMappingURL=index-DtEUJDeH.js.map