From e6059bc5bc08365a721c1d9966c5229c4560014a Mon Sep 17 00:00:00 2001 From: laxmanhalaki Date: Fri, 13 Feb 2026 18:25:46 +0530 Subject: [PATCH] csp issue for drop down hash code added --- ...{conclusionApi-CeHB_4RC.js => conclusionApi-CzJL-0h7.js} | 2 +- build/assets/{index-CNBODJlh.js => index-Dpa9DrmL.js} | 6 +++--- build/index.html | 2 +- src/app.ts | 6 +++--- 4 files changed, 8 insertions(+), 8 deletions(-) rename build/assets/{conclusionApi-CeHB_4RC.js => conclusionApi-CzJL-0h7.js} (90%) rename build/assets/{index-CNBODJlh.js => index-Dpa9DrmL.js} (90%) diff --git a/build/assets/conclusionApi-CeHB_4RC.js b/build/assets/conclusionApi-CzJL-0h7.js similarity index 90% rename from build/assets/conclusionApi-CeHB_4RC.js rename to build/assets/conclusionApi-CzJL-0h7.js index 5572129..09b9796 100644 --- a/build/assets/conclusionApi-CeHB_4RC.js +++ b/build/assets/conclusionApi-CzJL-0h7.js @@ -1 +1 @@ -import{a as s}from"./index-CNBODJlh.js";import"./radix-vendor-CYvDqP9X.js";import"./charts-vendor-BVfwAPj-.js";import"./utils-vendor-BTBPSQfW.js";import"./ui-vendor-BFJfF1vG.js";import"./socket-vendor-TjCxX7sJ.js";import"./redux-vendor-tbZCm13o.js";import"./router-vendor-B_rK4TXr.js";async function m(n){return(await s.post(`/conclusions/${n}/generate`)).data.data}async function f(n,t){return(await s.post(`/conclusions/${n}/finalize`,{finalRemark:t})).data.data}async function d(n){var t;try{return(await s.get(`/conclusions/${n}`)).data.data}catch(o){if(((t=o.response)==null?void 0:t.status)===404)return null;throw o}}export{f as finalizeConclusion,m as generateConclusion,d as getConclusion}; +import{a as s}from"./index-Dpa9DrmL.js";import"./radix-vendor-CYvDqP9X.js";import"./charts-vendor-BVfwAPj-.js";import"./utils-vendor-BTBPSQfW.js";import"./ui-vendor-BFJfF1vG.js";import"./socket-vendor-TjCxX7sJ.js";import"./redux-vendor-tbZCm13o.js";import"./router-vendor-B_rK4TXr.js";async function m(n){return(await s.post(`/conclusions/${n}/generate`)).data.data}async function f(n,t){return(await s.post(`/conclusions/${n}/finalize`,{finalRemark:t})).data.data}async function d(n){var t;try{return(await s.get(`/conclusions/${n}`)).data.data}catch(o){if(((t=o.response)==null?void 0:t.status)===404)return null;throw o}}export{f as finalizeConclusion,m as generateConclusion,d as getConclusion}; diff --git a/build/assets/index-CNBODJlh.js b/build/assets/index-Dpa9DrmL.js similarity index 90% rename from build/assets/index-CNBODJlh.js rename to build/assets/index-Dpa9DrmL.js index 3fd30a6..57e2d05 100644 --- a/build/assets/index-CNBODJlh.js +++ b/build/assets/index-Dpa9DrmL.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-CeHB_4RC.js","assets/radix-vendor-CYvDqP9X.js","assets/charts-vendor-BVfwAPj-.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-BFJfF1vG.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-B_rK4TXr.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-CzJL-0h7.js","assets/radix-vendor-CYvDqP9X.js","assets/charts-vendor-BVfwAPj-.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-BFJfF1vG.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-B_rK4TXr.js"])))=>i.map(i=>d[i]); var jg=Object.defineProperty;var Ng=(t,s,a)=>s in t?jg(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var Ui=(t,s,a)=>Ng(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Ru,R as Du,I as Pu,F as Iu,a as wg,T as Cg,P as Sg,C as Ag,b as Tg,O as Eu,c as Fu,d as kg,e as Rg,f as Dg,D as Pg,g as Ig,A as Eg,h as Fg,i as _g,k as Lg,l as Mg,m as $g,n as Og,V as Ug,o as Bg,p as Vg,q as zg,r as Hg,s as Wg,t as Gg,u as Yg,v as Kg,w as Xg,x as Zg,y as Jg,z as Qg,B as qg,E as ef,G as tf,H as sf,J as af,K as rf,L as nf,M as lf,N as of,Q as _u,U as Lu,W as cf,X as Mu,Y as $u,Z as df,_ as mf,$ as uf,a0 as xf,a1 as hf,a2 as pf,a3 as gf,a4 as ff,a5 as bf,a6 as yf,a7 as vf,a8 as jf,a9 as Nf,aa as wf,ab as Cf}from"./radix-vendor-CYvDqP9X.js";import{a as Sf,r as p,c as Ou,d as Pr,B as kl,C as ei,X as ti,Y as si,T as Ir,L as ai,e as fa,P as Uu,f as Bu,g as Vu,h as Af,i as Td,j as fi,k as bi,b as Tf}from"./charts-vendor-BVfwAPj-.js";import{a as no,f as zu,s as Vs,e as io,b as kd,c as kf,d as ja,g as hn,i as lo,h as Hu,j as _s,k as Us,l as Bi,m as ka,n as Rf,o as Rl,p as Df,q as He,r as Dl,t as Pf,u as If,v as Ef,w as Ff,x as Vi,y as Rd,z as _f,A as Wu,B as Gu,C as oo,D as co,E as Lf,F as Mf,G as Yu,H as wr,I as zi,J as $f,K as Of,L as Uf}from"./utils-vendor-BTBPSQfW.js";import{L as Bf,S as hs,C as ze,a as Ls,b as lt,X as ft,H as Vf,c as Ku,U as Vt,F as Re,d as De,e as wn,P as gs,f as zf,g as Hf,B as qs,h as Va,i as Hi,j as mo,k as uo,l as yr,m as Xu,n as yi,o as Zu,p as ot,q as Ya,R as $t,I as Ur,T as Ot,r as st,s as ha,t as Wf,A as ss,u as as,M as As,v as vi,w as kt,x as Pl,D as Ct,Z as xo,y as cs,z as Gf,E as Yf,G as Kf,J as Xf,K as Zf,N as Jf,O as Qf,Q as qf,V as e0,W as Ju,Y as t0,_ as s0,$ as Ra,a0 as ji,a1 as za,a2 as ri,a3 as Dd,a4 as _n,a5 as ni,a6 as Qu,a7 as wt,a8 as a0,a9 as K,aa as ta,ab as Ns,ac as qu,ad as Gt,ae as ex,af as ht,ag as r0,ah as n0,ai as tx,aj as Ni,ak as sx,al as i0,am as l0,an as ho,ao as zs,ap as Da,aq as wi,ar as Ci,as as Rs,at as o0,au as c0,av as ax,aw as d0,ax as Wn,ay as pn,az as po,aA as Si,aB as ii,aC as rx,aD as nx,aE as ix,aF as Ai,aG as Ti,aH as m0,aI as ln,aJ as lx,aK as Il,aL as u0,aM as x0,aN as h0,aO as go,aP as fo,aQ as bo,aR as p0,aS as Pd,aT as ox,aU as g0,aV as yo,aW as f0,aX as Ln,aY as b0,aZ as Id,a_ as y0,a$ as v0,b0 as j0}from"./ui-vendor-BFJfF1vG.js";import{l as N0}from"./socket-vendor-TjCxX7sJ.js";import{c as Br,a as w0}from"./redux-vendor-tbZCm13o.js";import{u as Ks,a as Ea,b as cx,B as C0,R as S0,c as Lt,O as A0}from"./router-vendor-B_rK4TXr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function a(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=a(n);fetch(n.href,i)}})();var El={},Ed=Sf;El.createRoot=Ed.createRoot,El.hydrateRoot=Ed.hydrateRoot;var dx={exports:{}},mx={};var Cn=p;function T0(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var k0=typeof Object.is=="function"?Object.is:T0,R0=Cn.useSyncExternalStore,D0=Cn.useRef,P0=Cn.useEffect,I0=Cn.useMemo,E0=Cn.useDebugValue;mx.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=D0(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=I0(function(){function c(u){if(!d){if(d=!0,m=u,u=r(u),n!==void 0&&l.hasValue){var g=l.value;if(n(g,u))return h=g}return h=u}if(g=h,k0(m,u))return g;var b=r(u);return n!==void 0&&n(g,b)?(m=u,g):(m=u,h=b)}var d=!1,m,h,x=a===void 0?null:a;return[function(){return c(s())},x===null?void 0:function(){return c(x())}]},[s,a,r,n]);var o=R0(t,i[0],i[1]);return P0(function(){l.hasValue=!0,l.value=o},[o]),E0(o),o};dx.exports=mx;var F0=dx.exports;function _0(t){t()}function L0(){let t=null,s=null;return{clear(){t=null,s=null},notify(){_0(()=>{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 Fd={notify(){},get:()=>[]};function M0(t,s){let a,r=Fd,n=0,i=!1;function l(b){m();const f=r.subscribe(b);let y=!1;return()=>{y||(y=!0,f(),h())}}function o(){r.notify()}function c(){g.onStateChange&&g.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=L0())}function h(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Fd)}function x(){i||(i=!0,m())}function u(){i&&(i=!1,h())}const g={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:c,isSubscribed:d,trySubscribe:x,tryUnsubscribe:u,getListeners:()=>r};return g}var $0=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",O0=$0(),U0=()=>typeof navigator<"u"&&navigator.product==="ReactNative",B0=U0(),V0=()=>O0||B0?p.useLayoutEffect:p.useEffect,z0=V0(),Wi=Symbol.for("react-redux-context"),Gi=typeof globalThis<"u"?globalThis:{};function H0(){if(!p.createContext)return{};const t=Gi[Wi]??(Gi[Wi]=new Map);let s=t.get(p.createContext);return s||(s=p.createContext(null),t.set(p.createContext,s)),s}var Ha=H0();function W0(t){const{children:s,context:a,serverState:r,store:n}=t,i=p.useMemo(()=>{const c=M0(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=p.useMemo(()=>n.getState(),[n]);z0(()=>{const{subscription:c}=i;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),l!==n.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[i,l]);const o=a||Ha;return p.createElement(o.Provider,{value:i},s)}var G0=W0;function vo(t=Ha){return function(){return p.useContext(t)}}var ux=vo();function xx(t=Ha){const s=t===Ha?ux:vo(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var Y0=xx();function K0(t=Ha){const s=t===Ha?Y0:xx(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var X0=K0(),Z0=(t,s)=>t===s;function J0(t=Ha){const s=t===Ha?ux:vo(t),a=(r,n={})=>{const{equalityFn:i=Z0}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:c,getServerState:d}=l;p.useRef(!0);const m=p.useCallback({[r.name](x){return r(x)}}[r.name],[r]),h=F0.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return p.useDebugValue(h),h};return Object.assign(a,{withTypes:()=>a}),a}var Q0=J0(),Fl=function(t,s){return Fl=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])},Fl(t,s)};function q0(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");Fl(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var li=function(){return li=Object.assign||function(s){for(var a,r=1,n=arguments.length;r0&&g[g.length-1])||C[0]!==6&&C[0]!==2)){f=0;continue}if(C[0]===3&&(!g||C[1]>g[0]&&C[1]0?setTimeout(u,w):u(null)}}window.addEventListener("storage",y),m.addToWaiting(y);var v=setTimeout(y,Math.max(0,h-Date.now()))})];case 1:return x.sent(),[2]}})})},m.addToWaiting=function(h){this.removeFromWaiting(h),m.waiters!==void 0&&m.waiters.push(h)},m.removeFromWaiting=function(h){m.waiters!==void 0&&(m.waiters=m.waiters.filter(function(x){return x!==h}))},m.notifyWaiters=function(){m.waiters!==void 0&&m.waiters.slice().forEach(function(h){return h()})},m.prototype.releaseLock=function(h){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,this.releaseLock__private__(h)];case 1:return[2,x.sent()]}})})},m.prototype.releaseLock__private__=function(h){return a(this,void 0,void 0,function(){var x,u,g,b;return r(this,function(f){switch(f.label){case 0:return x=this.storageHandler===void 0?l:this.storageHandler,u=i+"-"+h,(g=x.getItemSync(u))===null?[2]:(b=JSON.parse(g)).id!==this.id?[3,2]:[4,ir.default().lock(b.iat)];case 1:f.sent(),this.acquiredIatSet.delete(b.iat),x.removeItemSync(u),ir.default().unlock(b.iat),m.notifyWaiters(),f.label=2;case 2:return[2]}})})},m.lockCorrector=function(h){for(var x=Date.now()-5e3,u=h,g=[],b=0;;){var f=u.keySync(b);if(f===null)break;g.push(f),b++}for(var y=!1,v=0;v.")},sb=li(li({},tb),{buildAuthorizeUrl:Es,buildLogoutUrl:Es,getAccessTokenSilently:Es,getAccessTokenWithPopup:Es,getIdTokenClaims:Es,loginWithRedirect:Es,loginWithPopup:Es,connectAccountWithRedirect:Es,logout:Es,handleRedirectCallback:Es,getDpopNonce:Es,setDpopNonce:Es,generateDpopProof:Es,createFetcher:Es}),ab=p.createContext(sb);(function(t){q0(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 rb=function(t){return t===void 0&&(t=ab),p.useContext(t)};const Yi="idToken",Ki="userData",nb=()=>!0;class tt{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(Yi,s)}static getIdToken(){return sessionStorage.getItem(Yi)}static setUserData(s){localStorage.setItem(Ki,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(Ki);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(Ki),sessionStorage.removeItem(Yi)}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 nb()}}function Xi(t,s=5){if(!t)return!0;try{const a=t.split(".");if(a.length!==3||!a[1])return!0;const n=JSON.parse(atob(a[1])).exp*1e3,i=Date.now(),l=s*60*1e3;return n-it,t=>Promise.reject(t));je.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=tt.getRefreshToken(),l=await no.post(`${hx}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),c=(l.data.data||l.data).accessToken;return je(s)}catch(i){return tt.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function ib(t,s){var a,r;try{const n=await je.post("/auth/token-exchange",{code:t,redirectUri:s},{responseType:"json",headers:{"Content-Type":"application/json",Accept:"application/json"}});if(Array.isArray(n.data))throw console.error("❌ Response is an array (buffer issue):",{arrayLength:n.data.length,firstFew:n.data.slice(0,10),rawResponse:n}),new Error("Invalid response format: received array instead of JSON. Check Content-Type header.");const i=n.data,l=i.data||i;return l.user&&tt.setUserData(l.user),l.idToken&&tt.setIdToken(l.idToken),l.accessToken&&l.refreshToken&&(tt.setAccessToken(l.accessToken),tt.setRefreshToken(l.refreshToken)),l}catch(n){throw console.error("❌ Token exchange failed:",{message:n.message,response:(a=n.response)==null?void 0:a.data,status:(r=n.response)==null?void 0:r.status,code:t?`${t.substring(0,10)}...`:"MISSING",redirectUri:s}),n}}async function lb(){var r;const t={},a=(await je.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 sn(){const s=(await je.get("/auth/me")).data;return s.data||s}async function ob(){var t,s;try{await je.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 _l="https://ssodev.rebridge.co.in/realms/RE",px="REFLOW",wo=`${window.location.origin}/login/callback`;function cb(){const t=new URLSearchParams(window.location.search),s=t.has("logout")||t.has("tanflow_logged_out");s&&(sessionStorage.removeItem("tanflow_logged_out"),sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),console.log("đŸšĒ Cleared logout flags before initiating Tanflow login"));const a=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","tanflow"),sessionStorage.setItem("tanflow_auth_state",a);let r=`${_l}/protocol/openid-connect/auth?client_id=${px}&response_type=code&scope=openid&redirect_uri=${encodeURIComponent(wo)}&state=${a}`;s&&(r+="&prompt=login",console.log("đŸšĒ Adding prompt=login to force re-authentication after logout")),console.log("đŸšĒ Initiating Tanflow login",{isAfterLogout:s,hasPrompt:s}),window.location.href=r}async function db(t,s){var r,n,i;const a="https://reflow-uat.royalenfield.com/api/v1/";try{const l=await no.post(`${a}/auth/tanflow/token-exchange`,{code:t,redirectUri:wo,state:s},{withCredentials:!0,headers:{"Content-Type":"application/json"}}),o=((r=l.data)==null?void 0:r.data)||l.data;return o.accessToken&&tt.setAccessToken(o.accessToken),o.refreshToken&&tt.setRefreshToken(o.refreshToken),o.idToken&&tt.setIdToken(o.idToken),o.user&&tt.setUserData(o.user),o}catch(l){throw console.error("❌ Tanflow token exchange failed:",{message:l.message,response:(n=l.response)==null?void 0:n.data,status:(i=l.response)==null?void 0:i.status}),l}}function mb(t){if(!t){console.warn("đŸšĒ No id_token available for Tanflow logout, redirecting to home");const n=`${window.location.origin}/?tanflow_logged_out=true&logout=${Date.now()}`;window.location.replace(n);return}const s=wo,a=new URL(`${_l}/protocol/openid-connect/logout`);a.searchParams.set("client_id",px),a.searchParams.set("id_token_hint",t),a.searchParams.set("post_logout_redirect_uri",s);const r=a.toString();console.log("đŸšĒ Tanflow logout initiated",{hasIdToken:!!t,idTokenPrefix:t?t.substring(0,20)+"...":"none",postLogoutRedirectUri:s,logoutUrlBase:`${_l}/protocol/openid-connect/logout`,finalLogoutUrl:r.replace(t.substring(0,20),"***")}),sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),console.log("đŸšĒ Redirecting to Tanflow logout endpoint..."),window.location.href=r}const gx=p.createContext(void 0);function ub({children:t}){const[s,a]=p.useState(!1),[r,n]=p.useState(!0),[i,l]=p.useState(null),[o,c]=p.useState(null),[d,m]=p.useState(!1);p.useEffect(()=>{const v=sessionStorage.getItem("__logout_in_progress__"),w=sessionStorage.getItem("__force_logout__");if(v==="true"||w==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),tt.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(k){console.error("Error clearing storage:",k)}a(!1),l(null),n(!1),c(null);return}const C=new URLSearchParams(window.location.search);if(C.has("logout")||C.has("okta_logged_out")||C.has("tanflow_logged_out")){console.log("đŸšĒ Logout parameter detected in URL, clearing all tokens"),tt.clearAll(),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state"),sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),sessionStorage.removeItem("tanflow_logged_out"),localStorage.clear(),a(!1),l(null),n(!1);const k=new URLSearchParams;C.has("okta_logged_out")&&k.set("okta_logged_out","true"),C.has("tanflow_logged_out")&&k.set("tanflow_logged_out","true");const S=k.toString()?`/?${k.toString()}`:"/";window.history.replaceState({},document.title,S);return}window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback"||(tt.getUserData(),d?n(!1):x())},[d]),p.useEffect(()=>{if(!s)return;const v=async()=>{try{await f()}catch(k){console.error("Silent refresh failed:",k)}},w=10*60*1e3,C=setInterval(v,w);return()=>clearInterval(C)},[s]);const h=p.useRef(!1);p.useEffect(()=>{if(h.current||window.location.pathname!=="/login/callback")return;(async()=>{const w=new URLSearchParams(window.location.search);if((w.has("logout")||w.has("tanflow_logged_out")||w.has("okta_logged_out"))&&!w.get("code")){console.log("đŸšĒ Logout redirect detected in callback, redirecting to home");const _=new URLSearchParams;w.has("tanflow_logged_out")&&_.set("tanflow_logged_out","true"),w.has("okta_logged_out")&&_.set("okta_logged_out","true"),w.has("logout")&&_.set("logout",w.get("logout")||Date.now().toString());const D=_.toString()?`/?${_.toString()}`:"/?logout="+Date.now();window.location.replace(D);return}h.current=!0;const C=w.get("code"),k=w.get("error");if(window.history.replaceState({},document.title,"/login/callback"),sessionStorage.getItem("auth_provider")==="tanflow"){h.current=!1;return}if(k){c(new Error(`Authentication error: ${k}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!C){n(!1),sessionStorage.removeItem("auth_provider");return}try{n(!0),a(!1),c(null);const _=`${window.location.origin}/login/callback`,D=await ib(C,_);l(D.user),a(!0),c(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(_){console.error("❌ Token exchange error in AuthContext:",_),c(_),a(!1),l(null),sessionStorage.removeItem("auth_provider"),h.current=!1}finally{n(!1)}})()},[]);const x=async()=>{var w;if(d){n(!1);return}const v=!0;try{if(n(!0),v){const S=tt.getUserData();try{const _=await sn();l(_),tt.setUserData(_),a(!0)}catch(_){if(((w=_==null?void 0:_.response)==null?void 0:w.status)===401)try{await f();const D=await sn();l(D),tt.setUserData(D),a(!0)}catch{tt.clearAll(),a(!1),l(null)}else _!=null&&_.isConnectionError?S?(l(S),a(!0)):(a(!1),l(null)):(tt.clearAll(),a(!1),l(null))}return}const C=tt.getAccessToken(),k=tt.getUserData();if(!C){a(!1),l(null),n(!1);return}if(Xi(C))try{await f();const S=tt.getAccessToken();if(S&&!Xi(S)){const _=tt.getUserData();if(_)l(_),a(!0);else try{const D=await sn();l(D),tt.setUserData(D),a(!0)}catch{tt.clearAll(),a(!1),l(null)}}else tt.clearAll(),a(!1),l(null)}catch{tt.clearAll(),a(!1),l(null)}else if(k)l(k),a(!0);else try{const S=await sn();l(S),tt.setUserData(S),a(!0)}catch{tt.clearAll(),a(!1),l(null)}}catch(C){console.error("Error checking auth status:",C),c(C),tt.clearAll(),a(!1),l(null)}finally{n(!1)}},u=async()=>{try{c(null);const v="https://dev-830839.oktapreview.co",w="0oa2jgzvrpdwx2iqd0h8",C=`${window.location.origin}/login/callback`,k="code",S="openid profile email",_=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const D=new URLSearchParams(window.location.search),A=D.has("logout")||D.has("okta_logged_out")||D.has("tanflow_logged_out");let N=`${v}/oauth2/default/v1/authorize?client_id=${w}&redirect_uri=${encodeURIComponent(C)}&response_type=${k}&scope=${encodeURIComponent(S)}&state=${_}`;A&&(N+="&prompt=login"),window.location.href=N}catch(v){throw c(v),v}},g=async()=>{try{const v=tt.getIdToken(),w=sessionStorage.getItem("auth_provider")||(v&&v.includes("tanflow")?"tanflow":null)||"okta";sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),m(!0),a(!1),l(null),c(null),n(!0);try{await ob(),console.log("đŸšĒ Backend logout API called successfully")}catch(D){console.error("đŸšĒ Logout API error:",D),console.warn("đŸšĒ Backend logout failed - httpOnly cookies may not be cleared")}const C=sessionStorage.getItem("__logout_in_progress__"),k=sessionStorage.getItem("__force_logout__"),S=sessionStorage.getItem("auth_provider");if(tt.clearAll(),C&&sessionStorage.setItem("__logout_in_progress__",C),k&&sessionStorage.setItem("__force_logout__",k),v&&tt.setIdToken(v),S&&sessionStorage.setItem("auth_provider",S),await new Promise(D=>setTimeout(D,100)),w==="tanflow"&&v){console.log("đŸšĒ Initiating Tanflow logout...");try{mb(v);return}catch(D){console.error("đŸšĒ Tanflow logout error:",D)}}console.log("đŸšĒ Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),v&&tt.clearAll();const _=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(_)}catch(v){console.error("đŸšĒ Logout error:",v);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const w=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(w)}catch{window.location.replace("/?logout="+Date.now())}}},b=async()=>{{if(s)return"cookie-based-auth";try{return await f(),s?"cookie-based-auth":null}catch{return null}}const v=tt.getAccessToken();if(v&&!Xi(v))return v;try{return await f(),tt.getAccessToken()}catch{return null}},f=async()=>{try{const w=await lb();return}catch(w){throw tt.clearAll(),a(!1),l(null),w}},y={isAuthenticated:s,isLoading:r,user:i,error:o,login:u,logout:g,getAccessTokenSilently:b,refreshTokenSilently:f};return e.jsx(gx.Provider,{value:y,children:t})}function xb({children:t}){return e.jsx(ub,{children:t})}function Kt(){const t=p.useContext(gx);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function lr(t){return(t==null?void 0:t.role)==="ADMIN"}function Jr(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function ki(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const Md=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,$d=Ou,fx=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return $d(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,l=Object.keys(n).map(d=>{const m=a==null?void 0:a[d],h=i==null?void 0:i[d];if(m===null)return null;const x=Md(m)||Md(h);return n[d][x]}),o=a&&Object.entries(a).reduce((d,m)=>{let[h,x]=m;return x===void 0||(d[h]=x),d},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((d,m)=>{let{class:h,className:x,...u}=m;return Object.entries(u).every(g=>{let[b,f]=g;return Array.isArray(f)?f.includes({...i,...o}[b]):{...i,...o}[b]===f})?[...d,h,x]:d},[]);return $d(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},Co="-",hb=t=>{const s=gb(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(Co);return o[0]===""&&o.length!==1&&o.shift(),bx(o,s)||pb(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},bx=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?bx(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(Co);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Od=/^\[(.+)\]$/,pb=t=>{if(Od.test(t)){const s=Od.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},gb=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return bb(Object.entries(t.classGroups),a).forEach(([i,l])=>{Ll(l,r,i,s)}),r},Ll=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:Ud(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(fb(n)){Ll(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{Ll(l,Ud(s,i),a,r)})})},Ud=(t,s)=>{let a=t;return s.split(Co).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},fb=t=>t.isThemeGetter,bb=(t,s)=>s?t.map(([a,r])=>{const n=r.map(i=>typeof i=="string"?s+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([l,o])=>[s+l,o])):i);return[a,n]}):t,yb=t=>{if(t<1)return{get:()=>{},set:()=>{}};let s=0,a=new Map,r=new Map;const n=(i,l)=>{a.set(i,l),s++,s>t&&(s=0,r=a,a=new Map)};return{get(i){let l=a.get(i);if(l!==void 0)return l;if((l=r.get(i))!==void 0)return n(i,l),l},set(i,l){a.has(i)?a.set(i,l):n(i,l)}}},yx="!",vb=t=>{const{separator:s,experimentalParseClassName:a}=t,r=s.length===1,n=s[0],i=s.length,l=o=>{const c=[];let d=0,m=0,h;for(let f=0;fm?h-m:void 0;return{modifiers:c,hasImportantModifier:u,baseClassName:g,maybePostfixModifierPosition:b}};return a?o=>a({className:o,parseClassName:l}):l},jb=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},Nb=t=>({cache:yb(t.cacheSize),parseClassName:vb(t),...hb(t)}),wb=/\s+/,Cb=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(wb);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:m,hasImportantModifier:h,baseClassName:x,maybePostfixModifierPosition:u}=a(d);let g=!!u,b=r(g?x.substring(0,u):x);if(!b){if(!g){o=d+(o.length>0?" "+o:o);continue}if(b=r(x),!b){o=d+(o.length>0?" "+o:o);continue}g=!1}const f=jb(m).join(":"),y=h?f+yx:f,v=y+b;if(i.includes(v))continue;i.push(v);const w=n(b,g);for(let C=0;C0?" "+o:o)}return o};function Sb(){let t=0,s,a,r="";for(;t{if(typeof t=="string")return t;let s,a="";for(let r=0;rh(m),t());return a=Nb(d),r=a.cache.get,n=a.cache.set,i=o,o(c)}function o(c){const d=r(c);if(d)return d;const m=Cb(c,a);return n(c,m),m}return function(){return i(Sb.apply(null,arguments))}}const Et=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},jx=/^\[(?:([a-z-]+):)?(.+)\]$/i,Tb=/^\d+\/\d+$/,kb=new Set(["px","full","screen"]),Rb=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Db=/\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$/,Pb=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Ib=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Eb=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Sa=t=>Er(t)||kb.has(t)||Tb.test(t),$a=t=>Vr(t,"length",Bb),Er=t=>!!t&&!Number.isNaN(Number(t)),Zi=t=>Vr(t,"number",Er),Qr=t=>!!t&&Number.isInteger(Number(t)),Fb=t=>t.endsWith("%")&&Er(t.slice(0,-1)),it=t=>jx.test(t),Oa=t=>Rb.test(t),_b=new Set(["length","size","percentage"]),Lb=t=>Vr(t,_b,Nx),Mb=t=>Vr(t,"position",Nx),$b=new Set(["image","url"]),Ob=t=>Vr(t,$b,zb),Ub=t=>Vr(t,"",Vb),qr=()=>!0,Vr=(t,s,a)=>{const r=jx.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},Bb=t=>Db.test(t)&&!Pb.test(t),Nx=()=>!1,Vb=t=>Ib.test(t),zb=t=>Eb.test(t),Hb=()=>{const t=Et("colors"),s=Et("spacing"),a=Et("blur"),r=Et("brightness"),n=Et("borderColor"),i=Et("borderRadius"),l=Et("borderSpacing"),o=Et("borderWidth"),c=Et("contrast"),d=Et("grayscale"),m=Et("hueRotate"),h=Et("invert"),x=Et("gap"),u=Et("gradientColorStops"),g=Et("gradientColorStopPositions"),b=Et("inset"),f=Et("margin"),y=Et("opacity"),v=Et("padding"),w=Et("saturate"),C=Et("scale"),k=Et("sepia"),S=Et("skew"),_=Et("space"),D=Et("translate"),A=()=>["auto","contain","none"],N=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto",it,s],R=()=>[it,s],O=()=>["",Sa,$a],F=()=>["auto",Er,it],$=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],V=()=>["solid","dashed","dotted","double","none"],T=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],j=()=>["start","end","center","between","around","evenly","stretch"],U=()=>["","0",it],I=()=>["auto","avoid","all","avoid-page","page","left","right","column"],M=()=>[Er,it];return{cacheSize:500,separator:":",theme:{colors:[qr],spacing:[Sa,$a],blur:["none","",Oa,it],brightness:M(),borderColor:[t],borderRadius:["none","","full",Oa,it],borderSpacing:R(),borderWidth:O(),contrast:M(),grayscale:U(),hueRotate:M(),invert:U(),gap:R(),gradientColorStops:[t],gradientColorStopPositions:[Fb,$a],inset:P(),margin:P(),opacity:M(),padding:R(),saturate:M(),scale:M(),sepia:U(),skew:M(),space:R(),translate:R()},classGroups:{aspect:[{aspect:["auto","square","video",it]}],container:["container"],columns:[{columns:[Oa]}],"break-after":[{"break-after":I()}],"break-before":[{"break-before":I()}],"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:[...$(),it]}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],overscroll:[{overscroll:A()}],"overscroll-x":[{"overscroll-x":A()}],"overscroll-y":[{"overscroll-y":A()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[b]}],"inset-x":[{"inset-x":[b]}],"inset-y":[{"inset-y":[b]}],start:[{start:[b]}],end:[{end:[b]}],top:[{top:[b]}],right:[{right:[b]}],bottom:[{bottom:[b]}],left:[{left:[b]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Qr,it]}],basis:[{basis:P()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",it]}],grow:[{grow:U()}],shrink:[{shrink:U()}],order:[{order:["first","last","none",Qr,it]}],"grid-cols":[{"grid-cols":[qr]}],"col-start-end":[{col:["auto",{span:["full",Qr,it]},it]}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":[qr]}],"row-start-end":[{row:["auto",{span:[Qr,it]},it]}],"row-start":[{"row-start":F()}],"row-end":[{"row-end":F()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",it]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",it]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...j()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...j(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...j(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[v]}],px:[{px:[v]}],py:[{py:[v]}],ps:[{ps:[v]}],pe:[{pe:[v]}],pt:[{pt:[v]}],pr:[{pr:[v]}],pb:[{pb:[v]}],pl:[{pl:[v]}],m:[{m:[f]}],mx:[{mx:[f]}],my:[{my:[f]}],ms:[{ms:[f]}],me:[{me:[f]}],mt:[{mt:[f]}],mr:[{mr:[f]}],mb:[{mb:[f]}],ml:[{ml:[f]}],"space-x":[{"space-x":[_]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[_]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",it,s]}],"min-w":[{"min-w":[it,s,"min","max","fit"]}],"max-w":[{"max-w":[it,s,"none","full","min","max","fit","prose",{screen:[Oa]},Oa]}],h:[{h:[it,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[it,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[it,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[it,s,"auto","min","max","fit"]}],"font-size":[{text:["base",Oa,$a]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Zi]}],"font-family":[{font:[qr]}],"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",it]}],"line-clamp":[{"line-clamp":["none",Er,Zi]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Sa,it]}],"list-image":[{"list-image":["none",it]}],"list-style-type":[{list:["none","disc","decimal",it]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[y]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...V(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Sa,$a]}],"underline-offset":[{"underline-offset":["auto",Sa,it]}],"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:R()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",it]}],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",it]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[y]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...$(),Mb]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Lb]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Ob]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[u]}],"gradient-via":[{via:[u]}],"gradient-to":[{to:[u]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[y]}],"border-style":[{border:[...V(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[y]}],"divide-style":[{divide:V()}],"border-color":[{border:[n]}],"border-color-x":[{"border-x":[n]}],"border-color-y":[{"border-y":[n]}],"border-color-s":[{"border-s":[n]}],"border-color-e":[{"border-e":[n]}],"border-color-t":[{"border-t":[n]}],"border-color-r":[{"border-r":[n]}],"border-color-b":[{"border-b":[n]}],"border-color-l":[{"border-l":[n]}],"divide-color":[{divide:[n]}],"outline-style":[{outline:["",...V()]}],"outline-offset":[{"outline-offset":[Sa,it]}],"outline-w":[{outline:[Sa,$a]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:O()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[y]}],"ring-offset-w":[{"ring-offset":[Sa,$a]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Oa,Ub]}],"shadow-color":[{shadow:[qr]}],opacity:[{opacity:[y]}],"mix-blend":[{"mix-blend":[...T(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":T()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Oa,it]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[h]}],saturate:[{saturate:[w]}],sepia:[{sepia:[k]}],"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":[h]}],"backdrop-opacity":[{"backdrop-opacity":[y]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[k]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[l]}],"border-spacing-x":[{"border-spacing-x":[l]}],"border-spacing-y":[{"border-spacing-y":[l]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",it]}],duration:[{duration:M()}],ease:[{ease:["linear","in","out","in-out",it]}],delay:[{delay:M()}],animate:[{animate:["none","spin","ping","pulse","bounce",it]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[C]}],"scale-x":[{"scale-x":[C]}],"scale-y":[{"scale-y":[C]}],rotate:[{rotate:[Qr,it]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[S]}],"skew-y":[{"skew-y":[S]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",it]}],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",it]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":R()}],"scroll-mx":[{"scroll-mx":R()}],"scroll-my":[{"scroll-my":R()}],"scroll-ms":[{"scroll-ms":R()}],"scroll-me":[{"scroll-me":R()}],"scroll-mt":[{"scroll-mt":R()}],"scroll-mr":[{"scroll-mr":R()}],"scroll-mb":[{"scroll-mb":R()}],"scroll-ml":[{"scroll-ml":R()}],"scroll-p":[{"scroll-p":R()}],"scroll-px":[{"scroll-px":R()}],"scroll-py":[{"scroll-py":R()}],"scroll-ps":[{"scroll-ps":R()}],"scroll-pe":[{"scroll-pe":R()}],"scroll-pt":[{"scroll-pt":R()}],"scroll-pr":[{"scroll-pr":R()}],"scroll-pb":[{"scroll-pb":R()}],"scroll-pl":[{"scroll-pl":R()}],"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",it]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Sa,$a,Zi]}],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"]}}},Wb=Ab(Hb);function ke(...t){return Wb(Ou(t))}const gn=fx("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background text-foreground hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),E=p.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?Ru:"button";return e.jsx(l,{"data-slot":"button",className:ke(gn({variant:s,size:a,className:t})),ref:i,...n})});E.displayName="Button";function ee({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:ke("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function ge({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:ke("@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 fe({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:ke("leading-none",t),...s})}function $e({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:ke("text-muted-foreground",t),...s})}function se({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:ke("px-6 [&:last-child]:pb-6",t),...s})}const Ri="/assets/Re_Logo-By51taPS.png",Bd="/assets/landing_page_image-ClTD-4qZ.jpg";function Gb(){const{login:t,isLoading:s,error:a}=Kt(),[r,n]=p.useState(!1),[i,l]=p.useState(!1);p.useEffect(()=>{const d=new Image;d.src=Bd,d.onload=()=>{l(!0)},d.complete&&l(!0)},[]);const o=async()=>{localStorage.clear(),sessionStorage.clear();try{await t()}catch(d){console.error("========================================"),console.error("OKTA LOGIN ERROR"),console.error("Error details:",d),console.error("Error message:",d==null?void 0:d.message),console.error("Error stack:",d==null?void 0:d.stack),console.error("========================================")}},c=()=>{localStorage.clear(),sessionStorage.clear(),n(!0);try{cb()}catch(d){console.error("========================================"),console.error("TANFLOW LOGIN ERROR"),console.error("Error details:",d),n(!1)}};return a&&console.error("Auth Error in Auth Component:",{message:a.message,error:a}),e.jsxs("div",{className:"min-h-screen flex items-center justify-center p-4 relative",style:{backgroundImage:i?`url(${Bd})`:"none",backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transition:"background-image 0.3s ease-in-out"},children:[!i&&e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 to-slate-800"}),e.jsx("div",{className:"absolute inset-0 bg-black/40"}),e.jsxs(ee,{className:"w-full max-w-md shadow-xl relative z-10 bg-black backdrop-blur-sm border-gray-800",children:[e.jsx(ge,{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:Ri,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-300 text-center truncate",children:"Approval Portal"})]})}),e.jsxs(se,{className:"space-y-4",children:[a&&e.jsxs("div",{className:"bg-red-900/50 border border-red-700 text-red-200 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.jsxs("div",{className:"space-y-3",children:[e.jsx(E,{onClick:o,disabled:s||r,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(Bf,{className:"mr-2 h-5 w-5"}),"RE Employee Login"]})}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t border-gray-700"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-gray-900 px-2 text-gray-400",children:"Or"})})]}),e.jsx(E,{onClick:c,disabled:s||r,className:"w-full h-12 text-base font-semibold bg-indigo-600 hover:bg-indigo-700 text-white",size:"lg",children:r?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"}),"Redirecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hs,{className:"mr-2 h-5 w-5"}),"Dealer Login"]})})]}),e.jsxs("div",{className:"text-center text-sm text-gray-400 mt-4",children:[e.jsx("p",{children:"Secure Single Sign-On"}),e.jsx("p",{className:"text-xs mt-1 text-gray-500",children:"Choose your authentication provider"})]})]})]})]})}function wx(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Kt(),[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 l=()=>{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:Ri,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-400 text-center truncate",children:"Approval Portal"})]})}),e.jsxs("div",{className:"bg-white/10 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/20",children:[e.jsx("div",{className:"mb-6 flex justify-center",children:n==="error"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(ze,{className:"w-16 h-16 text-red-500"})}),e.jsx(ze,{className:"w-16 h-16 text-red-500 relative"})]}):n==="complete"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(Ls,{className:"w-16 h-16 text-green-500"})}),e.jsx(Ls,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(lt,{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:l()})]}),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%; } @@ -33,7 +33,7 @@ var jg=Object.defineProperty;var Ng=(t,s,a)=>s in t?jg(t,s,{enumerable:!0,config ${g}px !important; top: ${h}px !important; } - `),()=>{f.contains(b)&&f.removeChild(b)}},[s]),e.jsx(u1,{isPresent:s,childRef:i,sizeRef:l,children:p.cloneElement(t,{ref:c})})}const h1=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=_o(p1),m=p.useId();let h=!0,x=p.useMemo(()=>(h=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:u=>{d.set(u,!0);for(const g of d.values())if(!g)return;r&&r()},register:u=>(d.set(u,!1),()=>d.delete(u))}),[a,d,r]);return i&&h&&(x={...x}),p.useMemo(()=>{d.forEach((u,g)=>d.set(g,!1))},[a]),p.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(x1,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(Ii.Provider,{value:x,children:t})};function p1(){return new Map}function Vh(t=!0){const s=p.useContext(Ii);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 l=p.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const Un=t=>t.key||"";function ym(t){const s=[];return p.Children.forEach(t,a=>{p.isValidElement(a)&&s.push(a)}),s}const Ei=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",root:c})=>{const[d,m]=Vh(l),h=p.useMemo(()=>ym(t),[t]),x=l&&!d?[]:h.map(Un),u=p.useRef(!0),g=p.useRef(h),b=_o(()=>new Map),[f,y]=p.useState(h),[v,w]=p.useState(h);Jx(()=>{u.current=!1,g.current=h;for(let S=0;S{const _=Un(S),D=l&&!d?!1:h===v||x.includes(_),A=()=>{if(b.has(_))b.set(_,!0);else return;let N=!0;b.forEach(P=>{P||(N=!1)}),N&&(k==null||k(),w(g.current),l&&(m==null||m()),r&&r())};return e.jsx(h1,{isPresent:D,initial:!u.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:D?void 0:A,anchorX:o,children:S},_)})})},zh=p.createContext({strict:!1}),vm={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"]},$r={};for(const t in vm)$r[t]={isEnabled:s=>vm[t].some(a=>!!s[a])};function g1(t){for(const s in t)$r[s]={...$r[s],...t[s]}}const f1=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 ui(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||f1.has(t)}let Hh=t=>!ui(t);function b1(t){typeof t=="function"&&(Hh=s=>s.startsWith("on")?!ui(s):t(s))}try{b1(require("@emotion/is-prop-valid").default)}catch{}function y1(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(Hh(n)||a===!0&&ui(n)||!s&&!ui(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Fi=p.createContext({});function _i(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function vn(t){return typeof t=="string"||Array.isArray(t)}const nc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ic=["initial",...nc];function Li(t){return _i(t.animate)||ic.some(s=>vn(t[s]))}function Wh(t){return!!(Li(t)||t.variants)}function v1(t,s){if(Li(t)){const{initial:a,animate:r}=t;return{initial:a===!1||vn(a)?a:void 0,animate:vn(r)?r:void 0}}return t.inherit!==!1?s:{}}function j1(t){const{initial:s,animate:a}=v1(t,p.useContext(Fi));return p.useMemo(()=>({initial:s,animate:a}),[jm(s),jm(a)])}function jm(t){return Array.isArray(t)?t.join(" "):t}const jn={};function N1(t){for(const s in t)jn[s]=t[s],Ho(s)&&(jn[s].isCSSVariable=!0)}function Gh(t,{layout:s,layoutId:a}){return Yr.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!jn[t]||t==="opacity")}const w1={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},C1=Gr.length;function S1(t,s,a){let r="",n=!0;for(let i=0;i({style:{},transform:{},transformOrigin:{},vars:{}});function Yh(t,s,a){for(const r in s)!js(s[r])&&!Gh(r,a)&&(t[r]=s[r])}function A1({transformTemplate:t},s){return p.useMemo(()=>{const a=oc();return lc(a,s,t),Object.assign({},a.vars,a.style)},[s])}function T1(t,s){const a=t.style||{},r={};return Yh(r,a,t),Object.assign(r,A1(t,s)),r}function k1(t,s){const a={},r=T1(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 R1={offset:"stroke-dashoffset",array:"stroke-dasharray"},D1={offset:"strokeDashoffset",array:"strokeDasharray"};function P1(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?R1:D1;t[i.offset]=Je.transform(-r);const l=Je.transform(s),o=Je.transform(a);t[i.array]=`${l} ${o}`}function Kh(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(lc(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:h,style:x}=t;h.transform&&(x.transform=h.transform,delete h.transform),(x.transform||h.transformOrigin)&&(x.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),x.transform&&(x.transformBox=(m==null?void 0:m.transformBox)??"fill-box",delete h.transformBox),s!==void 0&&(h.x=s),a!==void 0&&(h.y=a),r!==void 0&&(h.scale=r),n!==void 0&&P1(h,n,i,l,!1)}const Xh=()=>({...oc(),attrs:{}}),Zh=t=>typeof t=="string"&&t.toLowerCase()==="svg";function I1(t,s,a,r){const n=p.useMemo(()=>{const i=Xh();return Kh(i,s,Zh(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};Yh(i,t.style,t),n.style={...i,...n.style}}return n}const E1=["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 cc(t){return typeof t!="string"||t.includes("-")?!1:!!(E1.indexOf(t)>-1||/[A-Z]/u.test(t))}function F1(t,s,a,{latestValues:r},n,i=!1){const o=(cc(t)?I1:k1)(s,r,n,t),c=y1(s,typeof t=="string",i),d=t!==p.Fragment?{...c,...o,ref:a}:{},{children:m}=s,h=p.useMemo(()=>js(m)?m.get():m,[m]);return p.createElement(t,{...d,children:h})}function Nm(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function dc(t,s,a,r){if(typeof s=="function"){const[n,i]=Nm(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]=Nm(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Jn(t){return js(t)?t.get():t}function _1({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:L1(a,r,n,t),renderState:s()}}function L1(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=Jn(i[x]);let{initial:l,animate:o}=t;const c=Li(t),d=Wh(t);s&&d&&!c&&t.inherit!==!1&&(l===void 0&&(l=s.initial),o===void 0&&(o=s.animate));let m=a?a.initial===!1:!1;m=m||l===!1;const h=m?o:l;if(h&&typeof h!="boolean"&&!_i(h)){const x=Array.isArray(h)?h:[h];for(let u=0;u(s,a)=>{const r=p.useContext(Fi),n=p.useContext(Ii),i=()=>_1(t,s,r,n);return a?i():_o(i)};function mc(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(js(r[l])||s.style&&js(s.style[l])||Gh(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const M1=Jh({scrapeMotionValuesFromProps:mc,createRenderState:oc});function Qh(t,s,a){const r=mc(t,s,a);for(const n in t)if(js(t[n])||js(s[n])){const i=Gr.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const $1=Jh({scrapeMotionValuesFromProps:Qh,createRenderState:Xh}),O1=Symbol.for("motionComponentSymbol");function Tr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function U1(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):Tr(a)&&(a.current=r))},[s])}const uc=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),B1="framerAppearId",qh="data-"+uc(B1),ep=p.createContext({});function V1(t,s,a,r,n){var b,f;const{visualElement:i}=p.useContext(Fi),l=p.useContext(zh),o=p.useContext(Ii),c=p.useContext(rc).reducedMotion,d=p.useRef(null);r=r||l.renderer,!d.current&&r&&(d.current=r(t,{visualState:s,parent:i,props:a,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:c}));const m=d.current,h=p.useContext(ep);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&z1(d.current,a,n,h);const x=p.useRef(!1);p.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const u=a[qh],g=p.useRef(!!u&&!((b=window.MotionHandoffIsComplete)!=null&&b.call(window,u))&&((f=window.MotionHasOptimisedAnimation)==null?void 0:f.call(window,u)));return Jx(()=>{m&&(x.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 y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,u)}),g.current=!1),m.enteringChildren=void 0)}),m}function z1(t,s,a,r){const{layoutId:n,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:tp(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&Tr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function tp(t){if(t)return t.options.allowProjection!==!1?t.projection:tp(t.parent)}function ul(t,{forwardMotionProps:s=!1}={},a,r){a&&g1(a);const n=cc(t)?$1:M1;function i(o,c){let d;const m={...p.useContext(rc),...o,layoutId:H1(o)},{isStatic:h}=m,x=j1(o),u=n(o,h);if(!h&&Lo){W1();const g=G1(m);d=g.MeasureLayout,x.visualElement=V1(t,u,m,r,g.ProjectionNode)}return e.jsxs(Fi.Provider,{value:x,children:[d&&x.visualElement?e.jsx(d,{visualElement:x.visualElement,...m}):null,F1(t,o,U1(u,x.visualElement,c),u,h,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=p.forwardRef(i);return l[O1]=t,l}function H1({layoutId:t}){const s=p.useContext(Fo).id;return s&&t!==void 0?s+"-"+t:t}function W1(t,s){p.useContext(zh).strict}function G1(t){const{drag:s,layout:a}=$r;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 Y1(t,s){if(typeof Proxy>"u")return ul;const a=new Map,r=(i,l)=>ul(i,l,t,s),n=(i,l)=>r(i,l);return new Proxy(n,{get:(i,l)=>l==="create"?r:(a.has(l)||a.set(l,ul(l,void 0,t,s)),a.get(l))})}function sp({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function K1({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function X1(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 xl(t){return t===void 0||t===1}function Jl({scale:t,scaleX:s,scaleY:a}){return!xl(t)||!xl(s)||!xl(a)}function or(t){return Jl(t)||ap(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function ap(t){return wm(t.x)||wm(t.y)}function wm(t){return t&&t!=="0%"}function xi(t,s,a){const r=t-a,n=s*r;return a+n}function Cm(t,s,a,r,n){return n!==void 0&&(t=xi(t,n,r)),xi(t,a,r)+s}function Ql(t,s=0,a=1,r,n){t.min=Cm(t.min,s,a,r,n),t.max=Cm(t.max,s,a,r,n)}function rp(t,{x:s,y:a}){Ql(t.x,s.translate,s.scale,s.originPoint),Ql(t.y,a.translate,a.scale,a.originPoint)}const Sm=.999999999999,Am=1.0000000000001;function Z1(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,l;for(let o=0;oSm&&(s.x=1),s.ySm&&(s.y=1)}function kr(t,s){t.min=t.min+s,t.max=t.max+s}function Tm(t,s,a,r,n=.5){const i=zt(t.min,t.max,n);Ql(t,s,a,i,r)}function Rr(t,s){Tm(t.x,s.x,s.scaleX,s.scale,s.originX),Tm(t.y,s.y,s.scaleY,s.scale,s.originY)}function np(t,s){return sp(X1(t.getBoundingClientRect(),s))}function J1(t,s,a){const r=np(t,a),{scroll:n}=s;return n&&(kr(r.x,n.offset.x),kr(r.y,n.offset.y)),r}const km=()=>({translate:0,scale:1,origin:0,originPoint:0}),Dr=()=>({x:km(),y:km()}),Rm=()=>({min:0,max:0}),Yt=()=>({x:Rm(),y:Rm()}),ql={current:null},ip={current:!1};function Q1(){if(ip.current=!0,!!Lo)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>ql.current=t.matches;t.addEventListener("change",s),s()}else ql.current=!1}const q1=new WeakMap;function eC(t,s,a){for(const r in s){const n=s[r],i=a[r];if(js(n))t.addValue(r,n);else if(js(i))t.addValue(r,Mr(n,{owner:t}));else if(i!==n)if(t.hasValue(r)){const l=t.getValue(r);l.liveStyle===!0?l.jump(n):l.hasAnimated||l.set(n)}else{const l=t.getStaticValue(r);t.addValue(r,Mr(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Dm=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class tC{scrapeMotionValuesFromProps(s,a,r){return{}}constructor({parent:s,props:a,presenceContext:r,reducedMotionConfig:n,blockInitialAnimation:i,visualState:l},o={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=qo,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const x=$s.now();this.renderScheduledAtthis.bindToMotionValue(n,r)),ip.current||Q1(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ql.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),Wa(this.notifyUpdate),Wa(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=Yr.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&Mt.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 $r){const a=$r[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):Yt()}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=Mr(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"&&(Qx(r)||eh(r))?r=parseFloat(r):!c1(r)&&Ga.test(a)&&(r=_h(s,a)),this.setBaseTarget(s,js(r)?r.get():r)),js(r)?r.get():r}setBaseTarget(s,a){this.baseTarget[s]=a}getBaseTarget(s){var i;const{initial:a}=this.props;let r;if(typeof a=="string"||typeof a=="object"){const l=dc(this.props,a,(i=this.presenceContext)==null?void 0:i.custom);l&&(r=l[s])}if(a&&r!==void 0)return r;const n=this.getBaseTargetFromProps(this.props,s);return n!==void 0&&!js(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 Bo),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){sc.render(this.render)}}class lp extends tC{constructor(){super(...arguments),this.KeyframeResolver=Jw}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;js(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function op(t,{style:s,vars:a},r,n){const i=t.style;let l;for(l in s)i[l]=s[l];n==null||n.applyProjectionStyles(i,r);for(l in a)i.setProperty(l,a[l])}function sC(t){return window.getComputedStyle(t)}class aC extends lp{constructor(){super(...arguments),this.type="html",this.renderInstance=op}readValueFromInstance(s,a){var r;if(Yr.has(a))return(r=this.projection)!=null&&r.isProjecting?Hl(a):gw(s,a);{const n=sC(s),i=(Ho(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return np(s,a)}build(s,a,r){lc(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return mc(s,a,r)}}const cp=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 rC(t,s,a,r){op(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(cp.has(n)?n:uc(n),s.attrs[n])}class nC extends lp{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Yt}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Yr.has(a)){const r=Fh(a);return r&&r.default||0}return a=cp.has(a)?a:uc(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return Qh(s,a,r)}build(s,a,r){Kh(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){rC(s,a,r,n)}mount(s){this.isSVGTag=Zh(s.tagName),super.mount(s)}}const iC=(t,s)=>cc(t)?new nC(s):new aC(s,{allowProjection:t!==p.Fragment});function _r(t,s,a){const r=t.getProps();return dc(r,s,a!==void 0?a:r.custom,t)}const eo=t=>Array.isArray(t);function lC(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,Mr(a))}function oC(t){return eo(t)?t[t.length-1]||0:t}function cC(t,s){const a=_r(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=oC(i[l]);lC(t,l,o)}}function dC(t){return!!(js(t)&&t.add)}function to(t,s){const a=t.getValue("willChange");if(dC(a))return a.add(s);if(!a&&Ia.WillChange){const r=new Ia.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function dp(t){return t.props[qh]}const mC=t=>t!==null;function uC(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(mC),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const xC={type:"spring",stiffness:500,damping:25,restSpeed:10},hC=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),pC={type:"keyframes",duration:.8},gC={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},fC=(t,{keyframes:s})=>s.length>2?pC:Yr.has(t)?t.startsWith("scale")?hC(s[1]):xC:gC;function bC({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:l,repeatDelay:o,from:c,elapsed:d,...m}){return!!Object.keys(m).length}const xc=(t,s,a,r={},n,i)=>l=>{const o=ec(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-ya(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-d,onUpdate:x=>{s.set(x),o.onUpdate&&o.onUpdate(x)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:t,motionValue:s,element:i?void 0:n};bC(o)||Object.assign(m,fC(t,m)),m.duration&&(m.duration=ya(m.duration)),m.repeatDelay&&(m.repeatDelay=ya(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let h=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(Xl(m),m.delay===0&&(h=!0)),(Ia.instantAnimations||Ia.skipAnimations)&&(h=!0,Xl(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,h&&!i&&s.get()!==void 0){const x=uC(m.keyframes,o);if(x!==void 0){Mt.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new Qo(m):new Ow(m)};function yC({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function mp(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in o){const h=t.getValue(m,t.latestValues[m]??null),x=o[m];if(x===void 0||d&&yC(d,m))continue;const u={delay:a,...ec(i||{},m)},g=h.get();if(g!==void 0&&!h.isAnimating&&!Array.isArray(x)&&x===g&&!u.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const y=dp(t);if(y){const v=window.MotionHandoffAnimation(y,m,Mt);v!==null&&(u.startTime=v,b=!0)}}to(t,m),h.start(xc(m,h,x,t.shouldReduceMotion&&Ph.has(m)?{type:!1}:u,t,b));const f=h.animation;f&&c.push(f)}return l&&Promise.all(c).then(()=>{Mt.update(()=>{l&&cC(t,l)})}),c}function up(t,s,a,r=0,n=1){const i=Array.from(t).sort((d,m)=>d.sortNodePosition(m)).indexOf(s),l=t.size,o=(l-1)*r;return typeof a=="function"?a(i,l):n===1?i*r:o-i*r}function so(t,s,a={}){var c;const r=_r(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(mp(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:h,staggerDirection:x}=n;return vC(t,s,d,m,h,x,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[d,m]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function vC(t,s,a=0,r=0,n=0,i=1,l){const o=[];for(const c of t.variantChildren)c.notify("AnimationStart",s),o.push(so(c,s,{...l,delay:a+(typeof r=="function"?0:r)+up(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function jC(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>so(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=so(t,s,a);else{const n=typeof s=="function"?_r(t,s,a.custom):s;r=Promise.all(mp(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function xp(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})=>jC(t,a,r)))}function AC(t){let s=SC(t),a=Pm(),r=!0;const n=c=>(d,m)=>{var x;const h=_r(t,m,c==="exit"?(x=t.presenceContext)==null?void 0:x.custom:void 0);if(h){const{transition:u,transitionEnd:g,...b}=h;d={...d,...b,...g}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=hp(t.parent)||{},h=[],x=new Set;let u={},g=1/0;for(let f=0;fg&&C,A=!1;const N=Array.isArray(w)?w:[w];let P=N.reduce(n(y),{});k===!1&&(P={});const{prevResolvedValues:R={}}=v,O={...R,...P},F=T=>{D=!0,x.has(T)&&(A=!0,x.delete(T)),v.needsAnimating[T]=!0;const j=t.getValue(T);j&&(j.liveStyle=!1)};for(const T in O){const j=P[T],U=R[T];if(u.hasOwnProperty(T))continue;let I=!1;eo(j)&&eo(U)?I=!xp(j,U):I=j!==U,I?j!=null?F(T):x.add(T):j!==void 0&&x.has(T)?F(T):v.protectedKeys[T]=!0}v.prevProp=w,v.prevResolvedValues=P,v.isActive&&(u={...u,...P}),r&&t.blockInitialAnimation&&(D=!1);const $=S&&_;D&&(!$||A)&&h.push(...N.map(T=>{const j={type:y};if(typeof T=="string"&&r&&!$&&t.manuallyAnimateOnMount&&t.parent){const{parent:U}=t,I=_r(U,T);if(U.enteringChildren&&I){const{delayChildren:M}=I.transition||{};j.delay=up(U.enteringChildren,t,M)}}return{animation:T,options:j}}))}if(x.size){const f={};if(typeof d.initial!="boolean"){const y=_r(t,Array.isArray(d.initial)?d.initial[0]:d.initial);y&&y.transition&&(f.transition=y.transition)}x.forEach(y=>{const v=t.getBaseTarget(y),w=t.getValue(y);w&&(w.liveStyle=!0),f[y]=v??null}),h.push({animation:f})}let b=!!h.length;return r&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(b=!1),r=!1,b?s(h):Promise.resolve()}function o(c,d){var h;if(a[c].isActive===d)return Promise.resolve();(h=t.variantChildren)==null||h.forEach(x=>{var u;return(u=x.animationState)==null?void 0:u.setActive(c,d)}),a[c].isActive=d;const m=l(c);for(const x in a)a[x].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=Pm()}}}function TC(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!xp(s,t):!1}function nr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Pm(){return{animate:nr(!0),whileInView:nr(),whileHover:nr(),whileTap:nr(),whileDrag:nr(),whileFocus:nr(),exit:nr()}}class Ka{constructor(s){this.isMounted=!1,this.node=s}update(){}}class kC extends Ka{constructor(s){super(s),s.animationState||(s.animationState=AC(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();_i(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 RC=0;class DC extends Ka{constructor(){super(...arguments),this.id=RC++}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 PC={animation:{Feature:kC},exit:{Feature:DC}};function Nn(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function En(t){return{point:{x:t.pageX,y:t.pageY}}}const IC=t=>s=>ac(s)&&t(s,En(s));function mn(t,s,a,r){return Nn(t,s,IC(a),r)}const pp=1e-4,EC=1-pp,FC=1+pp,gp=.01,_C=0-gp,LC=0+gp;function Ss(t){return t.max-t.min}function MC(t,s,a){return Math.abs(t-s)<=a}function Im(t,s,a,r=.5){t.origin=r,t.originPoint=zt(s.min,s.max,t.origin),t.scale=Ss(a)/Ss(s),t.translate=zt(a.min,a.max,t.origin)-t.originPoint,(t.scale>=EC&&t.scale<=FC||isNaN(t.scale))&&(t.scale=1),(t.translate>=_C&&t.translate<=LC||isNaN(t.translate))&&(t.translate=0)}function un(t,s,a,r){Im(t.x,s.x,a.x,r?r.originX:void 0),Im(t.y,s.y,a.y,r?r.originY:void 0)}function Em(t,s,a){t.min=a.min+s.min,t.max=t.min+Ss(s)}function $C(t,s,a){Em(t.x,s.x,a.x),Em(t.y,s.y,a.y)}function Fm(t,s,a){t.min=s.min-a.min,t.max=t.min+Ss(s)}function xn(t,s,a){Fm(t.x,s.x,a.x),Fm(t.y,s.y,a.y)}function Qs(t){return[t("x"),t("y")]}const fp=({current:t})=>t?t.ownerDocument.defaultView:null,_m=(t,s)=>Math.abs(t-s);function OC(t,s){const a=_m(t.x,s.x),r=_m(t.y,s.y);return Math.sqrt(a**2+r**2)}class bp{constructor(s,a,{transformPagePoint:r,contextWindow:n=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const x=pl(this.lastMoveEventInfo,this.history),u=this.startEvent!==null,g=OC(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!u&&!g)return;const{point:b}=x,{timestamp:f}=xs;this.history.push({...b,timestamp:f});const{onStart:y,onMove:v}=this.handlers;u||(y&&y(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,x)},this.handlePointerMove=(x,u)=>{this.lastMoveEvent=x,this.lastMoveEventInfo=hl(u,this.transformPagePoint),Mt.update(this.updatePoint,!0)},this.handlePointerUp=(x,u)=>{this.end();const{onEnd:g,onSessionEnd:b,resumeAnimation:f}=this.handlers;if(this.dragSnapToOrigin&&f&&f(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=pl(x.type==="pointercancel"?this.lastMoveEventInfo:hl(u,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,y),b&&b(x,y)},!ac(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=En(s),c=hl(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=xs;this.history=[{...d,timestamp:m}];const{onSessionStart:h}=a;h&&h(s,pl(c,this.history)),this.removeListeners=Dn(mn(this.contextWindow,"pointermove",this.handlePointerMove),mn(this.contextWindow,"pointerup",this.handlePointerUp),mn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),Wa(this.updatePoint)}}function hl(t,s){return s?{point:s(t.point)}:t}function Lm(t,s){return{x:t.x-s.x,y:t.y-s.y}}function pl({point:t},s){return{point:t,delta:Lm(t,yp(s)),offset:Lm(t,UC(s)),velocity:BC(s,.1)}}function UC(t){return t[0]}function yp(t){return t[t.length-1]}function BC(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=yp(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>ya(s)));)a--;if(!r)return{x:0,y:0};const i=ea(n.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const l={x:(n.x-r.x)/i,y:(n.y-r.y)/i};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function VC(t,{min:s,max:a},r){return s!==void 0&&ta&&(t=r?zt(a,t,r.max):Math.min(t,a)),t}function Mm(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 zC(t,{top:s,left:a,bottom:r,right:n}){return{x:Mm(t.x,a,n),y:Mm(t.y,s,r)}}function $m(t,s){let a=s.min-t.min,r=s.max-t.max;return s.max-s.minr?a=fn(s.min,s.max-r,t.min):r>n&&(a=fn(t.min,t.max-n,s.min)),Pa(0,1,a)}function GC(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 ao=.35;function YC(t=ao){return t===!1?t=0:t===!0&&(t=ao),{x:Om(t,"left","right"),y:Om(t,"top","bottom")}}function Om(t,s,a){return{min:Um(t,s),max:Um(t,a)}}function Um(t,s){return typeof t=="number"?t:t[s]||0}const KC=new WeakMap;class XC{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=Yt(),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=h=>{const{dragSnapToOrigin:x}=this.getProps();x?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(En(h).point)},l=(h,x)=>{const{drag:u,dragPropagation:g,onDragStart:b}=this.getProps();if(u&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=t1(u),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=x,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Qs(y=>{let v=this.getAxisMotionValue(y).get()||0;if(va.test(v)){const{projection:w}=this.visualElement;if(w&&w.layout){const C=w.layout.layoutBox[y];C&&(v=Ss(C)*(parseFloat(v)/100))}}this.originPoint[y]=v}),b&&Mt.postRender(()=>b(h,x)),to(this.visualElement,"transform");const{animationState:f}=this.visualElement;f&&f.setActive("whileDrag",!0)},o=(h,x)=>{this.latestPointerEvent=h,this.latestPanInfo=x;const{dragPropagation:u,dragDirectionLock:g,onDirectionLock:b,onDrag:f}=this.getProps();if(!u&&!this.openDragLock)return;const{offset:y}=x;if(g&&this.currentDirection===null){this.currentDirection=ZC(y),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",x.point,y),this.updateAxis("y",x.point,y),this.visualElement.render(),f&&f(h,x)},c=(h,x)=>{this.latestPointerEvent=h,this.latestPanInfo=x,this.stop(h,x),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>Qs(h=>{var x;return this.getAnimationState(h)==="paused"&&((x=this.getAxisMotionValue(h).animation)==null?void 0:x.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new bp(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:fp(this.visualElement)})}stop(s,a){const r=s||this.latestPointerEvent,n=a||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!n||!r)return;const{velocity:l}=n;this.startAnimation(l);const{onDragEnd:o}=this.getProps();o&&Mt.postRender(()=>o(r,n))}cancel(){this.isDragging=!1;const{projection:s,animationState:a}=this.visualElement;s&&(s.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),a&&a.setActive("whileDrag",!1)}updateAxis(s,a,r){const{drag:n}=this.getProps();if(!r||!Bn(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=VC(l,this.constraints[s],this.elastic[s])),i.set(l)}resolveConstraints(){var i;const{dragConstraints:s,dragElastic:a}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(i=this.visualElement.projection)==null?void 0:i.layout,n=this.constraints;s&&Tr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=zC(r.layoutBox,s):this.constraints=!1,this.elastic=YC(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&Qs(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=GC(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!Tr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=J1(r,n.root,this.visualElement.getTransformPagePoint());let l=HC(n.layout.layoutBox,i);if(a){const o=a(K1(l));this.hasMutatedConstraints=!!o,o&&(l=sp(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=Qs(m=>{if(!Bn(m,a,this.currentDirection))return;let h=c&&c[m]||{};l&&(h={min:0,max:0});const x=n?200:1e6,u=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:x,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return to(this.visualElement,s),r.start(xc(s,r,0,a,this.visualElement,!1))}stopAnimation(){Qs(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Qs(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){Qs(a=>{const{drag:r}=this.getProps();if(!Bn(a,r,this.currentDirection))return;const{projection:n}=this.visualElement,i=this.getAxisMotionValue(a);if(n&&n.layout){const{min:l,max:o}=n.layout.layoutBox[a];i.set(s[a]-zt(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!Tr(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};Qs(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=WC({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),Qs(l=>{if(!Bn(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(zt(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;KC.set(this.visualElement,this);const s=this.visualElement.current,a=mn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();Tr(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()),Mt.read(r);const l=Nn(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(Qs(m=>{const h=this.getAxisMotionValue(m);h&&(this.originPoint[m]+=c[m].translate,h.set(h.get()+c[m].translate))}),this.visualElement.render())});return()=>{l(),a(),i(),o&&o()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:l=ao,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Bn(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function ZC(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class JC extends Ka{constructor(s){super(s),this.removeGroupControls=aa,this.removeListeners=aa,this.controls=new XC(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||aa}unmount(){this.removeGroupControls(),this.removeListeners()}}const Bm=t=>(s,a)=>{t&&Mt.postRender(()=>t(s,a))};class QC extends Ka{constructor(){super(...arguments),this.removePointerDownListener=aa}onPointerDown(s){this.session=new bp(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:fp(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Bm(s),onStart:Bm(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&Mt.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=mn(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 Qn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Vm(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const en={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(Je.test(t))t=parseFloat(t);else return t;const a=Vm(t,s.target.x),r=Vm(t,s.target.y);return`${a}% ${r}%`}},qC={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=Ga.parse(t);if(n.length>5)return r;const i=Ga.createTransformer(t),l=typeof n[0]!="number"?1:0,o=a.x.scale*s.x,c=a.y.scale*s.y;n[0+l]/=o,n[1+l]/=c;const d=zt(o,c,.5);return typeof n[2+l]=="number"&&(n[2+l]/=d),typeof n[3+l]=="number"&&(n[3+l]/=d),i(n)}};let gl=!1;class e2 extends p.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;N1(t2),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),gl&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Qn.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,gl=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||Mt.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),sc.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;gl=!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 vp(t){const[s,a]=Vh(),r=p.useContext(Fo);return e.jsx(e2,{...t,layoutGroup:r,switchLayoutGroup:p.useContext(ep),isPresent:s,safeToRemove:a})}const t2={borderRadius:{...en,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:en,borderTopRightRadius:en,borderBottomLeftRadius:en,borderBottomRightRadius:en,boxShadow:qC};function s2(t,s,a){const r=js(t)?t:Mr(t);return r.start(xc("",r,s,a)),r.animation}const a2=(t,s)=>t.depth-s.depth;class r2{constructor(){this.children=[],this.isDirty=!1}add(s){Mo(this.children,s),this.isDirty=!0}remove(s){$o(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(a2),this.isDirty=!1,this.children.forEach(s)}}function n2(t,s){const a=$s.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(Wa(r),t(i-s))};return Mt.setup(r,!0),()=>Wa(r)}const jp=["TopLeft","TopRight","BottomLeft","BottomRight"],i2=jp.length,zm=t=>typeof t=="string"?parseFloat(t):t,Hm=t=>typeof t=="number"||Je.test(t);function l2(t,s,a,r,n,i){n?(t.opacity=zt(0,a.opacity??1,o2(r)),t.opacityExit=zt(s.opacity??1,0,c2(r))):i&&(t.opacity=zt(s.opacity??1,a.opacity??1,r));for(let l=0;lrs?1:a(fn(t,s,r))}function Gm(t,s){t.min=s.min,t.max=s.max}function Js(t,s){Gm(t.x,s.x),Gm(t.y,s.y)}function Ym(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function Km(t,s,a,r,n){return t-=s,t=xi(t,1/a,r),n!==void 0&&(t=xi(t,1/n,r)),t}function d2(t,s=0,a=1,r=.5,n,i=t,l=t){if(va.test(s)&&(s=parseFloat(s),s=zt(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=zt(i.min,i.max,r);t===i&&(o-=s),t.min=Km(t.min,s,a,o,n),t.max=Km(t.max,s,a,o,n)}function Xm(t,s,[a,r,n],i,l){d2(t,s[a],s[r],s[n],s.scale,i,l)}const m2=["x","scaleX","originX"],u2=["y","scaleY","originY"];function Zm(t,s,a,r){Xm(t.x,s,m2,a?a.x:void 0,r?r.x:void 0),Xm(t.y,s,u2,a?a.y:void 0,r?r.y:void 0)}function Jm(t){return t.translate===0&&t.scale===1}function wp(t){return Jm(t.x)&&Jm(t.y)}function Qm(t,s){return t.min===s.min&&t.max===s.max}function x2(t,s){return Qm(t.x,s.x)&&Qm(t.y,s.y)}function qm(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function Cp(t,s){return qm(t.x,s.x)&&qm(t.y,s.y)}function eu(t){return Ss(t.x)/Ss(t.y)}function tu(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class h2{constructor(){this.members=[]}add(s){Mo(this.members,s),s.scheduleRender()}remove(s){if($o(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 p2(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,l=(a==null?void 0:a.z)||0;if((n||i||l)&&(r=`translate3d(${n}px, ${i}px, ${l}px) `),(s.x!==1||s.y!==1)&&(r+=`scale(${1/s.x}, ${1/s.y}) `),a){const{transformPerspective:d,rotate:m,rotateX:h,rotateY:x,skewX:u,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),h&&(r+=`rotateX(${h}deg) `),x&&(r+=`rotateY(${x}deg) `),u&&(r+=`skewX(${u}deg) `),g&&(r+=`skewY(${g}deg) `)}const o=t.x.scale*s.x,c=t.y.scale*s.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const fl=["","X","Y","Z"],g2=1e3;let f2=0;function bl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Sp(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=dp(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",Mt,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Sp(r)}function Ap({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=f2++,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(v2),this.nodes.forEach(C2),this.nodes.forEach(S2),this.nodes.forEach(j2)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=l,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let c=0;cthis.root.updateBlockedByResize=!1;Mt.read(()=>{h=window.innerWidth}),t(l,()=>{const u=window.innerWidth;u!==h&&(h=u,this.root.updateBlockedByResize=!0,m&&m(),m=n2(x,250),Qn.hasAnimatedSinceResize&&(Qn.hasAnimatedSinceResize=!1,this.nodes.forEach(ru)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:h,hasRelativeLayoutChanged:x,layout:u})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||D2,{onLayoutAnimationStart:b,onLayoutAnimationComplete:f}=d.getProps(),y=!this.targetLayout||!Cp(this.targetLayout,u),v=!h&&x;if(this.options.layoutRoot||this.resumeFrom||v||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...ec(g,"layout"),onPlay:b,onComplete:f};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(m,v)}else h||ru(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=u})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Wa(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(A2),this.animationId++)}getTransformTemplate(){const{visualElement:l}=this.options;return l&&l.getProps().transformTemplate}willUpdate(l=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Sp(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&&!Ss(this.snapshot.measuredBox.x)&&!Ss(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 k=C/1e3;nu(h.x,l.x,k),nu(h.y,l.y,k),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(xn(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),k2(this.relativeTarget,this.relativeTargetOrigin,x,k),w&&x2(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=Yt()),Js(w,this.relativeTarget)),b&&(this.animationValues=m,l2(m,d,this.latestValues,k,v,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=k},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(Wa(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Mt.update(()=>{Qn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Mr(0)),this.currentAnimation=s2(this.motionValue,[0,1e3],{...l,velocity:0,isSync:!0,onUpdate:m=>{this.mixTargetDelta(m),l.onUpdate&&l.onUpdate(m)},onStop:()=>{},onComplete:()=>{l.onComplete&&l.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const l=this.getStack();l&&l.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(g2),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:m}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&Tp(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Yt();const h=Ss(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const x=Ss(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+x}Js(o,c),Rr(o,m),un(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new h2),this.sharedNodes.get(l).add(o);const d=o.options.initialPromotionConfig;o.promote({transition:d?d.transition:void 0,preserveFollowOpacity:d&&d.shouldPreserveFollowOpacity?d.shouldPreserveFollowOpacity(o):void 0})}isLead(){const l=this.getStack();return l?l.lead===this:!0}getLead(){var o;const{layoutId:l}=this.options;return l?((o=this.getStack())==null?void 0:o.lead)||this:this}getPrevLead(){var o;const{layoutId:l}=this.options;return l?(o=this.getStack())==null?void 0:o.prevLead:void 0}getStack(){const{layoutId:l}=this.options;if(l)return this.root.sharedNodes.get(l)}promote({needsReset:l,transition:o,preserveFollowOpacity:c}={}){const d=this.getStack();d&&d.promote(this,c),l&&(this.projectionDelta=void 0,this.needsReset=!0),o&&this.setOptions({transition:o})}relegate(){const l=this.getStack();return l?l.relegate(this):!1}resetSkewAndRotation(){const{visualElement:l}=this.options;if(!l)return;let o=!1;const{latestValues:c}=l;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(o=!0),!o)return;const d={};c.z&&bl("z",l,d,this.animationValues);for(let m=0;m{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(su),this.root.sharedNodes.clear()}}}function b2(t){t.updateLayout()}function y2(t){var a;const s=((a=t.resumeFrom)==null?void 0:a.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&s&&t.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:n}=t.layout,{animationType:i}=t.options,l=s.source!==t.layout.source;i==="size"?Qs(h=>{const x=l?s.measuredBox[h]:s.layoutBox[h],u=Ss(x);x.min=r[h].min,x.max=x.min+u}):Tp(i,s.layoutBox,r)&&Qs(h=>{const x=l?s.measuredBox[h]:s.layoutBox[h],u=Ss(r[h]);x.max=x.min+u,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[h].max=t.relativeTarget[h].min+u)});const o=Dr();un(o,r,s.layoutBox);const c=Dr();l?un(c,t.applyTransform(n,!0),s.measuredBox):un(c,r,s.layoutBox);const d=!wp(o);let m=!1;if(!t.resumeFrom){const h=t.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:x,layout:u}=h;if(x&&u){const g=Yt();xn(g,s.layoutBox,x.layoutBox);const b=Yt();xn(b,r,u.layoutBox),Cp(g,b)||(m=!0),h.options.layoutRoot&&(t.relativeTarget=b,t.relativeTargetOrigin=g,t.relativeParent=h)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function v2(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 j2(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function N2(t){t.clearSnapshot()}function su(t){t.clearMeasurements()}function au(t){t.isLayoutDirty=!1}function w2(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function ru(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function C2(t){t.resolveTargetDelta()}function S2(t){t.calcProjection()}function A2(t){t.resetSkewAndRotation()}function T2(t){t.removeLeadSnapshot()}function nu(t,s,a){t.translate=zt(s.translate,0,a),t.scale=zt(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function iu(t,s,a,r){t.min=zt(s.min,a.min,r),t.max=zt(s.max,a.max,r)}function k2(t,s,a,r){iu(t.x,s.x,a.x,r),iu(t.y,s.y,a.y,r)}function R2(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const D2={duration:.45,ease:[.4,0,.1,1]},lu=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),ou=lu("applewebkit/")&&!lu("chrome/")?Math.round:aa;function cu(t){t.min=ou(t.min),t.max=ou(t.max)}function P2(t){cu(t.x),cu(t.y)}function Tp(t,s,a){return t==="position"||t==="preserve-aspect"&&!MC(eu(s),eu(a),.2)}function I2(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const E2=Ap({attachResizeListener:(t,s)=>Nn(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),yl={current:void 0},kp=Ap({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!yl.current){const t=new E2({});t.mount(window),t.setOptions({layoutScroll:!0}),yl.current=t}return yl.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),F2={pan:{Feature:QC},drag:{Feature:JC,ProjectionNode:kp,MeasureLayout:vp}};function du(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&&Mt.postRender(()=>i(s,En(s)))}class _2 extends Ka{mount(){const{current:s}=this.node;s&&(this.unmount=s1(s,(a,r)=>(du(this.node,r,"Start"),n=>du(this.node,n,"End"))))}unmount(){}}class L2 extends Ka{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=Dn(Nn(this.node.current,"focus",()=>this.onFocus()),Nn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function mu(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&&Mt.postRender(()=>i(s,En(s)))}class M2 extends Ka{mount(){const{current:s}=this.node;s&&(this.unmount=i1(s,(a,r)=>(mu(this.node,r,"Start"),(n,{success:i})=>mu(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const ro=new WeakMap,vl=new WeakMap,$2=t=>{const s=ro.get(t.target);s&&s(t)},O2=t=>{t.forEach($2)};function U2({root:t,...s}){const a=t||document;vl.has(a)||vl.set(a,{});const r=vl.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(O2,{root:t,...s})),r[n]}function B2(t,s,a){const r=U2(s);return ro.set(t,a),r.observe(t),()=>{ro.delete(t),r.unobserve(t)}}const V2={some:0,all:1};class z2 extends Ka{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:a,margin:r,amount:n="some",once:i}=s,l={root:a?a.current:void 0,rootMargin:r,threshold:typeof n=="number"?n:V2[n]},o=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:h}=this.node.getProps(),x=d?m:h;x&&x(c)};return B2(this.node.current,l,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:s,prevProps:a}=this.node;["amount","margin","root"].some(H2(s,a))&&this.startObserver()}unmount(){}}function H2({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const W2={inView:{Feature:z2},tap:{Feature:M2},focus:{Feature:L2},hover:{Feature:_2}},G2={layout:{ProjectionNode:kp,MeasureLayout:vp}},Y2={...PC,...W2,...F2,...G2},ts=Y1(Y2,iC),tn=[{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:Gt,color:"from-blue-500 to-indigo-600",estimatedTime:"5-7 days",steps:7,features:["Automatic IO confirmation","Budget blocking","Document verification","E-invoice generation","Credit note issuance"],disabled:!1},{id:"vendor-payment",name:"Vendor Payment",description:"Streamlined vendor payment approval with PO validation and financial controls",category:"Finance",icon:ex,color:"from-green-500 to-emerald-600",estimatedTime:"3-5 days",steps:5,features:["PO matching","Invoice verification","Multi-level approvals","Payment scheduling"],disabled:!0,comingSoon:!0}];function K2({open:t,onClose:s,onSelectTemplate:a}){var d,m,h;const[r,n]=p.useState(null),[i,l]=p.useState(!1);p.useEffect(()=>{const x=tt.getUserData();l((x==null?void 0:x.jobTitle)==="Dealer")},[]);const o=x=>{if(i)return;const u=tn.find(g=>g.id===x);u!=null&&u.disabled||n(x)},c=()=>{r&&(a(r),s())};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{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(mt,{className:"sr-only",children:"Select a Template"}),e.jsx(Dt,{className:"sr-only",children:"Choose from pre-configured templates with predefined workflows and approval chains for faster processing."}),e.jsx("button",{onClick:s,className:"!flex absolute top-6 left-6 z-50 w-10 h-10 rounded-full bg-white shadow-lg hover:shadow-xl border border-gray-200 items-center justify-center transition-all hover:scale-110","aria-label":"Go back",children:e.jsx(Ns,{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(ts.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(qu,{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:tn.map((x,u)=>{const g=x.icon,b=r===x.id,f=i||x.disabled;return e.jsx(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:u*.1},whileHover:f?{}:{scale:1.03},whileTap:f?{}:{scale:.98},children:e.jsxs(ee,{className:`h-full transition-all duration-300 border-2 ${f?"opacity-50 cursor-not-allowed border-gray-200":b?"cursor-pointer border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"cursor-pointer border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>o(x.id),children:[e.jsxs(ge,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl bg-gradient-to-br ${x.color} flex items-center justify-center shadow-md`,children:e.jsx(g,{className:"w-7 h-7 text-white"})}),b&&e.jsx(ts.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(yr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(fe,{className:"text-xl mb-2",children:x.name}),e.jsx($e,{className:"text-sm leading-relaxed",children:x.description}),i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-amber-50 border border-amber-200 rounded-lg",children:[e.jsx(ze,{className:"w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-amber-800",children:"Not accessible for Dealers"})]}),x.comingSoon&&!i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-blue-50 border border-blue-200 rounded-lg",children:[e.jsx(ze,{className:"w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-blue-800 font-semibold",children:"Coming Soon"})]})]})]}),e.jsxs(se,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(ne,{variant:"secondary",className:"text-xs",children:x.category})}),e.jsx(Ts,{}),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(st,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:x.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ot,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[x.steps," steps"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx("p",{className:"text-xs text-gray-500 font-semibold",children:"Key Features:"}),e.jsxs("div",{className:"space-y-1.5",children:[x.features.slice(0,3).map((y,v)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(De,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:y})]},v)),x.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",x.features.length-3," more features"]})]})]})]})]})},x.id)})}),e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"flex flex-col sm:flex-row justify-center gap-4 mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(E,{onClick:c,disabled:!r||i||((d=tn.find(x=>x.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=tn.find(x=>x.id===r))!=null&&m.disabled)?"bg-blue-600 hover:bg-blue-700":"bg-gray-400 cursor-not-allowed"}`,children:["Continue with Template",e.jsx(ss,{className:"w-4 h-4"})]})]}),e.jsx(Ei,{children:r&&e.jsx(ts.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:(h=tn.find(x=>x.id===r))==null?void 0:h.name})]})})})]})})]})})}function jr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=p.useState(100),[m,h]=p.useState(0),[x,u]=p.useState(null),[g,b]=p.useState(!1),[f,y]=p.useState(null),v=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),w=s.toLowerCase().includes("pdf"),C=v||w;p.useEffect(()=>{if(!l||!C||!a){u(null);return}return(async()=>{b(!0),y(null);try{let R=a;a.startsWith("/")&&!a.startsWith("//")&&(R=`${window.location.origin}${a}`);const F=await fetch(R,{headers:{Accept:w?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!F.ok){const T=await F.text().catch(()=>"");throw new Error(`Failed to load file: ${F.status} ${F.statusText}. ${T}`)}const $=await F.blob();if($.size===0)throw new Error("File is empty or could not be loaded");w&&!$.type.includes("pdf")&&$.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${$.type}`);const V=window.URL.createObjectURL($);u(V)}catch(N){console.error("Failed to load file for preview:",N),y(N instanceof Error?N.message:"Failed to load file for preview")}finally{b(!1)}})(),()=>{x&&(window.URL.revokeObjectURL(x),u(null))}},[l,a,C,w]);const k=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},S=()=>d(A=>Math.min(A+25,200)),_=()=>d(A=>Math.max(A-25,50)),D=()=>h(A=>(A+90)%360);return e.jsx(pt,{open:l,onOpenChange:o,children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(gt,{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(ht,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`â€ĸ ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[v&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:_,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(r0,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[c,"%"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:S,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(n0,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:D,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(tx,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(E,{variant:"outline",size:"sm",onClick:k,className:"gap-2 h-9",children:[e.jsx(Ct,{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(lt,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):f?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(ft,{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:f}),i&&n&&e.jsxs(E,{onClick:k,className:"gap-2",children:[e.jsx(Ct,{className:"h-4 w-4"}),"Download ",t]})]}):C&&x?e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:x,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"})}),w&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:x,className:"w-full h-full rounded-lg border-0",title:t,style:{minHeight:"70vh",height:"100%"},onError:()=>{y("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(ht,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),i&&n&&e.jsxs(E,{onClick:k,className:"gap-2",children:[e.jsx(Ct,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function Fn({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Dt,{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(Tt,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const Ys=async t=>{const s=t?{category:t}:{};return(await je.get("/users/configurations",{params:s})).data.data},X2=async t=>{const s={};return(await je.get("/admin/configurations",{params:s})).data.data},Z2=async(t,s)=>{await je.put(`/admin/configurations/${t}`,{configValue:s})},J2=async t=>{await je.post(`/admin/configurations/${t}/reset`)},Q2=async t=>{const s=t?{year:t}:{};return(await je.get("/admin/holidays",{params:s})).data.data},q2=async t=>(await je.post("/admin/holidays",t)).data.data,eS=async(t,s)=>(await je.put(`/admin/holidays/${t}`,s)).data.data,tS=async t=>{await je.delete(`/admin/holidays/${t}`)},sS=async()=>(await je.get("/config/activity-types")).data.data,aS=async t=>{const s={activeOnly:t.toString()};return(await je.get("/admin/activity-types",{params:s})).data.data},rS=async t=>(await je.post("/admin/activity-types",t)).data.data,nS=async(t,s)=>(await je.put(`/admin/activity-types/${t}`,s)).data.data,iS=async t=>{await je.delete(`/admin/activity-types/${t}`)},lS={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 oS(t,s,a){const[r,n]=p.useState(lS),[i,l]=p.useState(null),[o,c]=p.useState(t),[d,m]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[h,x]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[u,g]=p.useState([]);return p.useEffect(()=>{(async()=>{var y;try{const v=await Ys("DOCUMENT_POLICY"),w={};v.forEach(P=>{w[P.configKey]=P.configValue});const C=parseInt(w.MAX_FILE_SIZE_MB||"10"),S=(w.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(P=>P.trim().toLowerCase());x({maxFileSizeMB:C,allowedFileTypes:S});const _=await Ys("SYSTEM_SETTINGS"),D=await Ys("WORKFLOW_SHARING"),A=[..._,...D],N={};A.forEach(P=>{N[P.configKey]=P.configValue}),m({maxApprovalLevels:parseInt(N.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(N.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((y=N.ALLOW_ADD_SPECTATOR)==null?void 0:y.toLowerCase())==="true",maxSpectators:parseInt(N.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(v){console.error("Failed to load policies:",v)}})()},[]),p.useEffect(()=>{if(!t||!s)return;let f=!0;return(async()=>{try{c(!0);const y=await vs(s);if(!f||!y)return;const v=y.workflow||{},w=Array.isArray(y.approvals)?y.approvals:[],C=Array.isArray(y.participants)?y.participants:[],k=Array.isArray(y.documents)?y.documents.filter(R=>!R.isDeleted):[];g(k);const S=(v.priority||"").toString().toLowerCase(),_={standard:"standard",express:"express"},D=v.templateType==="TEMPLATE"?"existing-template":"custom",A=a.find(R=>R.id===D)||a[0]||null;l(A);const N=w.sort((R,O)=>(R.levelNumber||0)-(O.levelNumber||0)).map(R=>{const O=Number(R.tatHours||24),F=Math.floor(O/24),$=O%24;return{id:R.approverId||`temp-${R.levelNumber}`,name:R.approverName||R.approverEmail||"",email:R.approverEmail||"",role:R.levelName||`Level ${R.levelNumber}`,department:"",avatar:(R.approverName||R.approverEmail||"XX").substring(0,2).toUpperCase(),level:R.levelNumber||1,canClose:!1,tat:F>0?F:$,tatType:F>0?"days":"hours",userId:R.approverId}}),P=C.filter(R=>(R.participantType||R.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(R.userEmail||R.user_email||R.email):!1).map((R,O)=>{const F=R.userId||R.user_id||R.id,$=R.userName||R.user_name||R.name||"",V=R.userEmail||R.user_email||R.email||"",j=($||V||"XX").split(" ").map(U=>U[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:F||`spectator-${s}-${O}-${Date.now()}`,userId:F,name:$||V||"Spectator",email:V,role:"Spectator",department:R.department||"",avatar:j,level:1,canClose:!1}});n(R=>({...R,template:D,title:v.title||"",description:v.description||"",priority:_[S]||"standard",approvers:N,approverCount:N.length||1,spectators:P,maxLevel:Math.max(...N.map(O=>O.level||1),1)}))}catch(y){console.error("Failed to load draft:",y)}finally{f&&c(!1)}})(),()=>{f=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(f,y)=>{n(v=>({...v,[f]:y}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:d,documentPolicy:h,existingDocuments:u,setExistingDocuments:g}}const uu=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function cS(t,s,a){const[r,n]=p.useState(t?2:1),i=uu.length,l=h=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(h),o=()=>{switch(r){case 1:return s!==null;case 2:return a.title.trim()!==""&&a.description.trim()!==""&&a.priority!=="";case 3:return(a.approverCount||1)>0&&a.approvers.length===(a.approverCount||1)&&a.approvers.every(h=>{if(!h||!h.email||!l(h.email))return!1;if(!h.userId)return!0;const x=h.tatType||"hours";return x==="hours"?h.tat&&h.tat>0&&h.tat<=720:x==="days"?h.tat&&h.tat>0&&h.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:uu,isStepValid:o,nextStep:()=>{o()&&(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:h=>{h>=1&&h<=i&&n(h)},validateEmail:l}}function dS(){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:(x,u,g="")=>{s({open:!0,type:x,email:u,message:g})},closeValidationModal:()=>{s(x=>({...x,open:!1}))},openPolicyViolationModal:x=>{r({open:!0,violations:x})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:x=>{i({open:!0,errors:x})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function mS(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function uS(t,s,a){var n;const r=mS(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 xS(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return uS(a,n,n===s)})}function xu(t,s,a,r=!1){return{templateId:(s==null?void 0:s.id)||null,templateType:(s==null?void 0:s.id)==="custom"?"CUSTOM":"TEMPLATE",title:t.title,description:t.description,priorityUi:t.priority==="express"?"express":"standard",approverCount:t.approverCount||1,approvers:(t.approvers||[]).map(n=>({userId:(n==null?void 0:n.userId)||"",email:(n==null?void 0:n.email)||"",name:n==null?void 0:n.name,tat:(n==null?void 0:n.tat)||24,tatType:(n==null?void 0:n.tatType)||"hours"})),spectators:(t.spectators||[]).map(n=>({userId:(n==null?void 0:n.userId)||"",name:(n==null?void 0:n.name)||"",email:(n==null?void 0:n.email)||""})),ccList:[],participants:[],isDraft:r}}function hu(t,s,a,r=!1){const n=xS(t.approvers||[],t.approverCount||1);return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:n,participants:[],deleteDocumentIds:a.length>0?a:void 0,isDraft:r}}function hS(t,s){const a=t.slice(0,s);if(a.some(l=>!(l!=null&&l.email)||!l.email.trim()))return{valid:!1,message:"Please provide email addresses for all approvers."};const n=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return a.some(l=>!n.test((l==null?void 0:l.email)||""))?{valid:!1,message:"Please provide valid email addresses for all approvers."}:{valid:!0}}async function pu(t,s){return{id:(await Io(t,s||[],"SUPPORTING")).id}}async function gu(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await sN(t,s,a||[],r):await tN(t,s)}function pS({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=p.useState(!1),[m,h]=p.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var b,f;if(c||m)return;const g=hS(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const y=hu(t,n,r,!1);await gu(l,y,a,r),K.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been submitted and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const y=xu(t,s,n,!1),v=await pu(y,a);K.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been created and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:v.id,template:s})}}catch(y){console.error("Failed to submit workflow:",y),K.error("Failed to Submit Request",{description:((f=(b=y==null?void 0:y.response)==null?void 0:b.data)==null?void 0:f.message)||(y==null?void 0:y.message)||"An error occurred while submitting the request.",duration:5e3}),d(!1)}},handleSaveDraft:async()=>{var g,b;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||m)){h(!0);try{if(i&&l){const f=hu(t,n,r,!0);await gu(l,f,a,r),K.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const f=xu(t,s,n,!0),y=await pu(f,a);K.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:y.id,template:s})}}catch(f){console.error("Failed to save draft:",f),K.error("Failed to Save Draft",{description:((b=(g=f==null?void 0:f.response)==null?void 0:g.data)==null?void 0:b.message)||(f==null?void 0:f.message)||"An error occurred while saving the draft.",duration:5e3}),h(!1)}}}}}async function ia(t,s=10,a="default"){return await je.get("/users/search",{params:{q:t,limit:s,source:a}})}async function ra(t){var a;const s=await je.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function gS(t,s){return await je.post("/admin/users/assign-role",{email:t,role:s})}async function fS(t,s){return await je.put(`/admin/users/${t}/role`,{role:s})}async function bS(t,s=1,a=10){return await je.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function yS(){return await je.get("/admin/users/role-statistics")}async function vS(t){var a;const s=await je.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function jS(){var s,a;return((a=(s=(await je.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const dr={searchUsers:ia,getUserById:vS,ensureUserExists:ra,assignRole:gS,updateUserRole:fS,getUsersByRole:bS,getRoleStatistics:yS,getAllUsers:jS};async function NS(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 ia(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 ra({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 wS(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(D),a("template",D.id),a("category",D.category),a("priority",D.priority);const A=new Date;A.setDate(A.getDate()+D.suggestedSLA),a("slaEndDate",A),D.id!=="custom"&&D.id!=="existing-template"&&u(`/create-admin-request/${D.id}`)},handleTemplateSelection:D=>{D==="claim-management"?u("/claim-management"):D==="vendor-payment"?u("/vendor-payment"):x&&x({templateType:D})},nextStep:async()=>{var D;if(i()){if(n===1&&(t==null?void 0:t.id)==="existing-template"){b(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&h){const P=r.approverCount||1;if(P>m.maxApprovalLevels){h([{type:"Maximum Approval Levels Exceeded",message:`The request has ${P} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:P,maxValue:m.maxApprovalLevels}]);return}}const A=((D=c==null?void 0:c.email)==null?void 0:D.toLowerCase())||"",N=await wS(r.approvers,A);if(!N.success&&N.error){d(N.error.type,N.error.email,N.error.message);return}N.validatedApprovers&&a("approvers",N.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(D,A)=>{if(A){const N=D.documentId||D.document_id||"";y({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:Hr(N),fileSize:Number(D.fileSize||D.file_size||0),documentId:N})}else{const N=URL.createObjectURL(D);y({fileName:D.name,fileType:D.type||"application/octet-stream",fileUrl:N,fileSize:D.size,file:D})}},closePreview:()=>{f!=null&&f.fileUrl&&(f!=null&&f.file)&&URL.revokeObjectURL(f.fileUrl),y(null)}}}const fu=[{id:"custom",name:"Non-Templatized",description:"Create a custom request for unique business needs with full flexibility to define your own workflow and requirements",category:"General",icon:Ni,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:Re,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let br=null;const bu=()=>br,SS=async t=>{const a=(await je.post("/templates",t)).data.data,r={id:a.templateId||a.id,name:a.templateName||a.name,description:a.templateDescription||a.description,category:a.templateCategory||a.category,priority:a.priority||"medium",estimatedTime:a.estimatedTime||"Variable",approvers:a.approvalLevelsConfig||a.approvers||[],suggestedSLA:a.defaultTatHours||a.suggestedSLA||24,isActive:a.isActive,fields:a.userFieldMappings||a.fields};return br&&br.push(r),r},Mi=async()=>{var r;const a=(((r=(await je.get("/templates")).data)==null?void 0:r.data)||[]).map(n=>({id:n.templateId||n.id,name:n.templateName||n.name,description:n.templateDescription||n.description,category:n.templateCategory||n.category,priority:n.priority||"medium",estimatedTime:n.estimatedTime||"Variable",approvers:n.approvalLevelsConfig||n.approvers||[],suggestedSLA:n.defaultTatHours||n.suggestedSLA||24,isActive:n.isActive,fields:n.userFieldMappings||n.fields}));return br=a,a},AS=async(t,s)=>{const r=(await je.put(`/templates/${t}`,s)).data.data,n={id:r.templateId||r.id,name:r.templateName||r.name,description:r.templateDescription||r.description,category:r.templateCategory||r.category,priority:r.priority||"medium",estimatedTime:r.estimatedTime||"Variable",approvers:r.approvalLevelsConfig||r.approvers||[],suggestedSLA:r.defaultTatHours||r.suggestedSLA||24,isActive:r.isActive,fields:r.userFieldMappings||r.fields};return br&&(br=br.map(i=>i.id===t?n:i)),n};function Rp({currentStep:t,totalSteps:s,stepNames:a}){const r=Math.round(t/s*100),n=a.length<=3?"max-w-xl":"max-w-6xl";return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-2 sm:py-3 flex-shrink-0","data-testid":"wizard-stepper",children:e.jsxs("div",{className:`${n} mx-auto`,children:[e.jsxs("div",{className:"block sm:hidden","data-testid":"wizard-stepper-mobile",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-green-600 text-white flex items-center justify-center text-xs font-semibold","data-testid":"wizard-stepper-mobile-current-step",children:t}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-900","data-testid":"wizard-stepper-mobile-step-name",children:a[t-1]}),e.jsxs("p",{className:"text-xs text-gray-600","data-testid":"wizard-stepper-mobile-step-info",children:["Step ",t," of ",s]})]})]}),e.jsx("div",{className:"text-right",children:e.jsxs("p",{className:"text-xs font-medium text-green-600","data-testid":"wizard-stepper-mobile-progress",children:[r,"%"]})})]}),e.jsx("div",{className:"w-full bg-gray-200 h-1.5 rounded-full overflow-hidden","data-testid":"wizard-stepper-mobile-progress-bar",children:e.jsx("div",{className:"bg-green-600 h-full transition-all duration-300",style:{width:`${r}%`},"data-testid":"wizard-stepper-mobile-progress-fill"})})]}),e.jsxs("div",{className:"hidden sm:block","data-testid":"wizard-stepper-desktop",children:[e.jsx("div",{className:"flex items-center justify-center gap-4 mb-2","data-testid":"wizard-stepper-desktop-steps",children:a.map((i,l)=>e.jsxs("div",{className:"flex items-center flex-1 last:flex-none","data-testid":`wizard-stepper-desktop-step-${l+1}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-xs font-semibold flex-shrink-0 ${l+1e.jsx("span",{className:`${l+1===t?"font-semibold text-green-600":""}`,"data-testid":`wizard-stepper-desktop-label-${l+1}`,children:i},l))})]})]})})}function TS({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:l,submitting:o,savingDraft:c,loadingDraft:d,isEditing:m}){return e.jsx("div",{className:"fixed sm:relative bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0 shadow-lg sm:shadow-none z-50","data-testid":"wizard-footer",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2 sm:gap-4 max-w-6xl mx-auto",children:[e.jsxs(E,{variant:"outline",onClick:r,disabled:t===1,size:"sm",className:"sm:size-lg order-2 sm:order-1","data-testid":"wizard-footer-prev-button",children:[e.jsx(Ns,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Previous"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 order-1 sm:order-2","data-testid":"wizard-footer-actions",children:[e.jsx(E,{variant:"outline",onClick:l,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:d||o||c,"data-testid":"wizard-footer-save-draft-button",children:c?e.jsxs(e.Fragment,{children:[e.jsx(lt,{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(E,{onClick:i,disabled:!a||d||o||c,size:"sm",className:"sm:size-lg bg-green-600 hover:bg-green-700 flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-submit-button",children:o?e.jsxs(e.Fragment,{children:[e.jsx(lt,{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(sx,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(E,{onClick:n,disabled:!a,size:"sm",className:"sm:size-lg flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-next-button",children:[e.jsx("span",{className:"hidden sm:inline",children:"Next Step"}),e.jsx("span",{className:"sm:hidden",children:"Next"}),e.jsx(ss,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const yu=t=>{switch(t){case"high":return e.jsx(ha,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Ot,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(ta,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Ot,{className:"w-4 h-4 text-gray-600"})}};function kS({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=p.useState("main"),l=Ks(),o=m=>{m.id==="admin-templates-category"?i("admin"):n==="admin"?l(`/create-admin-request/${m.id}`):a(m)},c=n==="main"?[...t]:r;return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"min-h-full flex flex-col items-center justify-center py-8","data-testid":"template-selection-step",children:[e.jsxs("div",{className:"text-center mb-12 max-w-3xl","data-testid":"template-selection-header",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4","data-testid":"template-selection-title",children:n==="main"?"Choose Your Request Type":"Organization Templates"}),e.jsx("p",{className:"text-lg text-gray-600","data-testid":"template-selection-description",children:n==="main"?"Start with a pre-built template for faster approvals, or create a custom request tailored to your needs.":"Select a pre-configured workflow template defined by your organization."})]}),n==="admin"&&e.jsx("div",{className:"w-full max-w-6xl mb-6 flex justify-start",children:e.jsxs(E,{variant:"ghost",className:"gap-2",onClick:()=>i("main"),children:[e.jsx(Ns,{className:"w-4 h-4"}),"Back to All Types"]})}),e.jsx("div",{className:"w-full max-w-6xl grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8","data-testid":"template-selection-grid",children:c.length===0&&n==="admin"?e.jsxs("div",{className:"col-span-full text-center py-12 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed border-gray-200",children:[e.jsx(i0,{className:"w-12 h-12 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No admin templates available yet."})]}):c.map(m=>{var g;const x=m.id==="admin-templates-category",u=(s==null?void 0:s.id)===m.id;return e.jsx(ts.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${m.id}`,children:e.jsxs(ee,{className:`h-full transition-all duration-300 border-2 ${u?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200 cursor-pointer":x?"border-blue-200 bg-blue-50/30 hover:border-blue-400 hover:shadow-lg cursor-pointer":"border-gray-200 hover:border-blue-300 hover:shadow-lg cursor-pointer"}`,onClick:()=>o(m),"data-testid":`template-card-${m.id}-clickable`,children:[e.jsxs(ge,{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 ${u||x?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${m.id}-icon`,children:e.jsx(m.icon,{className:`w-7 h-7 ${u||x?"text-blue-600":"text-gray-600"}`})}),u&&e.jsx(ts.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},"data-testid":`template-card-${m.id}-selected-indicator`,children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center",children:e.jsx(yr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsx(fe,{className:"text-xl","data-testid":`template-card-${m.id}-name`,children:m.name}),!1]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),yu(m.priority)]})]})]}),e.jsxs(se,{className:"pt-0 space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed line-clamp-2","data-testid":`template-card-${m.id}-description`,children:m.description}),!x&&e.jsxs(e.Fragment,{children:[e.jsx(Ts,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-estimated-time`,children:[e.jsx(st,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:m.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-approvers-count`,children:[e.jsx(cs,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[((g=m.commonApprovers)==null?void 0:g.length)||0," approvers"]})]})]})]}),x&&e.jsx("div",{className:"pt-2",children:e.jsx("p",{className:"text-xs text-blue-600 font-medium flex items-center gap-1",children:"Click to browse templates →"})})]})]})},m.id)})}),e.jsx(Ei,{children:s&&e.jsx(ts.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(ee,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Ur,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-sla",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Suggested SLA"}),e.jsxs("p",{className:"text-blue-700 mt-1",children:[s.suggestedSLA," hours"]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-priority",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[yu(s.priority),e.jsx("span",{className:"text-blue-700 capitalize",children:s.priority})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-duration",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Estimated Duration"}),e.jsx("p",{className:"text-blue-700 mt-1",children:s.estimatedTime})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-approvers",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((d=s.commonApprovers)==null?void 0:d.length)>0?s.commonApprovers.map((m,h)=>e.jsx(ne,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${h}`,children:m},`${s.id}-approver-${h}-${m}`)):e.jsx("span",{className:"text-sm text-gray-500 italic",children:"No specific approvers defined"})})]})]})]})})})]})}function Oe({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:ke("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 RS({className:t,...s}){return e.jsx(uf,{"data-slot":"radio-group",className:ke("grid gap-3",t),...s})}function vu({className:t,...s}){return e.jsx(xf,{"data-slot":"radio-group-item",className:ke("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(hf,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(l0,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function DS({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(ts.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(Re,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"basic-information-title",children:"Basic Information"}),e.jsxs("p",{className:"text-gray-600","data-testid":"basic-information-description",children:["Provide the essential details for your ",(s==null?void 0:s.name)||"request","."]})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"basic-information-form",children:[e.jsxs("div",{"data-testid":"basic-information-title-field",children:[e.jsx(re,{htmlFor:"title",className:"text-base font-semibold",children:"Request Title *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"Be specific and descriptive. This will be visible to all participants."}),e.jsx(Oe,{id:"title",placeholder:"e.g., Approval on new office location",value:t.title,onChange:r=>a("title",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-title-input"})]}),e.jsxs("div",{"data-testid":"basic-information-description-field",children:[e.jsx(re,{htmlFor:"description",className:"text-base font-semibold",children:"Detailed Description *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(Rn,{value:t.description||"",onChange:r=>a("description",r),placeholder:"Provide comprehensive details about your request including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px","data-testid":"basic-information-description-textarea"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6","data-testid":"basic-information-priority-section",children:e.jsxs("div",{"data-testid":"basic-information-priority-field",children:[e.jsx(re,{className:"text-base font-semibold",children:"Priority Level *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"select priority for your request"}),e.jsxs(RS,{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(vu,{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(xo,{className:"w-4 h-4 text-red-600"}),e.jsx(re,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(ne,{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(vu,{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(st,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(ne,{variant:"secondary",className:"text-xs",children:"DEFAULT"})]}),e.jsx("p",{className:"text-xs text-gray-600",children:"Includes working days in TAT - regular processing timeline"})]})]})]})]})}),((s==null?void 0:s.fields.amount)||(s==null?void 0:s.fields.vendor)||(s==null?void 0:s.fields.timeline)||(s==null?void 0:s.fields.impact))&&e.jsxs("div",{className:"border-t pt-6","data-testid":"basic-information-additional-details",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Additional Details"}),e.jsxs("div",{className:"space-y-6",children:[(s==null?void 0:s.fields.amount)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4","data-testid":"basic-information-amount-field",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(Oe,{id:"amount",placeholder:"Enter amount",value:t.amount,onChange:r=>a("amount",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-amount-input"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(We,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Ye,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"USD",children:"USD ($)"}),e.jsx(Y,{value:"EUR",children:"EUR (â‚Ŧ)"}),e.jsx(Y,{value:"GBP",children:"GBP (ÂŖ)"}),e.jsx(Y,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(re,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(Oe,{id:"vendor",placeholder:"Enter vendor or supplier name",value:t.vendor,onChange:r=>a("vendor",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-vendor-input"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{"data-testid":"basic-information-cost-center-field",children:[e.jsx(re,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(Oe,{id:"costCenter",placeholder:"e.g., Marketing, IT, Operations",value:t.costCenter,onChange:r=>a("costCenter",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-cost-center-input"})]}),e.jsxs("div",{"data-testid":"basic-information-project-field",children:[e.jsx(re,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(Oe,{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 Dp(){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 h=c.slice(1),u=((m=(await ia(h,d)).data)==null?void 0:m.data)||[];s(u)}catch(h){console.error("User search failed:",h),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await ra({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 Pp(){const[t,s]=p.useState({}),[a,r]=p.useState({}),n=p.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(o,c,d=10)=>{if(n.current[o]&&clearTimeout(n.current[o]),!c||!c.startsWith("@")||c.length<2){s(m=>({...m,[o]:[]})),r(m=>({...m,[o]:!1}));return}r(m=>({...m,[o]:!0})),n.current[o]=setTimeout(async()=>{var m;try{const h=c.slice(1),u=((m=(await ia(h,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:u}))}catch(h){console.error(`User search failed for index ${o}:`,h),s(x=>({...x,[o]:[]}))}finally{r(h=>({...h,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function PS({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var h;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=Pp();p.useEffect(()=>{const x=t.approverCount||1,u=t.approvers||[];if(u.lengthx&&s("approvers",u.slice(0,x))},[t.approverCount,s]);const d=(x,u)=>{var y,v,w,C,k;const g=[...t.approvers],f=((y=g[x])==null?void 0:y.email)!==u;if(g[x]={...g[x],email:u,level:x+1,userId:f||(v=g[x])==null?void 0:v.userId,name:f||(w=g[x])==null?void 0:w.name,department:f||(C=g[x])==null?void 0:C.department,avatar:f||(k=g[x])==null?void 0:k.avatar},s("approvers",g),!u||!u.startsWith("@")||u.length<2){c(x);return}o(x,u,10)},m=async(x,u)=>{var g,b;try{if((g=t.approvers)==null?void 0:g.some((C,k)=>{var S,_;return k!==x&&(C.userId===u.userId||((S=C.email)==null?void 0:S.toLowerCase())===((_=u.email)==null?void 0:_.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((b=t.spectators)==null?void 0:b.some(C=>{var k,S;return C.userId===u.userId||((k=C.email)==null?void 0:k.toLowerCase())===((S=u.email)==null?void 0:S.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 v=await ra({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[x]={...w[x],email:u.email,name:u.displayName||[u.firstName,u.lastName].filter(Boolean).join(" "),userId:v.userId,level:x+1},s("approvers",w),c(x)}catch(f){console.error("Failed to ensure user exists:",f),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(ts.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(cs,{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(ee,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(Va,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx($e,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(se,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(re,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const x=t.approverCount||1,u=Math.max(1,x-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(ho,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-2xl font-semibold w-12 text-center","data-testid":"approval-workflow-count-display",children:t.approverCount||1}),e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const u=(t.approverCount||1)+1;if(u>r.maxApprovalLevels){n([{type:"Maximum Approval Levels Exceeded",message:`Cannot add more than ${r.maxApprovalLevels} approval levels. Please remove an approver level or contact your administrator.`,currentValue:u,maxValue:r.maxApprovalLevels}]);return}s("approverCount",u)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(gs,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Maximum ",r.maxApprovalLevels," approver",r.maxApprovalLevels!==1?"s":""," allowed. Each approver will review sequentially."]})]})})]}),e.jsxs(ee,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(hs,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs($e,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsx("div",{className:"p-4 rounded-lg border-2 border-blue-200 bg-blue-50","data-testid":"approval-workflow-initiator-card",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center",children:e.jsx(Vt,{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(ne,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-sm text-blue-700",children:"Creates and submits the request"})]})]})}),Array.from({length:t.approverCount||1},(x,u)=>{var y,v;const g=u+1,b=g===(t.approverCount||1),f=t.approvers[u]||{email:"",tat:""};return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${g}`,children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-6 bg-gray-300"})}),e.jsx("div",{className:`p-4 rounded-lg border-2 transition-all ${f.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 ${f.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:g})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",g]}),b&&e.jsx(ne,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(re,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),f.email&&f.userId&&e.jsxs(ne,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Oe,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:f.email||"",onChange:w=>d(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-${g}-email-input`}),(l[u]||(((y=i[u])==null?void 0:y.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:l[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:(v=i[u])==null?void 0:v.map(w=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(u,w),"data-testid":`approval-workflow-approver-${g}-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-${g}-tat-field`,children:[e.jsx(re,{htmlFor:`tat-${g}`,className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Oe,{id:`tat-${g}`,type:"number",placeholder:f.tatType==="days"?"7":"24",min:"1",max:f.tatType==="days"?"30":"720",value:f.tat||"",onChange:w=>{const C=[...t.approvers];C[u]={...C[u],tat:parseInt(w.target.value)||"",level:g,tatType:f.tatType||"hours"},s("approvers",C)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(We,{value:f.tatType||"hours",onValueChange:w=>{const C=[...t.approvers];C[u]={...C[u],tatType:w,level:g,tat:""},s("approvers",C)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(Ye,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},g)})]})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ur,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900 mb-1",children:"Approval Flow Summary"}),e.jsxs("p",{className:"text-sm text-blue-700",children:["Your request will follow this sequence: ",e.jsx("strong",{children:"You (Initiator)"})," → ",Array.from({length:t.approverCount||1},(x,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(st,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const y=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+y:b+y/24},0))||0,u=Math.ceil(x);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:(h=t.approvers)==null?void 0:h.map((x,u)=>{const g=Number(x.tat||0),f=(x.tatType||"hours")==="days"?g*24:g;return g?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",u+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[f," ",f===1?"hour":"hours"]})]})},u):null})}),(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const y=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+y*24:b+y},0))||0,u=Math.ceil(x/8);return x===0?null:e.jsxs("div",{className:"bg-white/80 p-3 rounded border border-emerald-200",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[x,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children: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 IS({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=p.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=Dp(),h=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},x=async g=>{var b,f;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(w=>{var C,k;return w.userId===g.userId||((C=w.email)==null?void 0:C.toLowerCase())===((k=g.email)==null?void 0:k.toLowerCase())}),v=(b=t.approvers)==null?void 0:b.some(w=>{var C,k;return w.userId===g.userId||((C=w.email)==null?void 0:C.toLowerCase())===((k=g.email)==null?void 0:k.toLowerCase())});if(y){a({type:"error",email:g.email,message:"This user is already added as a spectator."});return}if(v){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 w=await m(g),C={id:w.userId,userId:w.userId,name:w.displayName||g.email.split("@")[0],email:w.email,avatar:(w.displayName||w.email).substring(0,2).toUpperCase(),role:"Spectator",department:w.department||"",level:1,canClose:!1},k=[...t.spectators,C];s("spectators",k),i(""),d()}catch{a({type:"error",email:g.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(w=>{var C;return((C=w.email)==null?void 0:C.toLowerCase())===n.toLowerCase()}),v=(f=t.approvers)==null?void 0:f.some(w=>{var C;return((C=w.email)==null?void 0:C.toLowerCase())===n.toLowerCase()});if(y){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(v){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}}},u=g=>{const b=t.spectators.filter(f=>f.id!==g);s("spectators",b)};return e.jsxs(ts.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(ht,{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(ee,{"data-testid":"participants-spectators-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{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(ht,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(ne,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx($e,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2","data-testid":"participants-spectators-add-section",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-full",children:[e.jsx(Oe,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>h(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.preventDefault(),await x())},className:"text-sm w-full","data-testid":"participants-spectators-email-input"}),(o||l.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:o?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:l.map(g=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>x(g),"data-testid":`participants-spectators-search-result-${g.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:g.displayName||g.email}),e.jsx("div",{className:"text-xs text-gray-600",children:g.email})]},g.userId))})})]}),e.jsx(E,{size:"sm",onClick:()=>x(),disabled:!n||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n),"data-testid":"participants-spectators-add-button",children:"Add"})]}),e.jsxs("p",{className:"text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded p-2 flex items-center gap-1",children:[e.jsx(Ur,{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(Zt,{className:"h-6 w-6",children:e.jsx(Jt,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(ft,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function ES({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:c,onDocumentErrors:d,fileInputRef:m}){const h=b=>{const f=Array.from(b.target.files||[]);if(f.length===0)return;const y=t.maxFileSizeMB*1024*1024,v=[],w=[];f.forEach(C=>{if(C.size>y){v.push({fileName:C.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(C.size/1048576).toFixed(2)}MB`});return}const k=C.name.toLowerCase(),S=k.substring(k.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(S)){v.push({fileName:C.name,reason:`File type "${S}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}w.push(C)}),w.length>0&&i([...a,...w]),v.length>0&&d&&d(v),b.target&&(b.target.value="")},x=b=>{const f=a.filter((y,v)=>v!==b);i(f)},u=b=>{o([...n,b])},g=(b,f=!1)=>{if(f){const y=(b.fileType||b.file_type||"").toLowerCase(),v=(b.originalFileName||b.fileName||"").toLowerCase();return y.includes("image")||y.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}else{const y=(b.type||"").toLowerCase(),v=(b.name||"").toLowerCase();return y.includes("image")||y.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}};return e.jsxs(ts.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(zs,{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(ee,{"data-testid":"documents-upload-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs($e,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(se,{children:e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-gray-400 transition-colors","data-testid":"documents-upload-area",children:[e.jsx(zs,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"click to browse"}),e.jsx("input",{type:"file",multiple:!0,accept:t.allowedFileTypes.map(b=>`.${b}`).join(","),onChange:h,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(E,{variant:"outline",size:"lg",type:"button",onClick:()=>{var b;return(b=m.current)==null?void 0:b.click()},"data-testid":"documents-browse-button",children:[e.jsx(gs,{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(b=>b.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(ee,{"data-testid":"documents-existing-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ne,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length," file",r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length!==1?"s":""]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(b=>{const f=b.documentId||b.document_id||"";return n.includes(f)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${f}`,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(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.originalFileName||b.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:b.fileSize?(Number(b.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!0)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>c(b,!0),"data-testid":`documents-existing-${f}-preview`,children:e.jsx(ht,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(f),"data-testid":`documents-existing-${f}-delete`,children:e.jsx(ft,{className:"h-4 w-4 text-red-600"})})]})]},f)})})})]}),a.length>0&&e.jsxs(ee,{"data-testid":"documents-new-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ne,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((b,f)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${f}`,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(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(b.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!1)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>c(b,!1),"data-testid":`documents-new-${f}-preview`,children:e.jsx(ht,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>x(f),"data-testid":`documents-new-${f}-remove`,children:e.jsx(ft,{className:"h-4 w-4"})})]})]},f))})})]})]})]})}const FS=t=>{switch(t){case"high":return e.jsx(ha,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Ot,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(ta,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Ot,{className:"w-4 h-4 text-gray-600"})}};function _S({formData:t,selectedTemplate:s}){return e.jsxs(ts.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(De,{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(ee,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(sx,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6","data-testid":"review-submit-overview-grid",children:[e.jsxs("div",{"data-testid":"review-submit-overview-type",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Request Type"}),e.jsx("p",{className:"text-green-800 mt-1",children:s==null?void 0:s.name}),e.jsx(ne,{variant:"outline",className:"mt-2 text-xs border-green-300 text-green-700",children:s==null?void 0:s.category})]}),e.jsxs("div",{"data-testid":"review-submit-overview-priority",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[FS(t.priority),e.jsx("span",{className:"text-green-800 capitalize",children:t.priority})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-workflow",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Workflow Type"}),e.jsx("p",{className:"text-green-800 mt-1 capitalize",children:t.workflowType}),e.jsxs("p",{className:"text-sm text-green-700",children:[t.approverCount||1," Level",(t.approverCount||1)>1?"s":""]})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-title",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Request Title"}),e.jsx("p",{className:"text-green-800 font-medium mt-1 text-lg",children:t.title})]})]})]}),e.jsxs(ee,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(re,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(sa,{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(Da,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{className:"font-semibold text-blue-900",children:"Financial Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Amount"}),e.jsxs("p",{className:"font-semibold text-blue-900",children:[t.amount," ",t.currency]})]}),t.costCenter&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Cost Center"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.costCenter})]})]})]})]})]}),e.jsxs(ee,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(cs,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx($e,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(se,{className:"space-y-6",children:e.jsx("div",{className:"space-y-4","data-testid":"review-submit-approval-levels",children:Array.from({length:t.approverCount||1},(a,r)=>{const n=r+1,i=n===(t.approverCount||1),l=t.approvers[r];return e.jsx("div",{className:"p-4 bg-white rounded-lg border border-orange-200","data-testid":`review-submit-approval-level-${n}`,children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${l!=null&&l.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:n})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",n]}),i&&e.jsx(ne,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Email Address"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:(l==null?void 0:l.email)||"Not assigned"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"TAT (Turn Around Time)"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l!=null&&l.tat?`${l.tat} ${l.tatType==="days"?"day":"hour"}${l.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(ee,{"data-testid":"review-submit-participants-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(ht,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(se,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(re,{className:"font-semibold text-sm",children:["Spectators (",t.spectators.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:t.spectators.map(a=>e.jsxs(ne,{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(ee,{"data-testid":"review-submit-documents-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(zs,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs($e,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"review-submit-documents-list",children:t.documents.map((a,r)=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-gray-50 rounded-lg border","data-testid":`review-submit-document-${r}`,children:[e.jsx(Re,{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(ee,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(se,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(De,{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 LS({isEditing:t,currentStep:s,totalSteps:a,stepNames:r,onBack:n}){return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0","data-testid":"create-request-header",children:e.jsxs("div",{className:"flex items-center justify-between max-w-6xl mx-auto gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-1 min-w-0",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"create-request-back-button",children:e.jsx(Ns,{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 MS({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(Ei,{mode:"wait",children:t})})})}function $S({modal:t,onClose:s}){return e.jsx(pt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Dt,{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(Ni,{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(Tt,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function OS({modal:t,documentPolicy:s,onClose:a}){return e.jsx(pt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Dt,{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(Tt,{children:e.jsx(E,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function ju({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Ea(),i=Ks(),l=n.requestId||a||"",o=r&&!!l,{user:c}=Kt(),[d,m]=p.useState([]);p.useEffect(()=>{(async()=>{try{const rt=(await Mi()).map(ut=>({id:ut.id,name:ut.name,description:ut.description,category:ut.category,icon:Re,estimatedTime:ut.estimatedTime,commonApprovers:ut.approvers.map(nt=>nt.name),workflowApprovers:ut.approvers,suggestedSLA:ut.suggestedSLA,priority:ut.priority,fields:ut.fields||{}}));m(rt)}catch(_e){console.error("Failed to fetch admin templates:",_e)}})()},[]);const h=p.useMemo(()=>[...fu,...d],[d]),{formData:x,updateFormData:u,selectedTemplate:g,setSelectedTemplate:b,loadingDraft:f,systemPolicy:y,documentPolicy:v,existingDocuments:w,setExistingDocuments:C}=oS(o,l,h),{currentStep:k,totalSteps:S,stepNames:_,isStepValid:D,nextStep:A,prevStep:N}=cS(o,g,x),[P,R]=p.useState([]),[O,F]=p.useState([]),$=p.useRef(null),{validationModal:V,policyViolationModal:T,documentErrorModal:j,openValidationModal:U,closeValidationModal:I,openPolicyViolationModal:M,closePolicyViolationModal:W,openDocumentErrorModal:G,closeDocumentErrorModal:ce}=dS(),{submitting:te,savingDraft:L,handleSubmit:z,handleSaveDraft:H}=pS({formData:x,selectedTemplate:g,documents:P,documentsToDelete:O,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:ye,setShowTemplateModal:ae,previewDocument:me,selectTemplate:Q,handleTemplateSelection:oe,nextStep:Ce,prevStep:Ee,handlePreviewDocument:be,closePreview:q}=CS({selectedTemplate:g,setSelectedTemplate:b,updateFormData:u,formData:x,currentStep:k,isStepValid:D,wizardNextStep:A,wizardPrevStep:N,user:c,openValidationModal:U,systemPolicy:y,onPolicyViolation:M,onSubmit:s}),ue=p.useCallback(()=>{if(k===1){i("/dashboard",{replace:!0});return}k===3||k===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Ee()},[k,t,i,Ee]),Ae=p.useRef(!0),Ue=p.useRef(!1);p.useEffect(()=>{Ae.current&&x.documents&&x.documents.length>0&&!Ue.current&&(R(x.documents),Ue.current=!0),Ae.current=!1},[x.documents]);const Z=p.useRef(!1),Te=p.useRef(P);p.useEffect(()=>{if(Z.current){Z.current=!1,Te.current=P;return}Te.current!==P&&(u("documents",P),Te.current=P)},[P]);const Xe=()=>{switch(k){case 1:return e.jsx(kS,{templates:fu,selectedTemplate:g,onSelectTemplate:Q,adminTemplates:d});case 2:return e.jsx(DS,{formData:x,selectedTemplate:g,updateFormData:u});case 3:return e.jsx(PS,{formData:x,updateFormData:u,systemPolicy:y,onValidationError:pe=>U(pe.type,pe.email,pe.message),onPolicyViolation:M});case 4:return e.jsx(IS,{formData:x,updateFormData:u,onValidationError:pe=>U(pe.type,pe.email,pe.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(ES,{documentPolicy:v,isEditing:o,documents:P,existingDocuments:w,documentsToDelete:O,onDocumentsChange:R,onExistingDocumentsChange:C,onDocumentsToDeleteChange:F,onPreviewDocument:be,onDocumentErrors:pe=>G(pe),fileInputRef:$});case 6:return e.jsx(_S,{formData:x,selectedTemplate:g});default:return null}};return f?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(LS,{isEditing:o,currentStep:k,totalSteps:S,stepNames:_,onBack:ue}),e.jsx(Rp,{currentStep:k,totalSteps:S,stepNames:_}),e.jsx(MS,{children:Xe()}),e.jsx(TS,{currentStep:k,totalSteps:S,isStepValid:D(),onPrev:Ee,onNext:Ce,onSubmit:z,onSaveDraft:H,submitting:te,savingDraft:L,loadingDraft:f,isEditing:o}),e.jsx(K2,{open:ye,onClose:()=>ae(!1),onSelectTemplate:oe}),me&&e.jsx(jr,{fileName:me.fileName,fileType:me.fileType,fileUrl:me.fileUrl,fileSize:me.fileSize,open:!!me,onClose:q,onDownload:async()=>{if(me.file){const pe=document.createElement("a");pe.href=me.fileUrl,pe.download=me.fileName,document.body.appendChild(pe),pe.click(),document.body.removeChild(pe)}else me.documentId&&await ps(me.documentId)},attachmentId:me.documentId}),e.jsx($S,{modal:V,onClose:I}),e.jsx(OS,{modal:j,documentPolicy:v,onClose:ce}),e.jsx(Fn,{open:T.open,onClose:W,violations:T.violations,policyDetails:{maxApprovalLevels:y.maxApprovalLevels,maxParticipants:y.maxParticipants,allowSpectators:y.allowSpectators,maxSpectators:y.maxSpectators}})]})}function $i({className:t,...s}){return e.jsx(pf,{"data-slot":"tabs",className:ke("flex flex-col gap-2",t),...s})}function Oi({className:t,...s}){return e.jsx(gf,{"data-slot":"tabs-list",className:ke("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function qt({className:t,...s}){return e.jsx(ff,{"data-slot":"tabs-trigger",className:ke("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 es({className:t,...s}){return e.jsx(bf,{"data-slot":"tabs-content",className:ke("flex-1 outline-none",t),...s})}function hc(t,s=[],a){const[r,n]=p.useState(null),[i,l]=p.useState(!1),[o,c]=p.useState(!0),[d,m]=p.useState(null),[h,x]=p.useState(null),[u,g]=p.useState(!1),b=(k,S)=>(k||S||"NA").toString().split(" ").map(D=>D[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),f=k=>{const S=(k||"").toUpperCase();return S==="IN_PROGRESS"?"in-review":S==="PENDING"?"pending":S==="APPROVED"?"approved":S==="REJECTED"?"rejected":S==="CLOSED"?"closed":S==="SKIPPED"?"skipped":(k||"").toLowerCase()},y=p.useCallback(async()=>{var k,S,_,D,A,N,P,R,O,F,$,V,T;l(!0);try{const j=await ks.getWorkflowDetails(t);if(!j){console.warn("[useRequestDetails] No details returned from API");return}const U=j.workflow||{},I=Array.isArray(j.approvals)?j.approvals:[],M=Array.isArray(j.participants)?j.participants:[],W=Array.isArray(j.documents)?j.documents:[],G=j.summary||{},ce=Array.isArray(j.tatAlerts)?j.tatAlerts:[];ce.length>0;const te=(G==null?void 0:G.currentLevel)||U.currentLevel||1,L=I.map(Z=>{const Te=Z.levelNumber||0,Xe=(Z.status||"").toString().toUpperCase(),pe=Z.levelId||Z.level_id;let _e=f(Z.status);Te>te&&Xe!=="APPROVED"&&Xe!=="REJECTED"?_e="waiting":Te===te&&Xe==="PENDING"&&(_e="pending");const rt=ce.filter(ut=>ut.levelId===pe);return{step:Te,levelId:pe,role:Z.levelName||Z.approverName||"Approver",status:_e,approver:Z.approverName||Z.approverEmail,approverId:Z.approverId||Z.approver_id,approverEmail:Z.approverEmail,tatHours:Number(Z.tatHours||0),elapsedHours:Number(Z.elapsedHours||0),remainingHours:Number(Z.remainingHours||0),tatPercentageUsed:Number(Z.tatPercentageUsed||0),actualHours:Z.levelEndTime&&Z.levelStartTime?Math.max(0,(new Date(Z.levelEndTime).getTime()-new Date(Z.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:Z.comments||void 0,timestamp:Z.actionDate||void 0,levelStartTime:Z.levelStartTime||Z.tatStartTime,tatAlerts:rt,skipReason:Z.skipReason||void 0,isSkipped:Xe==="SKIPPED"||Z.isSkipped||!1}}),z=M.filter(Z=>(Z.participantType||Z.participant_type||"").toUpperCase()==="SPECTATOR").map(Z=>({name:Z.userName||Z.user_name||Z.userEmail||Z.user_email,role:"Spectator",email:Z.userEmail||Z.user_email,avatar:b(Z.userName||Z.user_name,Z.userEmail||Z.user_email)})),H=Z=>{var Xe,pe;if(!Z)return;const Te=M.find(_e=>_e.userId===Z||_e.user_id===Z);return Te!=null&&Te.userName||Te!=null&&Te.user_name?Te.userName||Te.user_name:U.initiatorId===Z?((Xe=U.initiator)==null?void 0:Xe.displayName)||((pe=U.initiator)==null?void 0:pe.email):Z},ye=W.map(Z=>{const Te=Number(Z.fileSize||Z.file_size||0),Xe=(Te/(1024*1024)).toFixed(2)+" MB";return{documentId:Z.documentId||Z.document_id,name:Z.originalFileName||Z.fileName||Z.file_name,fileType:Z.fileType||Z.file_type||"",size:Xe,sizeBytes:Te,uploadedBy:H(Z.uploadedBy||Z.uploaded_by),uploadedAt:Z.uploadedAt||Z.uploaded_at}}),ae=Array.isArray(j.activities)?j.activities.filter(Z=>(Z.type||"").toLowerCase()!=="sla_warning"):[];let me=null;if(U.isPaused||!1)try{me=await Zd(U.requestId)}catch{}let oe=null,Ce=null,Ee=null,be=null;if(U.workflowType==="CLAIM_MANAGEMENT"||U.templateType==="claim-management")try{const Z=await je.get(`/dealer-claims/${U.requestId}`),Te=((k=Z.data)==null?void 0:k.data)||Z.data;if(Te){oe=Te.claimDetails||Te.claim_details,Ce=Te.proposalDetails||Te.proposal_details,Ee=Te.completionDetails||Te.completion_details,be=Te.internalOrder||Te.internal_order||null;const Xe=Te.budgetTracking||Te.budget_tracking||null,pe=Te.invoice||null,_e=Te.creditNote||Te.credit_note||null,rt=Te.completionExpenses||Te.completion_expenses||null;oe&&(oe.budgetTracking=Xe,oe.invoice=pe,oe.creditNote=_e,oe.completionExpenses=rt)}else console.warn("[useRequestDetails] No claimData found in response")}catch(Z){console.error("[useRequestDetails] Error fetching claim details:",{error:(Z==null?void 0:Z.message)||Z,status:(S=Z==null?void 0:Z.response)==null?void 0:S.status,statusText:(_=Z==null?void 0:Z.response)==null?void 0:_.statusText,responseData:(D=Z==null?void 0:Z.response)==null?void 0:D.data,requestId:U.requestId})}const q={...U,id:U.requestNumber||U.requestId,requestId:U.requestId,requestNumber:U.requestNumber,title:U.title,description:U.description,status:f(U.status),priority:(U.priority||"").toString().toLowerCase(),workflowType:U.workflowType||(U.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:L,approvals:I,participants:M,documents:ye,spectators:z,summary:G,sla:(G==null?void 0:G.sla)||U.sla||null,initiator:{name:((A=U.initiator)==null?void 0:A.displayName)||((N=U.initiator)==null?void 0:N.email),role:((P=U.initiator)==null?void 0:P.designation)||void 0,department:((R=U.initiator)==null?void 0:R.department)||void 0,email:((O=U.initiator)==null?void 0:O.email)||void 0,phone:((F=U.initiator)==null?void 0:F.phone)||void 0,avatar:b(($=U.initiator)==null?void 0:$.displayName,(V=U.initiator)==null?void 0:V.email)},createdAt:U.createdAt,updatedAt:U.updatedAt,totalSteps:U.totalLevels||1,currentStepRaw:(G==null?void 0:G.currentLevel)||U.currentLevel||1,currentStep:Math.min(Math.max(1,(G==null?void 0:G.currentLevel)||U.currentLevel||1),U.totalLevels||1),auditTrail:ae,conclusionRemark:U.conclusionRemark||null,closureDate:U.closureDate||null,pauseInfo:me||null,claimDetails:oe||null,proposalDetails:Ce||null,completionDetails:Ee||null,internalOrder:be||null,budgetTracking:(oe==null?void 0:oe.budgetTracking)||null,invoice:(oe==null?void 0:oe.invoice)||null,creditNote:(oe==null?void 0:oe.creditNote)||null,completionExpenses:(oe==null?void 0:oe.completionExpenses)||null};n(q);const ue=(T=a==null?void 0:a.email)==null?void 0:T.toLowerCase(),Ae=I.find(Z=>{const Te=(Z.status||"").toString().toUpperCase(),Xe=(Z.approverEmail||"").toLowerCase(),pe=Z.levelNumber||0;return(Te==="PENDING"||Te==="IN_PROGRESS"||Te==="PAUSED")&&Xe===ue&&pe===te});x(Ae||null);const Ue=a==null?void 0:a.userId;if(Ue){const Z=M.some(Te=>(Te.participantType||Te.participant_type||"").toUpperCase()==="SPECTATOR"&&(Te.userId||Te.user_id)===Ue);g(Z)}else g(!1)}catch(j){console.error("[useRequestDetails] Error refreshing details:",j),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);p.useEffect(()=>{if(!t){c(!1);return}let k=!0;return c(!0),m(null),(async()=>{var S,_,D,A,N,P,R,O,F,$,V,T,j,U;try{const I=await ks.getWorkflowDetails(t);if(!k||!I){k&&c(!1);return}const M=I.workflow||{},W=Array.isArray(I.approvals)?I.approvals:[],G=Array.isArray(I.participants)?I.participants:[],ce=Array.isArray(I.documents)?I.documents:[],te=I.summary||{},L=Array.isArray(I.tatAlerts)?I.tatAlerts:[],z=(M.priority||"").toString().toLowerCase(),H=(te==null?void 0:te.currentLevel)||M.currentLevel||1,ye=W.map(pe=>{const _e=pe.levelNumber||0,rt=(pe.status||"").toString().toUpperCase(),ut=pe.levelId||pe.level_id;let nt=f(pe.status);rt==="PAUSED"?nt="paused":_e>H&&rt!=="APPROVED"&&rt!=="REJECTED"?nt="waiting":_e===H&&(rt==="PENDING"||rt==="IN_PROGRESS")&&(nt=rt==="IN_PROGRESS"?"in-review":"pending");const Ps=L.filter(Xs=>Xs.levelId===ut);return{step:_e,levelId:ut,role:pe.levelName||pe.approverName||"Approver",status:nt,approver:pe.approverName||pe.approverEmail,approverId:pe.approverId||pe.approver_id,approverEmail:pe.approverEmail,tatHours:Number(pe.tatHours||0),elapsedHours:Number(pe.elapsedHours||0),remainingHours:Number(pe.remainingHours||0),tatPercentageUsed:Number(pe.tatPercentageUsed||0),actualHours:pe.elapsedHours!==void 0&&pe.elapsedHours!==null?Number(pe.elapsedHours):void 0,comment:pe.comments||void 0,timestamp:pe.actionDate||void 0,levelStartTime:pe.levelStartTime||pe.tatStartTime,tatAlerts:Ps}}),ae=G.filter(pe=>(pe.participantType||"").toUpperCase()==="SPECTATOR").map(pe=>({name:pe.userName||pe.userEmail,role:"Spectator",avatar:b(pe.userName,pe.userEmail)})),me=pe=>{var rt,ut;if(!pe)return;const _e=G.find(nt=>nt.userId===pe);return _e!=null&&_e.userName?_e.userName:M.initiatorId===pe?((rt=M.initiator)==null?void 0:rt.displayName)||((ut=M.initiator)==null?void 0:ut.email):pe},Q=ce.map(pe=>{const _e=Number(pe.fileSize||0),rt=(_e/(1024*1024)).toFixed(2)+" MB";return{documentId:pe.documentId||pe.document_id,name:pe.originalFileName||pe.fileName,fileType:pe.fileType||pe.file_type||"",size:rt,sizeBytes:_e,uploadedBy:me(pe.uploadedBy),uploadedAt:pe.uploadedAt}}),oe=Array.isArray(I.activities)?I.activities.filter(pe=>(pe.type||"").toLowerCase()!=="sla_warning"):[];let Ce=null;if(M.isPaused||!1)try{Ce=await Zd(M.requestId)}catch{}let be=null,q=null,ue=null,Ae=null;if(M.workflowType==="CLAIM_MANAGEMENT"||M.templateType==="claim-management")try{const pe=await je.get(`/dealer-claims/${M.requestId}`),_e=((S=pe.data)==null?void 0:S.data)||pe.data;if(_e){be=_e.claimDetails||_e.claim_details,q=_e.proposalDetails||_e.proposal_details,ue=_e.completionDetails||_e.completion_details,Ae=_e.internalOrder||_e.internal_order||null;const rt=_e.budgetTracking||_e.budget_tracking||null,ut=_e.invoice||null,nt=_e.creditNote||_e.credit_note||null,Ps=_e.completionExpenses||_e.completion_expenses||null;be&&(be.budgetTracking=rt,be.invoice=ut,be.creditNote=nt,be.completionExpenses=Ps)}}catch(pe){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(pe==null?void 0:pe.message)||pe,status:(_=pe==null?void 0:pe.response)==null?void 0:_.status,requestId:M.requestId})}const Ue={id:M.requestNumber||M.requestId,requestId:M.requestId,title:M.title,description:M.description,priority:z,status:f(M.status),workflowType:M.workflowType||(M.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:te,initiator:{name:((D=M.initiator)==null?void 0:D.displayName)||((A=M.initiator)==null?void 0:A.email),role:((N=M.initiator)==null?void 0:N.designation)||void 0,department:((P=M.initiator)==null?void 0:P.department)||void 0,email:((R=M.initiator)==null?void 0:R.email)||void 0,phone:((O=M.initiator)==null?void 0:O.phone)||void 0,avatar:b((F=M.initiator)==null?void 0:F.displayName,($=M.initiator)==null?void 0:$.email)},createdAt:M.createdAt,updatedAt:M.updatedAt,totalSteps:M.totalLevels||1,currentStepRaw:(te==null?void 0:te.currentLevel)||M.currentLevel||1,currentStep:Math.min(Math.max(1,(te==null?void 0:te.currentLevel)||M.currentLevel||1),M.totalLevels||1),approvalFlow:ye,approvals:W,documents:Q,spectators:ae,auditTrail:oe,conclusionRemark:M.conclusionRemark||null,closureDate:M.closureDate||null,pauseInfo:Ce||null,claimDetails:be||null,proposalDetails:q||null,completionDetails:ue||null,internalOrder:Ae||null,budgetTracking:(be==null?void 0:be.budgetTracking)||null,invoice:(be==null?void 0:be.invoice)||null,creditNote:(be==null?void 0:be.creditNote)||null,completionExpenses:(be==null?void 0:be.completionExpenses)||null};n(Ue);const Z=(V=a==null?void 0:a.email)==null?void 0:V.toLowerCase(),Te=W.find(pe=>{const _e=(pe.status||"").toString().toUpperCase(),rt=(pe.approverEmail||"").toLowerCase(),ut=pe.levelNumber||0;return(_e==="PENDING"||_e==="IN_PROGRESS"||_e==="PAUSED")&&rt===Z&&ut===H});x(Te||null);const Xe=a==null?void 0:a.userId;if(Xe){const pe=G.some(_e=>(_e.participantType||"").toUpperCase()==="SPECTATOR"&&_e.userId===Xe);g(pe)}else g(!1)}catch(I){if(console.error("[useRequestDetails] Error loading request details:",I),k){if(((T=I==null?void 0:I.response)==null?void 0:T.status)===403){const M=((U=(j=I==null?void 0:I.response)==null?void 0:j.data)==null?void 0:U.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:M})}n(null)}}finally{k&&c(!1)}})(),()=>{k=!1}},[t,a]);const v=p.useMemo(()=>{if(r)return r;const k=s.find(S=>S.id===t||S.requestNumber===t||S.request_number===t);return k||null},[t,s,r]),w=p.useMemo(()=>{var _,D,A;if(!v||!a)return!1;const k=(_=a==null?void 0:a.email)==null?void 0:_.toLowerCase(),S=(A=(D=v.initiator)==null?void 0:D.email)==null?void 0:A.toLowerCase();return k===S},[v,a]),C=p.useMemo(()=>{var S;if(!v)return[];const k=[];return(S=v.initiator)!=null&&S.email&&k.push({email:v.initiator.email.toLowerCase(),participantType:"INITIATOR",name:v.initiator.name}),v.approvalFlow&&Array.isArray(v.approvalFlow)&&v.approvalFlow.forEach(_=>{_.approverEmail&&k.push({email:_.approverEmail.toLowerCase(),participantType:"APPROVER",name:_.approver})}),v.spectators&&Array.isArray(v.spectators)&&v.spectators.forEach(_=>{_.email&&k.push({email:_.email.toLowerCase(),participantType:"SPECTATOR",name:_.name})}),v.participants&&Array.isArray(v.participants)&&v.participants.forEach(_=>{const D=(_.userEmail||_.email||"").toLowerCase(),A=(_.participantType||_.participant_type||"").toUpperCase(),N=_.userName||_.user_name||_.name;D&&A&&!k.find(P=>P.email===D)&&k.push({email:D,participantType:A,name:N})}),k},[v]);return p.useEffect(()=>{if(!t||!r)return;const k=Lr();if(!k)return;const S=_=>{((_==null?void 0:_.requestId)===r.requestId||(_==null?void 0:_.requestNumber)===t)&&y()};return k.on("request:updated",S),()=>{k.off("request:updated",S)}},[t,r,y]),{request:v,apiRequest:r,loading:o,refreshing:i,refreshDetails:y,currentApprovalLevel:h,isSpectator:u,isInitiator:w,existingParticipants:C,accessDenied:d}}function Ip(t,s,a,r){const[n,i]=p.useState([]),[l,o]=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,h=t;return(async()=>{var b;try{const f=await ks.getWorkflowDetails(t);(b=f==null?void 0:f.workflow)!=null&&b.requestId&&m&&(h=f.workflow.requestId)}catch(f){console.error("[useRequestSocket] Failed to resolve UUID:",f)}if(!m)return;const x=Lr();if(!x){console.error("[useRequestSocket] Socket not available");return}const u=r==null?void 0:r.userId,g=()=>{Ml(x,h,u)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),Ax(x,h))}})(),()=>{m=!1}},[t,r]),p.useEffect(()=>{!t||!s||(async()=>{try{const m=await Fr(t),h=s.auditTrail||[],x=[...m,...h];x.sort((u,g)=>{const b=new Date(u.createdAt||u.created_at||u.timestamp||0).getTime(),f=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return b-f}),i(x)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),p.useEffect(()=>{if(!t)return;const m=Lr();if(!m)return;const h=u=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await Fr(t),b=(s==null?void 0:s.auditTrail)||[],f=[...g,...b].sort((y,v)=>{const w=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime(),C=new Date(v.createdAt||v.created_at||v.timestamp||0).getTime();return w-C});i(f)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},x=u=>{const g=u.type==="breach"?"⏰":u.type==="threshold2"?"âš ī¸":"âŗ";(async()=>{try{const b=await ks.getWorkflowDetails(t);b&&(Array.isArray(b.tatAlerts)&&b.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:u.message,icon:"/favicon.ico",tag:`tat-${u.requestId}-${u.type}`,requireInteraction:!1}))}catch(b){console.error("[useRequestSocket] Failed to refresh after TAT alert:",b)}})()};return m.on("noteHandler",h),m.on("worknote:new",h),m.on("tat:alert",x),()=>{m.off("noteHandler",h),m.off("worknote:new",h),m.off("tat:alert",x)}},[t,a,s]),p.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function nn(t,s,a="SUPPORTING"){var l;const r=new FormData;r.append("file",t),r.append("requestId",s),r.append("category",a);const n=await je.post("/documents",r,{headers:{"Content-Type":"multipart/form-data"}}),i=((l=n.data)==null?void 0:l.data)||n.data;return{documentId:(i==null?void 0:i.documentId)||(i==null?void 0:i.document_id)||"",storageUrl:(i==null?void 0:i.storageUrl)||(i==null?void 0:i.storage_url),fileName:(i==null?void 0:i.fileName)||(i==null?void 0:i.file_name)||t.name,originalFileName:(i==null?void 0:i.originalFileName)||(i==null?void 0:i.original_file_name)||t.name}}function Ep(t,s){const[a,r]=p.useState(!1),[n,i]=p.useState(null),[l,o]=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 Ys("DOCUMENT_POLICY"),b={};g.forEach(w=>{b[w.configKey]=w.configValue});const f=parseInt(b.MAX_FILE_SIZE_MB||"10"),v=(b.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(w=>w.trim().toLowerCase());o({maxFileSizeMB:f,allowedFileTypes:v})}catch(g){console.error("Failed to load document policy:",g)}})()},[]);const m=u=>{const g=l.maxFileSizeMB*1024*1024;if(u.size>g)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${l.maxFileSizeMB}MB. Current size: ${(u.size/(1024*1024)).toFixed(2)}MB`};const b=u.name.toLowerCase(),f=b.substring(b.lastIndexOf(".")+1);return l.allowedFileTypes.includes(f)?{valid:!0}:{valid:!1,reason:`File type "${f}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},h=async u=>{var v,w;const g=u.target.files;if(!g||g.length===0)return;const b=Array.from(g),f=[],y=[];if(b.forEach(C=>{const k=m(C);k.valid?y.push(C):f.push({fileName:C.name,reason:k.reason||"Unknown validation error"})}),f.length>0&&d({show:!0,errors:f}),y.length===0){u.target&&(u.target.value="");return}r(!0);try{const C=y[0],k=t==null?void 0:t.requestId;if(!k){K.error("Request ID not found");return}C&&await nn(C,k,"SUPPORTING"),await s(),y.length{const u=document.createElement("input");u.type="file",u.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),u.onchange=h,u.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}const US="modulepreload",BS=function(t){return"/"+t},Nu={},jl=function(s,a,r){let n=Promise.resolve();if(a&&a.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));n=Promise.allSettled(a.map(c=>{if(c=BS(c),c in Nu)return;Nu[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":US,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((x,u)=>{h.addEventListener("load",x),h.addEventListener("error",()=>u(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return n.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};function Fp(t,s,a,r,n,i,l){const[o,c]=p.useState(""),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(!1),[b,f]=p.useState(0),[y,v]=p.useState(!1),[w,C]=p.useState(!1),[k,S]=p.useState(0),_=async()=>{var R;const N=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),P=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(N||P){c(N||P),g(!!P);return}try{const{getConclusion:O}=await jl(async()=>{const{getConclusion:$}=await import("./conclusionApi-CeHB_4RC.js");return{getConclusion:$}},__vite__mapDeps([0,1,2,3,4,5,6,7])),F=await O(t.requestId||s);F&&(F.aiGeneratedRemark||F.finalRemark)&&(c(F.finalRemark||F.aiGeneratedRemark||""),g(!!F.aiGeneratedRemark))}catch(O){((R=O==null?void 0:O.response)==null?void 0:R.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",O)}},D=async()=>{if(!w)try{m(!0),v(!1);const{generateConclusion:N}=await jl(async()=>{const{generateConclusion:F}=await import("./conclusionApi-CeHB_4RC.js");return{generateConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7])),P=await N(t.requestId||s),R=b+1;if(f(R),!(P!=null&&P.aiGeneratedRemark)||P.aiGeneratedRemark.toLowerCase().includes("unable to generate")||P.aiGeneratedRemark.toLowerCase().includes("sorry")){const F=k+1;S(F),F>=2?(C(!0),i==null||i({success:!1,title:"AI Generation Limit Reached",message:"We're unable to process a conclusion remark at this time after 2 attempts. Please proceed with a manual approach using the editor below."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process a conclusion remark at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0),c((P==null?void 0:P.aiGeneratedRemark)||""),g(!1);return}c(P.aiGeneratedRemark),g(!0),S(0),R>=2&&(C(!0),i==null||i({success:!0,title:"Maximum Attempts Reached",message:"You've reached the maximum of 2 regeneration attempts. Feel free to manually edit the current suggestion to fit your specific needs."}),l==null||l(!0))}catch(N){console.error("[useConclusionRemark] AI generation failed:",N);const P=k+1;S(P),g(!1),P>=2?(C(!0),i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. Since the maximum of 2 attempts is reached, please proceed with a manual approach."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0)}finally{m(!1)}},A=async()=>{var P,R;const N=o.replace(/<[^>]*>/g,"").trim();if(!N){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),l==null||l(!0);return}if(N.length>2e3){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark exceeds 2000 characters limit"}),l==null||l(!0);return}try{x(!0);const{finalizeConclusion:O}=await jl(async()=>{const{finalizeConclusion:F}=await import("./conclusionApi-CeHB_4RC.js");return{finalizeConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await O(t.requestId||s,o),i==null||i({success:!0,title:"Request Closed with Successful Completion",message:"The request has been finalized and moved to Closed Requests."}),l==null||l(!0),await r(),setTimeout(()=>{n?(n(),setTimeout(()=>{window.location.hash="#/closed-requests"},100)):window.location.hash="#/closed-requests"},2e3)}catch(O){i==null||i({success:!1,title:"Error",message:((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{x(!1)}};return p.useEffect(()=>{var F;const N=(F=t==null?void 0:t.status)==null?void 0:F.toLowerCase();if(!((N==="approved"||N==="rejected"||N==="closed")&&a&&!o))return;const R=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),O=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);R||O?(c(R||O),g(!!O)):_()},[t==null?void 0:t.status,t==null?void 0:t.conclusionRemark,t==null?void 0:t.aiGeneratedConclusion,a,o]),{conclusionRemark:o,setConclusionRemark:c,conclusionLoading:d,conclusionSubmitting:h,aiGenerated:u,handleGenerateConclusion:D,handleFinalizeConclusion:A,generationAttempts:b,generationFailed:y,maxAttemptsReached:w}}function _p(t,s,a){const[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState(!1),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(!1),[b,f]=p.useState(null),[y,v]=p.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:h,setShowSkipApproverModal:x,showActionStatusModal:u,setShowActionStatusModal:g,skipApproverData:b,setSkipApproverData:f,actionStatus:y,setActionStatus:v,handleApproveConfirm:async D=>{var N,P;const A=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!A){alert("Approval level not found");return}await an(t,A,D||""),await new Promise(R=>setTimeout(R,500)),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Approved successfully")},handleRejectConfirm:async D=>{var N,P;if(!(D!=null&&D.trim())){alert("Comments & remarks are required");return}const A=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!A){alert("Approval level not found");return}await Sr(t,A,D.trim(),D.trim()),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Rejected successfully")},handleAddApprover:async(D,A,N)=>{var P,R;try{await Vx(t,D,A,N),await a(),c(!1),v==null||v({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${A}h TAT`}),g==null||g(!0)}catch(O){throw v==null||v({success:!1,title:"Failed to Add Approver",message:((R=(P=O==null?void 0:O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to add approver. Please try again."}),g==null||g(!0),O}},handleSkipApprover:async D=>{var A,N;if(b)try{await Zj(t,b.levelId,D),await a(),x(!1),f(null),v==null||v({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),g==null||g(!0)}catch(P){throw v==null||v({success:!1,title:"Failed to Skip Approver",message:((N=(A=P==null?void 0:P.response)==null?void 0:A.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),P}},handleAddSpectator:async D=>{var A,N;try{await zx(t,D),await a(),m(!1),v==null||v({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),g==null||g(!0)}catch(P){throw v==null||v({success:!1,title:"Failed to Add Spectator",message:((N=(A=P==null?void 0:P.response)==null?void 0:A.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),P}}}}const VS=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 Or({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(Re,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900","data-testid":`${n}-name`,children:t.name}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${n}-metadata`,children:[t.size&&e.jsxs("span",{children:[t.size," â€ĸ "]}),t.uploadedBy&&e.jsxs("span",{children:["Uploaded by ",t.uploadedBy," on "]}),Qt(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&VS(t.fileType)&&s&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>s({fileName:t.name,fileType:t.fileType,documentId:t.documentId,fileSize:t.sizeBytes}),title:"Preview file","data-testid":`${n}-preview-btn`,children:e.jsx(ht,{className:"w-4 h-4"})}),a&&e.jsx(E,{variant:"ghost",size:"sm",onClick:async()=>{if(!t.documentId){alert("Document ID not available");return}try{await a(t.documentId)}catch{alert("Failed to download document")}},title:"Download file","data-testid":`${n}-download-btn`,children:e.jsx(Ct,{className:"w-4 h-4"})})]})]})}function zS({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l}){return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(ee,{children:[e.jsx(ge,{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(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx($e,{className:"text-xs sm:text-sm mt-1",children:"Documents attached while creating the request"})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsxs(E,{size:"sm",onClick:n,disabled:a||t.status==="closed",className:"gap-1 sm:gap-2 h-8 sm:h-9 text-xs sm:text-sm shrink-0","data-testid":"upload-document-btn",children:[e.jsx(zs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a?"Uploading...":t.status==="closed"?"Closed":"Upload",e.jsx("span",{className:"hidden sm:inline",children:t.status==="closed"?"":"Document"})]}),e.jsxs("p",{className:"text-xs text-gray-500 whitespace-nowrap",children:["Max ",r.maxFileSizeMB,"MB"]})]})]})}),e.jsx(se,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((o,c)=>e.jsx(Or,{document:o,onPreview:d=>i(d),onDownload:l,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(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(As,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(se,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((o,c)=>e.jsx(Or,{document:{documentId:o.attachmentId||"",name:o.name,fileType:o.type||"",size:o.size?`${(o.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:o.size,uploadedBy:o.uploadedBy,uploadedAt:o.uploadedAt},onPreview:d=>i(d),onDownload:async d=>{const{downloadWorkNoteAttachment:m}=require("@/services/workflowApi");await m(d)},testId:"worknote-attachment"},o.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 HS=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"}}},WS=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}}},GS=t=>{switch(t){case"approval":case"approved":return e.jsx(De,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(wt,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(As,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx($t,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(wi,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Re,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(st,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(vi,{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(kt,{className:"w-5 h-5 text-gray-600"})}};function YS({request:t}){return e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(kt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(se,{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:GS(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(kt,{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 Lp({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsx(gt,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[a?e.jsx(De,{className:"w-5 h-5 text-green-600"}):e.jsx(ze,{className:"w-5 h-5 text-red-600"}),r||(a?"Success":"Error")]})}),e.jsx("div",{className:"py-6",children:e.jsx("div",{className:"flex flex-col items-center text-center",children:a?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mb-4",children:e.jsx(De,{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(wt,{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(Tt,{children:e.jsx(E,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function Mp({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=p.useState(""),[l,o]=p.useState(!1),[c,d]=p.useState([]),[m,h]=p.useState(!1),[x,u]=p.useState(null),g=p.useRef(null),b=p.useRef(null),[f,y]=p.useState({open:!1,type:"error",email:"",message:""}),[v,w]=p.useState({open:!1,violations:[]}),[C,k]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});p.useEffect(()=>{t&&(async()=>{var P;try{const R=await Ys("WORKFLOW_SHARING"),O=await Ys("TAT_SETTINGS"),F=[...R,...O],$={};F.forEach(V=>{$[V.configKey]=V.configValue}),k({maxApprovalLevels:parseInt($.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt($.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((P=$.ALLOW_ADD_SPECTATOR)==null?void 0:P.toLowerCase())==="true",maxSpectators:parseInt($.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(R){console.error("Failed to load system policy:",R)}})()},[t]);const S=async()=>{var T,j;const N=n.trim().toLowerCase();if(!N){y({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(N)){y({open:!0,type:"error",email:N,message:"Please enter a valid email address"});return}const R=r.find(U=>(U.email||"").toLowerCase()===N);if(R){const U=((T=R.participantType)==null?void 0:T.toUpperCase())||"PARTICIPANT",I=R.name||N;if(U==="INITIATOR"){y({open:!0,type:"error",email:N,message:`${I} is the request initiator and cannot be added as a spectator.`});return}else if(U==="APPROVER"){y({open:!0,type:"error",email:N,message:`${I} is already an approver on this request and cannot be added as a spectator.`});return}else if(U==="SPECTATOR"){y({open:!0,type:"error",email:N,message:`${I} is already a spectator on this request.`});return}else{y({open:!0,type:"error",email:N,message:`${I} is already a participant on this request.`});return}}const O=[];C.allowSpectators||O.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const $=r.filter(U=>(U.participantType||"").toUpperCase()==="SPECTATOR").length;$>=C.maxSpectators&&O.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:$,maxValue:C.maxSpectators});const V=r.length+1;if(V>C.maxParticipants&&O.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:V,maxValue:C.maxParticipants}),O.length>0){w({open:!0,violations:O});return}if(!x||x.email.toLowerCase()!==N)try{const I=((j=(await ia(N,1)).data)==null?void 0:j.data)||[];if(I.length===0){y({open:!0,type:"not-found",email:N,message:""});return}const M=I[0];await ra({userId:M.userId,email:M.email,displayName:M.displayName,firstName:M.firstName,lastName:M.lastName,department:M.department,phone:M.phone,mobilePhone:M.mobilePhone,designation:M.designation,jobTitle:M.jobTitle,manager:M.manager,employeeId:M.employeeId,employeeNumber:M.employeeNumber,secondEmail:M.secondEmail,location:M.location})}catch(U){console.error("Failed to validate spectator:",U),y({open:!0,type:"error",email:N,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(N),i(""),u(null),s()}catch(U){console.error("Failed to add spectator:",U)}finally{o(!1)}},_=()=>{l||(i(""),u(null),d([]),h(!1),s())};p.useEffect(()=>{c.length>0&&b.current&&b.current.scrollTo({top:b.current.scrollHeight,behavior:"smooth"})},[c.length]),p.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const D=N=>{if(i(N),x&&x.email.toLowerCase()!==N.toLowerCase()&&u(null),g.current&&clearTimeout(g.current),!N||!N.startsWith("@")||N.length<2){d([]),h(!1);return}h(!0),g.current=setTimeout(async()=>{var P;try{const R=N.slice(1),F=((P=(await ia(R,10)).data)==null?void 0:P.data)||[];d(F)}catch(R){console.error("Search failed:",R),d([])}finally{h(!1)}},300)},A=async N=>{try{await ra({userId:N.userId,email:N.email,displayName:N.displayName,firstName:N.firstName,lastName:N.lastName,department:N.department,phone:N.phone,mobilePhone:N.mobilePhone,designation:N.designation,jobTitle:N.jobTitle,manager:N.manager,employeeId:N.employeeId,employeeNumber:N.employeeNumber,secondEmail:N.secondEmail,location:N.location}),i(N.email),u(N),d([]),h(!1)}catch(P){console.error("Failed to ensure user exists:",P),y({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(pt,{open:t,onOpenChange:_,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:_,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:l,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(gt,{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(ht,{className:"w-5 h-5 text-purple-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:b,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a 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(Ci,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Oe,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:N=>D(N.target.value),className:"pl-10 h-11 border-gray-300",disabled:l,autoFocus:!0}),(m||c.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:m?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):c.length>0?e.jsx("ul",{className:"divide-y",children:c.map(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>A(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zt,{className:"h-8 w-8",children:e.jsx(Jt,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(N.displayName||N.email).split(" ").map(P=>P[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:N.displayName||[N.firstName,N.lastName].filter(Boolean).join(" ")||N.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:N.email}),N.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:N.designation})]})]})},N.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:_,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:S,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(ht,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(pt,{open:f.open,onOpenChange:N=>y(P=>({...P,open:N})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:f.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[f.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:f.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(Ni,{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."]})})]}),f.type==="error"&&e.jsxs(e.Fragment,{children:[f.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:f.email}),"."]}),f.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:f.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:()=>y(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(Fn,{open:v.open,onClose:()=>w({open:!1,violations:[]}),violations:v.violations,policyDetails:{maxApprovalLevels:C.maxApprovalLevels,maxParticipants:C.maxParticipants,allowSpectators:C.allowSpectators,maxSpectators:C.maxSpectators}})]})}function $p({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=p.useState(""),[d,m]=p.useState(24),[h,x]=p.useState(null),[u,g]=p.useState(!1),[b,f]=p.useState([]),[y,v]=p.useState(!1),[w,C]=p.useState(null),k=p.useRef(null),S=p.useRef(null),[_,D]=p.useState({open:!1,type:"error",email:"",message:""}),A=n.filter(j=>j&&(j.status==="approved"||j.status==="rejected"||j.status==="skipped")),N=Math.max(1,A.length+1),P=Math.max(1,n.length+1),R=P>=N?Array.from({length:P-N+1},(j,U)=>N+U):[N];p.useEffect(()=>{R.length>0&&h===null&&x(R[0]||null)},[R.length,h]);const O=async()=>{var G,ce;const j=o.trim().toLowerCase();if(!j){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(j)){D({open:!0,type:"error",email:j,message:"Please enter a valid email address"});return}if(!d||d<=0){D({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(d>720){D({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!h){D({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(h0?Math.max(...n.map(te=>te.levelNumber),0):0,M=h>I?h:I+1;if(i&&M>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${h} would result in ${M} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:M,maxValue:i}]):D({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${I} level(s).`});return}const W=r.find(te=>(te.email||"").toLowerCase()===j);if(W){const te=((G=W.participantType)==null?void 0:G.toUpperCase())||"PARTICIPANT",L=W.name||j;if(te==="INITIATOR"){D({open:!0,type:"error",email:j,message:`${L} is the request initiator and cannot be added as an approver.`});return}else if(te==="APPROVER"){D({open:!0,type:"error",email:j,message:`${L} is already an approver on this request.`});return}else if(te==="SPECTATOR"){D({open:!0,type:"error",email:j,message:`${L} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{D({open:!0,type:"error",email:j,message:`${L} is already a participant on this request.`});return}}if(!w||w.email.toLowerCase()!==j)try{const L=((ce=(await ia(j,1)).data)==null?void 0:ce.data)||[];if(L.length===0){D({open:!0,type:"not-found",email:j,message:""});return}const z=L[0];await ra({userId:z.userId,email:z.email,displayName:z.displayName,firstName:z.firstName,lastName:z.lastName,department:z.department,phone:z.phone,mobilePhone:z.mobilePhone,designation:z.designation,jobTitle:z.jobTitle,manager:z.manager,employeeId:z.employeeId,employeeNumber:z.employeeNumber,secondEmail:z.secondEmail,location:z.location})}catch(te){console.error("Failed to validate approver:",te),D({open:!0,type:"error",email:j,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(j,d,h),c(""),m(24),x(null),C(null),s()}catch(te){console.error("Failed to add approver:",te)}finally{g(!1)}},F=()=>{u||(c(""),m(24),x(null),C(null),f([]),v(!1),s())},$=j=>{const U=j.toLowerCase();return U==="approved"?e.jsx(De,{className:"w-4 h-4 text-green-600"}):U==="rejected"?e.jsx(wt,{className:"w-4 h-4 text-red-600"}):U==="skipped"?e.jsx(ze,{className:"w-4 h-4 text-orange-600"}):U==="in-review"||U==="pending"?e.jsx(st,{className:"w-4 h-4 text-blue-600"}):e.jsx(st,{className:"w-4 h-4 text-gray-400"})};p.useEffect(()=>{b.length>0&&S.current&&S.current.scrollTo({top:S.current.scrollHeight,behavior:"smooth"})},[b.length]),p.useEffect(()=>()=>{k.current&&clearTimeout(k.current)},[]);const V=j=>{if(c(j),w&&w.email.toLowerCase()!==j.toLowerCase()&&C(null),k.current&&clearTimeout(k.current),!j||!j.startsWith("@")||j.length<2){f([]),v(!1);return}v(!0),k.current=setTimeout(async()=>{var U;try{const I=j.slice(1),W=((U=(await ia(I,10)).data)==null?void 0:U.data)||[];f(W)}catch(I){console.error("Search failed:",I),f([])}finally{v(!1)}},300)},T=async j=>{try{await ra({userId:j.userId,email:j.email,displayName:j.displayName,firstName:j.firstName,lastName:j.lastName,department:j.department,phone:j.phone,mobilePhone:j.mobilePhone,designation:j.designation,jobTitle:j.jobTitle,manager:j.manager,employeeId:j.employeeId,employeeNumber:j.employeeNumber,secondEmail:j.secondEmail,location:j.location}),c(j.email),C(j),f([]),v(!1)}catch(U){console.error("Failed to ensure user exists:",U),D({open:!0,type:"error",email:j.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(pt,{open:t,onOpenChange:F,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:F,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:u,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(gt,{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(cs,{className:"w-5 h-5 text-blue-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:S,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a new approver at a specific level. Existing approvers at and after the selected level will be shifted down."}),i&&e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-2",children:e.jsxs("p",{className:"text-xs text-blue-800",children:["â„šī¸ Max: ",i," level",i!==1?"s":"",n.length>0&&e.jsxs("span",{className:"ml-2",children:["(",Math.max(...n.map(j=>j.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-semibold text-gray-700",children:"Current Approval Levels"}),e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-2 border rounded-lg p-3 bg-gray-50",children:n.map(j=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${j.status==="approved"?"bg-green-100 border border-green-200":j.status==="rejected"?"bg-red-100 border border-red-200":j.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:j.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:j.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[j.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[$(j.status),e.jsx(ne,{variant:"outline",className:`text-xs ${j.status==="approved"?"bg-green-50 text-green-700 border-green-300":j.status==="rejected"?"bg-red-50 text-red-700 border-red-300":j.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:j.status})]})]},j.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:["â„šī¸ New approver can only be added at level ",N," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(We,{value:(h==null?void 0:h.toString())||"",onValueChange:j=>x(Number(j)),disabled:u,children:[e.jsx(Ye,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select level"})}),e.jsx(Ke,{children:R.map(j=>e.jsx(Y,{value:j.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",j]}),j<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",j,")"]})]})},j))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Choose where to insert the new approver. Existing levels will be automatically shifted."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{type:"number",min:"1",max:"720",value:d,onChange:j=>m(Number(j.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(st,{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(Ci,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Oe,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:j=>V(j.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(y||b.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:y?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):b.length>0?e.jsx("ul",{className:"divide-y",children:b.map(j=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>T(j),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zt,{className:"h-8 w-8",children:e.jsx(Jt,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(j.displayName||j.email).split(" ").map(U=>U[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:j.displayName||[j.firstName,j.lastName].filter(Boolean).join(" ")||j.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:j.email}),j.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:j.designation})]})]})},j.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:F,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:O,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!o.trim()||!h||!d,children:[e.jsx(cs,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${h||"?"}`]})]})]}),e.jsx(pt,{open:_.open,onOpenChange:j=>D(U=>({...U,open:j})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:_.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[_.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:_.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(Ni,{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."]})})]}),_.type==="error"&&e.jsxs(e.Fragment,{children:[_.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:_.email}),"."]}),_.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:_.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:()=>D(j=>({...j,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const KS=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"}},XS=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},ZS=t=>{const s=t.replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,(a,r,n,i)=>{const l=n+a.length,o=i[l];return!o||/\s|[.,!?;:]|@/.test(o)?'@'+r+"":a}).replace(/\n/g,"
");return ba(s)},JS=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",wu=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Re,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(d0,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Re,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Re,{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(Wn,{className:`${s} text-purple-600`}):e.jsx(vi,{className:`${s} text-gray-600`})};function Op({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:c=[],onAddApprover:d,maxApprovalLevels:m,onPolicyViolation:h}){const x=Ea(),u=t||x.requestId||"",[g,b]=p.useState(""),[f,y]=p.useState(""),[v,w]=p.useState(!1),[C,k]=p.useState([]),[S,_]=p.useState(!1),[D,A]=p.useState([]),[N,P]=p.useState(null),[R,O]=p.useState(null),[F,$]=p.useState(!1),[V,T]=p.useState(!1),[j,U]=p.useState(!1),[I,M]=p.useState({success:!0,title:"",message:""}),W=p.useRef(null),G=p.useRef(null),ce=p.useRef(null),te=p.useRef(!1),[L,z]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[H,ye]=p.useState({open:!1,errors:[]}),ae=p.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[me,Q]=p.useState([]),oe=me.filter(X=>X.status==="online"),Ce=C.filter(X=>X.content.toLowerCase().includes(f.toLowerCase())||X.user.name.toLowerCase().includes(f.toLowerCase())),Ee=p.useMemo(()=>o!==void 0?o:!N||me.length===0?!1:me.some(X=>{const we=X.userId||X.user_id,J=(X.role||"").toString().toUpperCase(),Le=(X.participantType||X.participant_type||"").toString().toUpperCase();return we===N&&(J==="SPECTATOR"||Le==="SPECTATOR")}),[o,N,me]);p.useEffect(()=>{},[me]),p.useEffect(()=>{!u||!N||s||(async()=>{try{const X=await Fr(u),we=Array.isArray(X)?X.map(J=>{const Le=J.userId||J.user_id;return{id:J.noteId||J.id||String(Math.random()),user:{name:J.userName||"User",avatar:(J.userName||"U").slice(0,2).toUpperCase(),role:J.userRole||"Participant"},content:J.message||"",timestamp:J.createdAt||new Date().toISOString(),isCurrentUser:Le===N,attachments:Array.isArray(J.attachments)?J.attachments.map(Fe=>({attachmentId:Fe.attachmentId||Fe.attachment_id,name:Fe.fileName||Fe.file_name||Fe.name,fileName:Fe.fileName||Fe.file_name||Fe.name,url:Fe.storageUrl||Fe.storage_url||Fe.url||"#",type:Fe.fileType||Fe.file_type||Fe.type||"file",fileType:Fe.fileType||Fe.file_type||Fe.type||"file",fileSize:Fe.fileSize||Fe.file_size})):void 0}}):[];k(we)}catch(X){console.error("[WorkNoteChat] Failed to load messages:",X)}})()},[u,N,s]);const be=p.useMemo(()=>{const X=[];return C.forEach(we=>{we.attachments&&we.attachments.length>0&&we.attachments.forEach(J=>{X.push({attachmentId:J.attachmentId||J.attachment_id,name:J.fileName||J.file_name||J.name||"Untitled",fileName:J.fileName||J.file_name||J.name||"Untitled",size:J.fileSize||J.file_size,type:J.fileType||J.file_type||J.type||"file",uploadedBy:we.user.name,uploadedAt:we.timestamp,url:J.storageUrl||J.storage_url||J.url||"#"})})}),X},[C]);p.useEffect(()=>{i&&be.length>=0&&i(be)},[be,i]);const q=p.useMemo(()=>me.map(X=>({email:(X.email||"").toLowerCase(),participantType:X.role==="Initiator"?"INITIATOR":X.role==="Approver"?"APPROVER":X.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:X.name})),[me]),ue=X=>{if(!X)return"Participant";switch(X.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()}},Ae=()=>{var X;(X=W.current)==null||X.scrollIntoView({behavior:"smooth"})};p.useEffect(()=>{Ae()},[C]);const Ue=X=>{switch(X.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()}};p.useEffect(()=>{te.current||u&&(async()=>{try{const X=await vs(u),we=Array.isArray(X==null?void 0:X.participants)?X.participants:[];if(we.length===0)return;const J=we.map(Me=>{const Ze=Me.participantType||Me.participant_type||"participant",Be=Me.userId||Me.user_id||"";return{name:Me.userName||Me.user_name||Me.user_email||Me.userEmail||"User",avatar:(Me.userName||Me.user_name||Me.user_email||"U").toString().split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ue(Ze.toString()),status:"offline",email:Me.userEmail||Me.user_email||"",permissions:["read","write","mention"],userId:Be}});te.current=!0,Q(J);let Le=0;const Fe=3,Ve=()=>{ce.current&&ce.current.connected?(ce.current.emit("request:online-users",{requestId:u}),Le++,Le()=>{u&&(te.current=!1)},[u]),p.useEffect(()=>{const X=localStorage.getItem("userData");if(X)try{const we=JSON.parse(X),J=(we==null?void 0:we.id)||(we==null?void 0:we.userId)||(we==null?void 0:we.user_id)||null;P(J)}catch(we){console.error("[WorkNoteChat] Failed to parse userData:",we)}},[]),p.useEffect(()=>{(async()=>{try{const we=await Ys("DOCUMENT_POLICY"),J={};we.forEach(Me=>{J[Me.configKey]=Me.configValue});const Le=parseInt(J.MAX_FILE_SIZE_MB||"10"),Ve=(J.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Me=>Me.trim().toLowerCase());z({maxFileSizeMB:Le,allowedFileTypes:Ve})}catch(we){console.error("Failed to load document policy:",we)}})()},[]),p.useEffect(()=>{if(!N)return;let X=u;return(async()=>{var we;try{const J=await vs(u);(we=J==null?void 0:J.workflow)!=null&&we.requestId&&(X=J.workflow.requestId)}catch{}try{const J=Lr();r?Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)):(Ml(J,X,N),Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)));const Le=at=>{const et=(at==null?void 0:at.note)||at;if(!et)return;const yt=et.noteId||et.id;k(rs=>{if(rs.some(St=>St.id===yt))return rs;const Pt=et.userName||et.user_name||"User",la=et.userRole||et.user_role,pa=ue(la),Fa=et.userId||et.user_id,wa={id:yt||String(Date.now()),user:{name:Pt,avatar:Pt.split(" ").map(St=>St[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:pa},content:et.message||"",timestamp:et.createdAt||new Date().toISOString(),isCurrentUser:Fa===N,attachments:Array.isArray(et.attachments)?et.attachments.map(St=>({attachmentId:St.attachmentId||St.attachment_id,name:St.fileName||St.file_name||St.name,fileName:St.fileName||St.file_name||St.name,url:St.storageUrl||St.storage_url||St.url||"#",type:St.fileType||St.file_type||St.type||"file",fileType:St.fileType||St.file_type||St.type||"file",fileSize:St.fileSize||St.file_size})):void 0};return[...rs,wa]})},Fe=at=>{Q(et=>et.length===0||!et.find(Pt=>Pt.userId===at.userId)?et:et.map(Pt=>Pt.userId===at.userId?{...Pt,status:"online"}:Pt))},Ve=at=>{at.userId!==N&&Q(et=>et.length===0||!et.find(Pt=>Pt.userId===at.userId)?et:et.map(Pt=>Pt.userId===at.userId?{...Pt,status:"offline"}:Pt))},Me=at=>{Q(et=>et.length===0?et:et.map(rs=>{const Pt=rs.userId||"";if(Pt===N)return{...rs,status:"online"};const pa=at.userIds.includes(Pt);return{...rs,status:pa?"online":"offline"}}))},Ze=()=>{Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)),r||Ml(J,X,N),te.current&&(J.emit("request:online-users",{requestId:X}),setTimeout(()=>J.emit("request:online-users",{requestId:X}),300),setTimeout(()=>J.emit("request:online-users",{requestId:X}),800))},Be=at=>{console.error("[WorkNoteChat] ❌ Socket error:",at)},qe=at=>{console.warn("[WorkNoteChat] âš ī¸ Socket disconnected:",at),Q(et=>et.map(yt=>yt.userId===N?yt:{...yt,status:"offline"}))},fs=at=>{at.includes("presence")||at.includes("worknote")||at.includes("request")};J.on("connect",Ze),J.on("disconnect",qe),J.on("error",Be),J.on("worknote:new",Le),J.on("presence:join",Fe),J.on("presence:leave",Ve),J.on("presence:online",Me),J.onAny(fs),ce.current=J,J.connected&&te.current&&(J.emit("request:online-users",{requestId:X}),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},300),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},800),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},1500));const Ht=()=>{J.off("connect",Ze),J.off("disconnect",qe),J.off("error",Be),J.off("worknote:new",Le),J.off("presence:join",Fe),J.off("presence:leave",Ve),J.off("presence:online",Me),J.offAny(fs),r||Ax(J,X),ce.current=null};window.__wn_cleanup=Ht}catch{}})(),()=>{var we;try{(we=window.__wn_cleanup)==null||we.call(window)}catch{}}},[u,N,r]);const Z=async()=>{if(g.trim()||D.length>0){const X=Xs(g),we=X.map(Fe=>{const Ve=me.find(Me=>Me.name.toLowerCase().includes(Fe.toLowerCase()));return Ve==null?void 0:Ve.userId}).filter(Boolean),J=D.map(Fe=>({name:Fe.name,url:URL.createObjectURL(Fe),type:Fe.type.split("/")[1]||"file"})),Le={id:Date.now().toString(),user:{name:"You",avatar:"YO",role:"Current User"},content:g,timestamp:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),mentions:X,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:J.length>0?J:void 0,isCurrentUser:!0};if(a)try{await a(g,D)}catch{}else try{await Bx(u,{message:g,mentions:we},D);const Fe=await Fr(u),Ve=Array.isArray(Fe)?Fe.map(Me=>{const Ze=Me.userId||Me.user_id;return{id:Me.noteId||Me.id||String(Math.random()),user:{name:Me.userName||"User",avatar:(Me.userName||"U").slice(0,2).toUpperCase(),role:Me.userRole||"Participant"},content:Me.message||"",timestamp:Me.createdAt||new Date().toISOString(),isCurrentUser:Ze===N,attachments:Array.isArray(Me.attachments)?Me.attachments.map(Be=>({attachmentId:Be.attachmentId||Be.attachment_id,name:Be.fileName||Be.file_name||Be.name,fileName:Be.fileName||Be.file_name||Be.name,url:Be.storageUrl||Be.storage_url||Be.url||"#",type:Be.fileType||Be.file_type||Be.type||"file",fileType:Be.fileType||Be.file_type||Be.type||"file",fileSize:Be.fileSize||Be.file_size})):void 0}}):[];k(Ve)}catch{k(Fe=>[...Fe,Le])}b(""),A([])}};p.useEffect(()=>{if(s&&Array.isArray(s))try{const we=s.filter(J=>(J.type||"").toLowerCase()!=="sla_warning").map(J=>{var Fe;if(J.type||J.activityType||J.isSystem)return{id:J.id||`activity-${J.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:J.details||J.action||J.content||"",timestamp:J.timestamp||J.createdAt||J.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const Ve=J.userName||J.user_name||((Fe=J.user)==null?void 0:Fe.name)||"User",Me=J.userRole||J.user_role,Ze=ue(Me),Be=J.userId||J.user_id;return{id:J.noteId||J.note_id||J.id||String(Math.random()),user:{name:Ve,avatar:Ve.split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ze},content:J.message||J.content||"",timestamp:J.createdAt||J.created_at||J.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(J.attachments)?J.attachments.map(qe=>({attachmentId:qe.attachmentId||qe.attachment_id,name:qe.fileName||qe.file_name||qe.name,fileName:qe.fileName||qe.file_name||qe.name,url:qe.storageUrl||qe.storage_url||qe.url||"#",type:qe.fileType||qe.file_type||qe.type||"file",fileType:qe.fileType||qe.file_type||qe.type||"file",fileSize:qe.fileSize||qe.file_size})):void 0,isCurrentUser:Be===N}}}).sort((J,Le)=>new Date(J.timestamp).getTime()-new Date(Le.timestamp).getTime());k(we)}catch(X){console.error("[WorkNoteChat] Error mapping messages:",X)}else(async()=>{try{const X=await Fr(u),we=Array.isArray(X)?X.map(J=>{const Le=J.userName||J.user_name||"User",Fe=J.userRole||J.user_role,Ve=ue(Fe),Me=J.userId||J.user_id;return{id:J.noteId||J.note_id||J.id||String(Math.random()),user:{name:Le,avatar:Le.split(" ").map(Ze=>Ze[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ve},content:J.message||"",timestamp:J.createdAt||J.created_at||new Date().toISOString(),attachments:Array.isArray(J.attachments)?J.attachments.map(Ze=>({attachmentId:Ze.attachmentId||Ze.attachment_id,name:Ze.fileName||Ze.file_name||Ze.name,fileName:Ze.fileName||Ze.file_name||Ze.name,url:Ze.storageUrl||Ze.storage_url||Ze.url||"#",type:Ze.fileType||Ze.file_type||Ze.type||"file",fileType:Ze.fileType||Ze.file_type||Ze.type||"file",fileSize:Ze.fileSize||Ze.file_size})):void 0,isCurrentUser:Me===N}}):[];k(we)}catch(X){console.error("[WorkNoteChat] Error loading work notes:",X)}})()},[s,u,me]);const Te=X=>{const we=L.maxFileSizeMB*1024*1024;if(X.size>we)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${L.maxFileSizeMB}MB. Current size: ${(X.size/(1024*1024)).toFixed(2)}MB`};const J=X.name.toLowerCase(),Le=J.substring(J.lastIndexOf(".")+1);return L.allowedFileTypes.includes(Le)?{valid:!0}:{valid:!1,reason:`File type "${Le}" is not allowed. Allowed types: ${L.allowedFileTypes.join(", ")}`}},Xe=X=>{if(!X.target.files||X.target.files.length===0)return;const we=Array.from(X.target.files),J=[],Le=[];we.forEach(Fe=>{const Ve=Te(Fe);Ve.valid?Le.push(Fe):J.push({fileName:Fe.name,reason:Ve.reason||"Unknown validation error"})}),J.length>0&&ye({open:!0,errors:J}),Le.length>0&&(A(Fe=>[...Fe,...Le]),Le.length{A(we=>we.filter((J,Le)=>Le!==X)),G.current&&(G.current.value="")},_e=X=>{b(we=>we+X),w(!1)},rt=()=>{var X;(X=G.current)==null||X.click()},ut=async X=>{var we,J;try{await zx(u,X);const Le=await vs(u),Fe=Array.isArray(Le==null?void 0:Le.participants)?Le.participants:[];if(Fe.length){const Ve=Fe.map(Me=>{const Ze=Me.participantType||Me.participant_type||"participant",Be=Me.userId||Me.user_id||"",qe=Me.userName||Me.user_name||Me.userEmail||Me.user_email||"User",fs=Me.userEmail||Me.user_email||"",Ht=qe.split(" ").map(at=>at[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:qe,avatar:Ht,role:Ue(Ze),status:"offline",email:fs,lastSeen:void 0,permissions:["read"],userId:Be}});Q(Ve),ce.current&&ce.current.connected&&ce.current.emit("request:online-users",{requestId:u})}$(!1),M({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),U(!0)}catch(Le){throw console.error("Failed to add spectator:",Le),M({success:!1,title:"Failed to Add Spectator",message:((J=(we=Le==null?void 0:Le.response)==null?void 0:we.data)==null?void 0:J.error)||"Failed to add spectator. Please try again."}),U(!0),Le}},nt=async(X,we,J)=>{var Le,Fe;if(d)await d(X,we,J),T(!1);else try{await Vx(u,X,we,J);const Ve=await vs(u),Me=Array.isArray(Ve==null?void 0:Ve.participants)?Ve.participants:[];if(Me.length){const Ze=Me.map(Be=>{const qe=Be.participantType||Be.participant_type||"participant",fs=Be.userId||Be.user_id||"",Ht=Be.userName||Be.user_name||Be.userEmail||Be.user_email||"User",at=Be.userEmail||Be.user_email||"",et=Ht.split(" ").map(yt=>yt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Ht,avatar:et,role:Ue(qe),status:"offline",email:at,lastSeen:void 0,permissions:["read"],userId:fs}});Q(Ze),ce.current&&ce.current.connected&&ce.current.emit("request:online-users",{requestId:u})}T(!1),M({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${J} with ${we}h TAT`}),U(!0)}catch(Ve){throw console.error("Failed to add approver:",Ve),M({success:!1,title:"Failed to Add Approver",message:((Fe=(Le=Ve==null?void 0:Ve.response)==null?void 0:Le.data)==null?void 0:Fe.error)||"Failed to add approver. Please try again."}),U(!0),Ve}},Ps=["😊","😂","đŸ¤Ŗ","😁","😃","😄","😅","😆","😉","😌","😍","đŸĨ°","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","đŸ˜ļ","🙄","😏","😒","🙃","đŸ˜Ŧ","🤐","😴","đŸ˜Ē","đŸ˜ĩ","đŸ¤¯","đŸ¤Ē","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","â˜šī¸","😮","đŸ˜¯","😲","đŸ˜ŗ","đŸĨē","đŸ˜Ļ","😧","😨","😰","đŸ˜Ĩ","đŸ˜ĸ","😭","😱","😖","đŸ˜Ŗ","😞","😓","😩","đŸ˜Ģ","đŸĨą","😤","😡","😠","đŸ¤Ŧ","😈","đŸ‘ŋ","💀","â˜ ī¸","💩","🤡","👹","đŸ‘ē","đŸ‘ģ","👋","🤚","đŸ–ī¸","✋","🖖","👌","🤌","🤏","âœŒī¸","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","â˜ī¸","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","đŸ’Ē","đŸĻž","đŸĻŋ","đŸĻĩ","đŸĻļ","👂","đŸĻģ","👃","🧠","â¤ī¸","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","âŖī¸","💕","💞","💓","💗","💖","💘","💝","💟","â¤ī¸â€đŸ”Ĩ","đŸ’ŧ","📊","📈","📉","đŸ’ģ","âŒ¨ī¸","đŸ–Ĩī¸","đŸ–¨ī¸","đŸ–ąī¸","💾","đŸ’ŋ","📱","â˜Žī¸","📞","📟","📠","📧","âœ‰ī¸","📨","📩","📮","đŸ“Ē","đŸ“Ģ","đŸ“Ŧ","📭","📄","📃","📑","📝","âœī¸","âœ’ī¸","đŸ–Šī¸","đŸ–‹ī¸","📏","📐","📌","📍","đŸ—‚ī¸","📁","📂","✅","âœ”ī¸","â˜‘ī¸","đŸŽ¯","đŸŽ–ī¸","🏆","đŸĨ‡","đŸĨˆ","đŸĨ‰","⭐","🌟","✨","đŸ’Ģ","đŸ”Ĩ","đŸ’Ĩ","⚡","đŸ’¯","🎉","🎊","🎈","âš ī¸","đŸšĢ","❌","⛔","🚷","đŸš¯","🚱","đŸšŗ","🔞","đŸ“ĩ","❗","❓","❕","❔","â€ŧī¸","â‰ī¸","đŸ’ĸ","đŸ’Ŧ","💭","đŸ—¯ī¸","⏰","âąī¸","â˛ī¸","âŗ","⌛","📅","📆","đŸ—“ī¸","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","đŸŽ¯","🎲","🎰","🧩","🔍","🔎","🔑","đŸ—ī¸","🔒","🔓","🔐","🔏","🔔","🔕","đŸ“Ŗ","đŸ“ĸ","💡","đŸ”Ļ","🏮","➕","➖","âœ–ī¸","➗","â™žī¸","â€ŧī¸","â‰ī¸","❓","❔","❕","🔄","🔃","🔂","â–ļī¸","â¸ī¸","â¯ī¸","âšī¸","âēī¸","â­ī¸","âŽī¸","⏊","âĒ","âĢ","âŦ","â—€ī¸","đŸ”ŧ","đŸ”Ŋ","âžĄī¸","âŦ…ī¸","âŦ†ī¸","âŦ‡ī¸","â†—ī¸","â†˜ī¸","â†™ī¸","â†–ī¸","â†•ī¸","â†”ī¸","â†Ēī¸","â†Šī¸","â¤´ī¸"],Xs=X=>{const we=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,J=[];let Le;for(;(Le=we.exec(X))!==null;)if(Le[1]){const Fe=Le.index+Le[0].length,Ve=X.slice(Fe),Me=X[Fe];(Ve.startsWith("@")||!Me||/\s|[.,!?;:]|@/.test(Me))&&J.push(Le[1].trim())}return J},Na=X=>{X.key==="Enter"&&!X.shiftKey&&(X.preventDefault(),Z())},Xa=(X,we)=>{k(J=>J.map(Le=>{if(Le.id===X){const Fe=Le.reactions||[],Ve=Fe.find(Me=>Me.emoji===we);if(Ve)if(Ve.users.includes("You")){if(Ve.users=Ve.users.filter(Me=>Me!=="You"),Ve.users.length===0)return{...Le,reactions:Fe.filter(Me=>Me.emoji!==we)}}else Ve.users.push("You");else Fe.push({emoji:we,users:["You"]});return{...Le,reactions:Fe}}return Le}))};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(As,{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:ae.title}),e.jsx(ne,{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:[oe.slice(0,3).map((X,we)=>e.jsx(Zt,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:"bg-blue-500 text-white text-xs font-semibold",children:X.avatar})},we)),oe.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:["+",oe.length-3]})]})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>_(!S),className:"lg:hidden",children:e.jsx(cs,{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(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Oe,{placeholder:"Search messages...",value:f,onChange:X=>y(X.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:[Ce.map(X=>{const we=X.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${X.isSystem?"justify-center":we?"justify-end":""}`,children:[!X.isSystem&&!we&&e.jsx(Zt,{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(Jt,{className:`text-white font-semibold text-xs sm:text-sm ${X.user.role==="Initiator"?"bg-green-600":X.user.role==="Current User"?"bg-blue-500":X.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:X.user.avatar})}),e.jsx("div",{className:`${we?"max-w-[70%]":"flex-1"} min-w-0 ${X.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:X.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(kt,{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:X.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:Qt(X.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${we?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[X.user.name," ",we&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(ne,{variant:"outline",className:"text-xs flex-shrink-0",children:X.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(st,{className:"w-3 h-3"}),Qt(X.timestamp)]}),X.isHighPriority&&e.jsxs(ne,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(o0,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${we?"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:ZS(X.content)}}),X.attachments&&X.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:X.attachments.map((J,Le)=>{const Fe=J.fileSize||J.file_size,Ve=J.fileName||J.file_name||J.name,Me=J.fileType||J.file_type||J.type||"",Ze=J.attachmentId||J.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(wu,{type:Me})}),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:Ve}),Fe&&e.jsx("p",{className:"text-xs text-gray-500",children:JS(Fe)})]}),Ze&&(()=>{const Be=(Me||"").toLowerCase();return Be.includes("image")||Be.includes("pdf")||Be.includes("jpg")||Be.includes("jpeg")||Be.includes("png")||Be.includes("gif")})()&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-purple-100 hover:text-purple-600",onClick:Be=>{Be.preventDefault(),Be.stopPropagation();const qe=eN(Ze);O({fileName:Ve,fileType:Me,fileUrl:qe,fileSize:Fe,attachmentId:Ze})},title:"Preview file",children:e.jsx(ht,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-blue-100 hover:text-blue-600",onClick:async Be=>{if(Be.preventDefault(),Be.stopPropagation(),!Ze){K.error("Cannot download: Attachment ID missing");return}try{await Jd(Ze)}catch{K.error("Failed to download file")}},title:"Download file",children:e.jsx(Ct,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Le)})})}),X.reactions&&X.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:[X.reactions.map((J,Le)=>e.jsxs("button",{onClick:()=>Xa(X.id,J.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${J.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:J.emoji}),e.jsx("span",{className:"text-xs font-medium",children:J.users.length})]},Le)),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>w(!v),children:e.jsx(gs,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!X.isSystem&&we&&e.jsx(Zt,{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(Jt,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:X.user.avatar})})]},X.id)}),e.jsx("div",{ref:W})]})}),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:G,onChange:Xe,className:"hidden",multiple:!0,accept:L.allowedFileTypes.map(X=>`.${X}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((X,we)=>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(wu,{type:X.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:X.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(X.size/1024).toFixed(1)," KB"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>pe(we),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(ft,{className:"h-3 w-3 text-red-600"})})]},we))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const X=g.lastIndexOf("@"),we=X>=0;if(!we)return null;const J=g.slice(X+1),Le=J.trim(),Fe=J.endsWith(" "),Ve=Le.length>0,Me=Le.includes(" ")&&!Fe,Ze=Fe&&Ve;if(!(we&&J.length<=20&&!Me&&!Ze))return null;const qe=Le.toLowerCase(),fs=me.filter(Ht=>Ht.userId===N?!1:qe?Ht.name.toLowerCase().includes(qe):!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:fs.length>0?fs.map((Ht,at)=>e.jsxs("button",{type:"button",onClick:et=>{et.preventDefault(),et.stopPropagation();const yt=g.lastIndexOf("@"),rs=g.slice(0,yt);b(rs+"@"+Ht.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(Zt,{className:"h-10 w-10",children:e.jsx(Jt,{className:`text-white text-sm font-semibold ${Ht.role==="Initiator"?"bg-green-600":Ht.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:Ht.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:Ht.name}),e.jsx("p",{className:"text-xs text-gray-600",children:Ht.role})]})]},at)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:qe?`No participants found matching "${qe}"`:"No other participants available"})})]})})(),e.jsx(Ds,{placeholder:"Type your message... Use @username to mention someone",value:g,onChange:X=>b(X.target.value),onKeyPress:Na,className:"min-h-[50px] sm:min-h-[60px] resize-none border-gray-200 focus:ring-blue-500 focus:border-blue-500 w-full text-sm",rows:2}),v&&e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border border-gray-200 rounded-lg shadow-xl p-3 z-50 w-full sm:w-96 max-h-80 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 sticky top-0 bg-white pb-2 border-b",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-700",children:"Pick an emoji"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>w(!1),className:"h-6 w-6 p-0",children:e.jsx(ft,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:Ps.map((X,we)=>e.jsx("button",{onClick:()=>_e(X),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:X,children:X},we))})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-shrink-0",children:[e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:rt,title:"Attach file",children:e.jsx(vi,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>w(!v),title:"Add emoji",children:e.jsx(c0,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>b(X=>X+"@"),title:"Mention someone",children:e.jsx(Ci,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto flex-shrink-0",children:[e.jsxs("span",{className:"text-xs text-gray-500 hidden md:inline whitespace-nowrap",children:[g.length,"/2000"]}),e.jsxs(E,{onClick:Z,disabled:!g.trim()&&D.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(ax,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),S&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>_(!1)}),e.jsxs("div",{className:` + `),()=>{f.contains(b)&&f.removeChild(b)}},[s]),e.jsx(u1,{isPresent:s,childRef:i,sizeRef:l,children:p.cloneElement(t,{ref:c})})}const h1=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=_o(p1),m=p.useId();let h=!0,x=p.useMemo(()=>(h=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:u=>{d.set(u,!0);for(const g of d.values())if(!g)return;r&&r()},register:u=>(d.set(u,!1),()=>d.delete(u))}),[a,d,r]);return i&&h&&(x={...x}),p.useMemo(()=>{d.forEach((u,g)=>d.set(g,!1))},[a]),p.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(x1,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(Ii.Provider,{value:x,children:t})};function p1(){return new Map}function Vh(t=!0){const s=p.useContext(Ii);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 l=p.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const Un=t=>t.key||"";function ym(t){const s=[];return p.Children.forEach(t,a=>{p.isValidElement(a)&&s.push(a)}),s}const Ei=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",root:c})=>{const[d,m]=Vh(l),h=p.useMemo(()=>ym(t),[t]),x=l&&!d?[]:h.map(Un),u=p.useRef(!0),g=p.useRef(h),b=_o(()=>new Map),[f,y]=p.useState(h),[v,w]=p.useState(h);Jx(()=>{u.current=!1,g.current=h;for(let S=0;S{const _=Un(S),D=l&&!d?!1:h===v||x.includes(_),A=()=>{if(b.has(_))b.set(_,!0);else return;let N=!0;b.forEach(P=>{P||(N=!1)}),N&&(k==null||k(),w(g.current),l&&(m==null||m()),r&&r())};return e.jsx(h1,{isPresent:D,initial:!u.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:D?void 0:A,anchorX:o,children:S},_)})})},zh=p.createContext({strict:!1}),vm={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"]},$r={};for(const t in vm)$r[t]={isEnabled:s=>vm[t].some(a=>!!s[a])};function g1(t){for(const s in t)$r[s]={...$r[s],...t[s]}}const f1=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 ui(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||f1.has(t)}let Hh=t=>!ui(t);function b1(t){typeof t=="function"&&(Hh=s=>s.startsWith("on")?!ui(s):t(s))}try{b1(require("@emotion/is-prop-valid").default)}catch{}function y1(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(Hh(n)||a===!0&&ui(n)||!s&&!ui(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Fi=p.createContext({});function _i(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function vn(t){return typeof t=="string"||Array.isArray(t)}const nc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ic=["initial",...nc];function Li(t){return _i(t.animate)||ic.some(s=>vn(t[s]))}function Wh(t){return!!(Li(t)||t.variants)}function v1(t,s){if(Li(t)){const{initial:a,animate:r}=t;return{initial:a===!1||vn(a)?a:void 0,animate:vn(r)?r:void 0}}return t.inherit!==!1?s:{}}function j1(t){const{initial:s,animate:a}=v1(t,p.useContext(Fi));return p.useMemo(()=>({initial:s,animate:a}),[jm(s),jm(a)])}function jm(t){return Array.isArray(t)?t.join(" "):t}const jn={};function N1(t){for(const s in t)jn[s]=t[s],Ho(s)&&(jn[s].isCSSVariable=!0)}function Gh(t,{layout:s,layoutId:a}){return Yr.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!jn[t]||t==="opacity")}const w1={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},C1=Gr.length;function S1(t,s,a){let r="",n=!0;for(let i=0;i({style:{},transform:{},transformOrigin:{},vars:{}});function Yh(t,s,a){for(const r in s)!js(s[r])&&!Gh(r,a)&&(t[r]=s[r])}function A1({transformTemplate:t},s){return p.useMemo(()=>{const a=oc();return lc(a,s,t),Object.assign({},a.vars,a.style)},[s])}function T1(t,s){const a=t.style||{},r={};return Yh(r,a,t),Object.assign(r,A1(t,s)),r}function k1(t,s){const a={},r=T1(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 R1={offset:"stroke-dashoffset",array:"stroke-dasharray"},D1={offset:"strokeDashoffset",array:"strokeDasharray"};function P1(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?R1:D1;t[i.offset]=Je.transform(-r);const l=Je.transform(s),o=Je.transform(a);t[i.array]=`${l} ${o}`}function Kh(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(lc(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:h,style:x}=t;h.transform&&(x.transform=h.transform,delete h.transform),(x.transform||h.transformOrigin)&&(x.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),x.transform&&(x.transformBox=(m==null?void 0:m.transformBox)??"fill-box",delete h.transformBox),s!==void 0&&(h.x=s),a!==void 0&&(h.y=a),r!==void 0&&(h.scale=r),n!==void 0&&P1(h,n,i,l,!1)}const Xh=()=>({...oc(),attrs:{}}),Zh=t=>typeof t=="string"&&t.toLowerCase()==="svg";function I1(t,s,a,r){const n=p.useMemo(()=>{const i=Xh();return Kh(i,s,Zh(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};Yh(i,t.style,t),n.style={...i,...n.style}}return n}const E1=["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 cc(t){return typeof t!="string"||t.includes("-")?!1:!!(E1.indexOf(t)>-1||/[A-Z]/u.test(t))}function F1(t,s,a,{latestValues:r},n,i=!1){const o=(cc(t)?I1:k1)(s,r,n,t),c=y1(s,typeof t=="string",i),d=t!==p.Fragment?{...c,...o,ref:a}:{},{children:m}=s,h=p.useMemo(()=>js(m)?m.get():m,[m]);return p.createElement(t,{...d,children:h})}function Nm(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function dc(t,s,a,r){if(typeof s=="function"){const[n,i]=Nm(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]=Nm(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Jn(t){return js(t)?t.get():t}function _1({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:L1(a,r,n,t),renderState:s()}}function L1(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=Jn(i[x]);let{initial:l,animate:o}=t;const c=Li(t),d=Wh(t);s&&d&&!c&&t.inherit!==!1&&(l===void 0&&(l=s.initial),o===void 0&&(o=s.animate));let m=a?a.initial===!1:!1;m=m||l===!1;const h=m?o:l;if(h&&typeof h!="boolean"&&!_i(h)){const x=Array.isArray(h)?h:[h];for(let u=0;u(s,a)=>{const r=p.useContext(Fi),n=p.useContext(Ii),i=()=>_1(t,s,r,n);return a?i():_o(i)};function mc(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(js(r[l])||s.style&&js(s.style[l])||Gh(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const M1=Jh({scrapeMotionValuesFromProps:mc,createRenderState:oc});function Qh(t,s,a){const r=mc(t,s,a);for(const n in t)if(js(t[n])||js(s[n])){const i=Gr.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const $1=Jh({scrapeMotionValuesFromProps:Qh,createRenderState:Xh}),O1=Symbol.for("motionComponentSymbol");function Tr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function U1(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):Tr(a)&&(a.current=r))},[s])}const uc=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),B1="framerAppearId",qh="data-"+uc(B1),ep=p.createContext({});function V1(t,s,a,r,n){var b,f;const{visualElement:i}=p.useContext(Fi),l=p.useContext(zh),o=p.useContext(Ii),c=p.useContext(rc).reducedMotion,d=p.useRef(null);r=r||l.renderer,!d.current&&r&&(d.current=r(t,{visualState:s,parent:i,props:a,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:c}));const m=d.current,h=p.useContext(ep);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&z1(d.current,a,n,h);const x=p.useRef(!1);p.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const u=a[qh],g=p.useRef(!!u&&!((b=window.MotionHandoffIsComplete)!=null&&b.call(window,u))&&((f=window.MotionHasOptimisedAnimation)==null?void 0:f.call(window,u)));return Jx(()=>{m&&(x.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 y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,u)}),g.current=!1),m.enteringChildren=void 0)}),m}function z1(t,s,a,r){const{layoutId:n,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:tp(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&Tr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function tp(t){if(t)return t.options.allowProjection!==!1?t.projection:tp(t.parent)}function ul(t,{forwardMotionProps:s=!1}={},a,r){a&&g1(a);const n=cc(t)?$1:M1;function i(o,c){let d;const m={...p.useContext(rc),...o,layoutId:H1(o)},{isStatic:h}=m,x=j1(o),u=n(o,h);if(!h&&Lo){W1();const g=G1(m);d=g.MeasureLayout,x.visualElement=V1(t,u,m,r,g.ProjectionNode)}return e.jsxs(Fi.Provider,{value:x,children:[d&&x.visualElement?e.jsx(d,{visualElement:x.visualElement,...m}):null,F1(t,o,U1(u,x.visualElement,c),u,h,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=p.forwardRef(i);return l[O1]=t,l}function H1({layoutId:t}){const s=p.useContext(Fo).id;return s&&t!==void 0?s+"-"+t:t}function W1(t,s){p.useContext(zh).strict}function G1(t){const{drag:s,layout:a}=$r;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 Y1(t,s){if(typeof Proxy>"u")return ul;const a=new Map,r=(i,l)=>ul(i,l,t,s),n=(i,l)=>r(i,l);return new Proxy(n,{get:(i,l)=>l==="create"?r:(a.has(l)||a.set(l,ul(l,void 0,t,s)),a.get(l))})}function sp({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function K1({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function X1(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 xl(t){return t===void 0||t===1}function Jl({scale:t,scaleX:s,scaleY:a}){return!xl(t)||!xl(s)||!xl(a)}function or(t){return Jl(t)||ap(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function ap(t){return wm(t.x)||wm(t.y)}function wm(t){return t&&t!=="0%"}function xi(t,s,a){const r=t-a,n=s*r;return a+n}function Cm(t,s,a,r,n){return n!==void 0&&(t=xi(t,n,r)),xi(t,a,r)+s}function Ql(t,s=0,a=1,r,n){t.min=Cm(t.min,s,a,r,n),t.max=Cm(t.max,s,a,r,n)}function rp(t,{x:s,y:a}){Ql(t.x,s.translate,s.scale,s.originPoint),Ql(t.y,a.translate,a.scale,a.originPoint)}const Sm=.999999999999,Am=1.0000000000001;function Z1(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,l;for(let o=0;oSm&&(s.x=1),s.ySm&&(s.y=1)}function kr(t,s){t.min=t.min+s,t.max=t.max+s}function Tm(t,s,a,r,n=.5){const i=zt(t.min,t.max,n);Ql(t,s,a,i,r)}function Rr(t,s){Tm(t.x,s.x,s.scaleX,s.scale,s.originX),Tm(t.y,s.y,s.scaleY,s.scale,s.originY)}function np(t,s){return sp(X1(t.getBoundingClientRect(),s))}function J1(t,s,a){const r=np(t,a),{scroll:n}=s;return n&&(kr(r.x,n.offset.x),kr(r.y,n.offset.y)),r}const km=()=>({translate:0,scale:1,origin:0,originPoint:0}),Dr=()=>({x:km(),y:km()}),Rm=()=>({min:0,max:0}),Yt=()=>({x:Rm(),y:Rm()}),ql={current:null},ip={current:!1};function Q1(){if(ip.current=!0,!!Lo)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>ql.current=t.matches;t.addEventListener("change",s),s()}else ql.current=!1}const q1=new WeakMap;function eC(t,s,a){for(const r in s){const n=s[r],i=a[r];if(js(n))t.addValue(r,n);else if(js(i))t.addValue(r,Mr(n,{owner:t}));else if(i!==n)if(t.hasValue(r)){const l=t.getValue(r);l.liveStyle===!0?l.jump(n):l.hasAnimated||l.set(n)}else{const l=t.getStaticValue(r);t.addValue(r,Mr(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Dm=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class tC{scrapeMotionValuesFromProps(s,a,r){return{}}constructor({parent:s,props:a,presenceContext:r,reducedMotionConfig:n,blockInitialAnimation:i,visualState:l},o={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=qo,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const x=$s.now();this.renderScheduledAtthis.bindToMotionValue(n,r)),ip.current||Q1(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ql.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),Wa(this.notifyUpdate),Wa(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=Yr.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&Mt.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 $r){const a=$r[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):Yt()}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=Mr(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"&&(Qx(r)||eh(r))?r=parseFloat(r):!c1(r)&&Ga.test(a)&&(r=_h(s,a)),this.setBaseTarget(s,js(r)?r.get():r)),js(r)?r.get():r}setBaseTarget(s,a){this.baseTarget[s]=a}getBaseTarget(s){var i;const{initial:a}=this.props;let r;if(typeof a=="string"||typeof a=="object"){const l=dc(this.props,a,(i=this.presenceContext)==null?void 0:i.custom);l&&(r=l[s])}if(a&&r!==void 0)return r;const n=this.getBaseTargetFromProps(this.props,s);return n!==void 0&&!js(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 Bo),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){sc.render(this.render)}}class lp extends tC{constructor(){super(...arguments),this.KeyframeResolver=Jw}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;js(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function op(t,{style:s,vars:a},r,n){const i=t.style;let l;for(l in s)i[l]=s[l];n==null||n.applyProjectionStyles(i,r);for(l in a)i.setProperty(l,a[l])}function sC(t){return window.getComputedStyle(t)}class aC extends lp{constructor(){super(...arguments),this.type="html",this.renderInstance=op}readValueFromInstance(s,a){var r;if(Yr.has(a))return(r=this.projection)!=null&&r.isProjecting?Hl(a):gw(s,a);{const n=sC(s),i=(Ho(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return np(s,a)}build(s,a,r){lc(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return mc(s,a,r)}}const cp=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 rC(t,s,a,r){op(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(cp.has(n)?n:uc(n),s.attrs[n])}class nC extends lp{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Yt}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Yr.has(a)){const r=Fh(a);return r&&r.default||0}return a=cp.has(a)?a:uc(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return Qh(s,a,r)}build(s,a,r){Kh(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){rC(s,a,r,n)}mount(s){this.isSVGTag=Zh(s.tagName),super.mount(s)}}const iC=(t,s)=>cc(t)?new nC(s):new aC(s,{allowProjection:t!==p.Fragment});function _r(t,s,a){const r=t.getProps();return dc(r,s,a!==void 0?a:r.custom,t)}const eo=t=>Array.isArray(t);function lC(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,Mr(a))}function oC(t){return eo(t)?t[t.length-1]||0:t}function cC(t,s){const a=_r(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=oC(i[l]);lC(t,l,o)}}function dC(t){return!!(js(t)&&t.add)}function to(t,s){const a=t.getValue("willChange");if(dC(a))return a.add(s);if(!a&&Ia.WillChange){const r=new Ia.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function dp(t){return t.props[qh]}const mC=t=>t!==null;function uC(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(mC),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const xC={type:"spring",stiffness:500,damping:25,restSpeed:10},hC=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),pC={type:"keyframes",duration:.8},gC={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},fC=(t,{keyframes:s})=>s.length>2?pC:Yr.has(t)?t.startsWith("scale")?hC(s[1]):xC:gC;function bC({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:l,repeatDelay:o,from:c,elapsed:d,...m}){return!!Object.keys(m).length}const xc=(t,s,a,r={},n,i)=>l=>{const o=ec(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-ya(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-d,onUpdate:x=>{s.set(x),o.onUpdate&&o.onUpdate(x)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:t,motionValue:s,element:i?void 0:n};bC(o)||Object.assign(m,fC(t,m)),m.duration&&(m.duration=ya(m.duration)),m.repeatDelay&&(m.repeatDelay=ya(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let h=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(Xl(m),m.delay===0&&(h=!0)),(Ia.instantAnimations||Ia.skipAnimations)&&(h=!0,Xl(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,h&&!i&&s.get()!==void 0){const x=uC(m.keyframes,o);if(x!==void 0){Mt.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new Qo(m):new Ow(m)};function yC({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function mp(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in o){const h=t.getValue(m,t.latestValues[m]??null),x=o[m];if(x===void 0||d&&yC(d,m))continue;const u={delay:a,...ec(i||{},m)},g=h.get();if(g!==void 0&&!h.isAnimating&&!Array.isArray(x)&&x===g&&!u.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const y=dp(t);if(y){const v=window.MotionHandoffAnimation(y,m,Mt);v!==null&&(u.startTime=v,b=!0)}}to(t,m),h.start(xc(m,h,x,t.shouldReduceMotion&&Ph.has(m)?{type:!1}:u,t,b));const f=h.animation;f&&c.push(f)}return l&&Promise.all(c).then(()=>{Mt.update(()=>{l&&cC(t,l)})}),c}function up(t,s,a,r=0,n=1){const i=Array.from(t).sort((d,m)=>d.sortNodePosition(m)).indexOf(s),l=t.size,o=(l-1)*r;return typeof a=="function"?a(i,l):n===1?i*r:o-i*r}function so(t,s,a={}){var c;const r=_r(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(mp(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:h,staggerDirection:x}=n;return vC(t,s,d,m,h,x,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[d,m]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function vC(t,s,a=0,r=0,n=0,i=1,l){const o=[];for(const c of t.variantChildren)c.notify("AnimationStart",s),o.push(so(c,s,{...l,delay:a+(typeof r=="function"?0:r)+up(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function jC(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>so(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=so(t,s,a);else{const n=typeof s=="function"?_r(t,s,a.custom):s;r=Promise.all(mp(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function xp(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})=>jC(t,a,r)))}function AC(t){let s=SC(t),a=Pm(),r=!0;const n=c=>(d,m)=>{var x;const h=_r(t,m,c==="exit"?(x=t.presenceContext)==null?void 0:x.custom:void 0);if(h){const{transition:u,transitionEnd:g,...b}=h;d={...d,...b,...g}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=hp(t.parent)||{},h=[],x=new Set;let u={},g=1/0;for(let f=0;fg&&C,A=!1;const N=Array.isArray(w)?w:[w];let P=N.reduce(n(y),{});k===!1&&(P={});const{prevResolvedValues:R={}}=v,O={...R,...P},F=T=>{D=!0,x.has(T)&&(A=!0,x.delete(T)),v.needsAnimating[T]=!0;const j=t.getValue(T);j&&(j.liveStyle=!1)};for(const T in O){const j=P[T],U=R[T];if(u.hasOwnProperty(T))continue;let I=!1;eo(j)&&eo(U)?I=!xp(j,U):I=j!==U,I?j!=null?F(T):x.add(T):j!==void 0&&x.has(T)?F(T):v.protectedKeys[T]=!0}v.prevProp=w,v.prevResolvedValues=P,v.isActive&&(u={...u,...P}),r&&t.blockInitialAnimation&&(D=!1);const $=S&&_;D&&(!$||A)&&h.push(...N.map(T=>{const j={type:y};if(typeof T=="string"&&r&&!$&&t.manuallyAnimateOnMount&&t.parent){const{parent:U}=t,I=_r(U,T);if(U.enteringChildren&&I){const{delayChildren:M}=I.transition||{};j.delay=up(U.enteringChildren,t,M)}}return{animation:T,options:j}}))}if(x.size){const f={};if(typeof d.initial!="boolean"){const y=_r(t,Array.isArray(d.initial)?d.initial[0]:d.initial);y&&y.transition&&(f.transition=y.transition)}x.forEach(y=>{const v=t.getBaseTarget(y),w=t.getValue(y);w&&(w.liveStyle=!0),f[y]=v??null}),h.push({animation:f})}let b=!!h.length;return r&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(b=!1),r=!1,b?s(h):Promise.resolve()}function o(c,d){var h;if(a[c].isActive===d)return Promise.resolve();(h=t.variantChildren)==null||h.forEach(x=>{var u;return(u=x.animationState)==null?void 0:u.setActive(c,d)}),a[c].isActive=d;const m=l(c);for(const x in a)a[x].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=Pm()}}}function TC(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!xp(s,t):!1}function nr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Pm(){return{animate:nr(!0),whileInView:nr(),whileHover:nr(),whileTap:nr(),whileDrag:nr(),whileFocus:nr(),exit:nr()}}class Ka{constructor(s){this.isMounted=!1,this.node=s}update(){}}class kC extends Ka{constructor(s){super(s),s.animationState||(s.animationState=AC(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();_i(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 RC=0;class DC extends Ka{constructor(){super(...arguments),this.id=RC++}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 PC={animation:{Feature:kC},exit:{Feature:DC}};function Nn(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function En(t){return{point:{x:t.pageX,y:t.pageY}}}const IC=t=>s=>ac(s)&&t(s,En(s));function mn(t,s,a,r){return Nn(t,s,IC(a),r)}const pp=1e-4,EC=1-pp,FC=1+pp,gp=.01,_C=0-gp,LC=0+gp;function Ss(t){return t.max-t.min}function MC(t,s,a){return Math.abs(t-s)<=a}function Im(t,s,a,r=.5){t.origin=r,t.originPoint=zt(s.min,s.max,t.origin),t.scale=Ss(a)/Ss(s),t.translate=zt(a.min,a.max,t.origin)-t.originPoint,(t.scale>=EC&&t.scale<=FC||isNaN(t.scale))&&(t.scale=1),(t.translate>=_C&&t.translate<=LC||isNaN(t.translate))&&(t.translate=0)}function un(t,s,a,r){Im(t.x,s.x,a.x,r?r.originX:void 0),Im(t.y,s.y,a.y,r?r.originY:void 0)}function Em(t,s,a){t.min=a.min+s.min,t.max=t.min+Ss(s)}function $C(t,s,a){Em(t.x,s.x,a.x),Em(t.y,s.y,a.y)}function Fm(t,s,a){t.min=s.min-a.min,t.max=t.min+Ss(s)}function xn(t,s,a){Fm(t.x,s.x,a.x),Fm(t.y,s.y,a.y)}function Qs(t){return[t("x"),t("y")]}const fp=({current:t})=>t?t.ownerDocument.defaultView:null,_m=(t,s)=>Math.abs(t-s);function OC(t,s){const a=_m(t.x,s.x),r=_m(t.y,s.y);return Math.sqrt(a**2+r**2)}class bp{constructor(s,a,{transformPagePoint:r,contextWindow:n=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const x=pl(this.lastMoveEventInfo,this.history),u=this.startEvent!==null,g=OC(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!u&&!g)return;const{point:b}=x,{timestamp:f}=xs;this.history.push({...b,timestamp:f});const{onStart:y,onMove:v}=this.handlers;u||(y&&y(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,x)},this.handlePointerMove=(x,u)=>{this.lastMoveEvent=x,this.lastMoveEventInfo=hl(u,this.transformPagePoint),Mt.update(this.updatePoint,!0)},this.handlePointerUp=(x,u)=>{this.end();const{onEnd:g,onSessionEnd:b,resumeAnimation:f}=this.handlers;if(this.dragSnapToOrigin&&f&&f(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=pl(x.type==="pointercancel"?this.lastMoveEventInfo:hl(u,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,y),b&&b(x,y)},!ac(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=En(s),c=hl(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=xs;this.history=[{...d,timestamp:m}];const{onSessionStart:h}=a;h&&h(s,pl(c,this.history)),this.removeListeners=Dn(mn(this.contextWindow,"pointermove",this.handlePointerMove),mn(this.contextWindow,"pointerup",this.handlePointerUp),mn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),Wa(this.updatePoint)}}function hl(t,s){return s?{point:s(t.point)}:t}function Lm(t,s){return{x:t.x-s.x,y:t.y-s.y}}function pl({point:t},s){return{point:t,delta:Lm(t,yp(s)),offset:Lm(t,UC(s)),velocity:BC(s,.1)}}function UC(t){return t[0]}function yp(t){return t[t.length-1]}function BC(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=yp(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>ya(s)));)a--;if(!r)return{x:0,y:0};const i=ea(n.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const l={x:(n.x-r.x)/i,y:(n.y-r.y)/i};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function VC(t,{min:s,max:a},r){return s!==void 0&&ta&&(t=r?zt(a,t,r.max):Math.min(t,a)),t}function Mm(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 zC(t,{top:s,left:a,bottom:r,right:n}){return{x:Mm(t.x,a,n),y:Mm(t.y,s,r)}}function $m(t,s){let a=s.min-t.min,r=s.max-t.max;return s.max-s.minr?a=fn(s.min,s.max-r,t.min):r>n&&(a=fn(t.min,t.max-n,s.min)),Pa(0,1,a)}function GC(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 ao=.35;function YC(t=ao){return t===!1?t=0:t===!0&&(t=ao),{x:Om(t,"left","right"),y:Om(t,"top","bottom")}}function Om(t,s,a){return{min:Um(t,s),max:Um(t,a)}}function Um(t,s){return typeof t=="number"?t:t[s]||0}const KC=new WeakMap;class XC{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=Yt(),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=h=>{const{dragSnapToOrigin:x}=this.getProps();x?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(En(h).point)},l=(h,x)=>{const{drag:u,dragPropagation:g,onDragStart:b}=this.getProps();if(u&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=t1(u),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=x,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Qs(y=>{let v=this.getAxisMotionValue(y).get()||0;if(va.test(v)){const{projection:w}=this.visualElement;if(w&&w.layout){const C=w.layout.layoutBox[y];C&&(v=Ss(C)*(parseFloat(v)/100))}}this.originPoint[y]=v}),b&&Mt.postRender(()=>b(h,x)),to(this.visualElement,"transform");const{animationState:f}=this.visualElement;f&&f.setActive("whileDrag",!0)},o=(h,x)=>{this.latestPointerEvent=h,this.latestPanInfo=x;const{dragPropagation:u,dragDirectionLock:g,onDirectionLock:b,onDrag:f}=this.getProps();if(!u&&!this.openDragLock)return;const{offset:y}=x;if(g&&this.currentDirection===null){this.currentDirection=ZC(y),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",x.point,y),this.updateAxis("y",x.point,y),this.visualElement.render(),f&&f(h,x)},c=(h,x)=>{this.latestPointerEvent=h,this.latestPanInfo=x,this.stop(h,x),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>Qs(h=>{var x;return this.getAnimationState(h)==="paused"&&((x=this.getAxisMotionValue(h).animation)==null?void 0:x.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new bp(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:fp(this.visualElement)})}stop(s,a){const r=s||this.latestPointerEvent,n=a||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!n||!r)return;const{velocity:l}=n;this.startAnimation(l);const{onDragEnd:o}=this.getProps();o&&Mt.postRender(()=>o(r,n))}cancel(){this.isDragging=!1;const{projection:s,animationState:a}=this.visualElement;s&&(s.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),a&&a.setActive("whileDrag",!1)}updateAxis(s,a,r){const{drag:n}=this.getProps();if(!r||!Bn(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=VC(l,this.constraints[s],this.elastic[s])),i.set(l)}resolveConstraints(){var i;const{dragConstraints:s,dragElastic:a}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(i=this.visualElement.projection)==null?void 0:i.layout,n=this.constraints;s&&Tr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=zC(r.layoutBox,s):this.constraints=!1,this.elastic=YC(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&Qs(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=GC(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!Tr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=J1(r,n.root,this.visualElement.getTransformPagePoint());let l=HC(n.layout.layoutBox,i);if(a){const o=a(K1(l));this.hasMutatedConstraints=!!o,o&&(l=sp(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=Qs(m=>{if(!Bn(m,a,this.currentDirection))return;let h=c&&c[m]||{};l&&(h={min:0,max:0});const x=n?200:1e6,u=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:x,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return to(this.visualElement,s),r.start(xc(s,r,0,a,this.visualElement,!1))}stopAnimation(){Qs(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Qs(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){Qs(a=>{const{drag:r}=this.getProps();if(!Bn(a,r,this.currentDirection))return;const{projection:n}=this.visualElement,i=this.getAxisMotionValue(a);if(n&&n.layout){const{min:l,max:o}=n.layout.layoutBox[a];i.set(s[a]-zt(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!Tr(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};Qs(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=WC({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),Qs(l=>{if(!Bn(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(zt(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;KC.set(this.visualElement,this);const s=this.visualElement.current,a=mn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();Tr(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()),Mt.read(r);const l=Nn(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(Qs(m=>{const h=this.getAxisMotionValue(m);h&&(this.originPoint[m]+=c[m].translate,h.set(h.get()+c[m].translate))}),this.visualElement.render())});return()=>{l(),a(),i(),o&&o()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:l=ao,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Bn(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function ZC(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class JC extends Ka{constructor(s){super(s),this.removeGroupControls=aa,this.removeListeners=aa,this.controls=new XC(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||aa}unmount(){this.removeGroupControls(),this.removeListeners()}}const Bm=t=>(s,a)=>{t&&Mt.postRender(()=>t(s,a))};class QC extends Ka{constructor(){super(...arguments),this.removePointerDownListener=aa}onPointerDown(s){this.session=new bp(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:fp(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Bm(s),onStart:Bm(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&Mt.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=mn(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 Qn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Vm(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const en={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(Je.test(t))t=parseFloat(t);else return t;const a=Vm(t,s.target.x),r=Vm(t,s.target.y);return`${a}% ${r}%`}},qC={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=Ga.parse(t);if(n.length>5)return r;const i=Ga.createTransformer(t),l=typeof n[0]!="number"?1:0,o=a.x.scale*s.x,c=a.y.scale*s.y;n[0+l]/=o,n[1+l]/=c;const d=zt(o,c,.5);return typeof n[2+l]=="number"&&(n[2+l]/=d),typeof n[3+l]=="number"&&(n[3+l]/=d),i(n)}};let gl=!1;class e2 extends p.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;N1(t2),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),gl&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Qn.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,gl=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||Mt.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),sc.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;gl=!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 vp(t){const[s,a]=Vh(),r=p.useContext(Fo);return e.jsx(e2,{...t,layoutGroup:r,switchLayoutGroup:p.useContext(ep),isPresent:s,safeToRemove:a})}const t2={borderRadius:{...en,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:en,borderTopRightRadius:en,borderBottomLeftRadius:en,borderBottomRightRadius:en,boxShadow:qC};function s2(t,s,a){const r=js(t)?t:Mr(t);return r.start(xc("",r,s,a)),r.animation}const a2=(t,s)=>t.depth-s.depth;class r2{constructor(){this.children=[],this.isDirty=!1}add(s){Mo(this.children,s),this.isDirty=!0}remove(s){$o(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(a2),this.isDirty=!1,this.children.forEach(s)}}function n2(t,s){const a=$s.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(Wa(r),t(i-s))};return Mt.setup(r,!0),()=>Wa(r)}const jp=["TopLeft","TopRight","BottomLeft","BottomRight"],i2=jp.length,zm=t=>typeof t=="string"?parseFloat(t):t,Hm=t=>typeof t=="number"||Je.test(t);function l2(t,s,a,r,n,i){n?(t.opacity=zt(0,a.opacity??1,o2(r)),t.opacityExit=zt(s.opacity??1,0,c2(r))):i&&(t.opacity=zt(s.opacity??1,a.opacity??1,r));for(let l=0;lrs?1:a(fn(t,s,r))}function Gm(t,s){t.min=s.min,t.max=s.max}function Js(t,s){Gm(t.x,s.x),Gm(t.y,s.y)}function Ym(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function Km(t,s,a,r,n){return t-=s,t=xi(t,1/a,r),n!==void 0&&(t=xi(t,1/n,r)),t}function d2(t,s=0,a=1,r=.5,n,i=t,l=t){if(va.test(s)&&(s=parseFloat(s),s=zt(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=zt(i.min,i.max,r);t===i&&(o-=s),t.min=Km(t.min,s,a,o,n),t.max=Km(t.max,s,a,o,n)}function Xm(t,s,[a,r,n],i,l){d2(t,s[a],s[r],s[n],s.scale,i,l)}const m2=["x","scaleX","originX"],u2=["y","scaleY","originY"];function Zm(t,s,a,r){Xm(t.x,s,m2,a?a.x:void 0,r?r.x:void 0),Xm(t.y,s,u2,a?a.y:void 0,r?r.y:void 0)}function Jm(t){return t.translate===0&&t.scale===1}function wp(t){return Jm(t.x)&&Jm(t.y)}function Qm(t,s){return t.min===s.min&&t.max===s.max}function x2(t,s){return Qm(t.x,s.x)&&Qm(t.y,s.y)}function qm(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function Cp(t,s){return qm(t.x,s.x)&&qm(t.y,s.y)}function eu(t){return Ss(t.x)/Ss(t.y)}function tu(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class h2{constructor(){this.members=[]}add(s){Mo(this.members,s),s.scheduleRender()}remove(s){if($o(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 p2(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,l=(a==null?void 0:a.z)||0;if((n||i||l)&&(r=`translate3d(${n}px, ${i}px, ${l}px) `),(s.x!==1||s.y!==1)&&(r+=`scale(${1/s.x}, ${1/s.y}) `),a){const{transformPerspective:d,rotate:m,rotateX:h,rotateY:x,skewX:u,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),h&&(r+=`rotateX(${h}deg) `),x&&(r+=`rotateY(${x}deg) `),u&&(r+=`skewX(${u}deg) `),g&&(r+=`skewY(${g}deg) `)}const o=t.x.scale*s.x,c=t.y.scale*s.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const fl=["","X","Y","Z"],g2=1e3;let f2=0;function bl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Sp(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=dp(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",Mt,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Sp(r)}function Ap({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=f2++,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(v2),this.nodes.forEach(C2),this.nodes.forEach(S2),this.nodes.forEach(j2)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=l,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let c=0;cthis.root.updateBlockedByResize=!1;Mt.read(()=>{h=window.innerWidth}),t(l,()=>{const u=window.innerWidth;u!==h&&(h=u,this.root.updateBlockedByResize=!0,m&&m(),m=n2(x,250),Qn.hasAnimatedSinceResize&&(Qn.hasAnimatedSinceResize=!1,this.nodes.forEach(ru)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:h,hasRelativeLayoutChanged:x,layout:u})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||D2,{onLayoutAnimationStart:b,onLayoutAnimationComplete:f}=d.getProps(),y=!this.targetLayout||!Cp(this.targetLayout,u),v=!h&&x;if(this.options.layoutRoot||this.resumeFrom||v||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...ec(g,"layout"),onPlay:b,onComplete:f};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(m,v)}else h||ru(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=u})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Wa(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(A2),this.animationId++)}getTransformTemplate(){const{visualElement:l}=this.options;return l&&l.getProps().transformTemplate}willUpdate(l=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Sp(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&&!Ss(this.snapshot.measuredBox.x)&&!Ss(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 k=C/1e3;nu(h.x,l.x,k),nu(h.y,l.y,k),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(xn(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),k2(this.relativeTarget,this.relativeTargetOrigin,x,k),w&&x2(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=Yt()),Js(w,this.relativeTarget)),b&&(this.animationValues=m,l2(m,d,this.latestValues,k,v,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=k},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(Wa(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Mt.update(()=>{Qn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Mr(0)),this.currentAnimation=s2(this.motionValue,[0,1e3],{...l,velocity:0,isSync:!0,onUpdate:m=>{this.mixTargetDelta(m),l.onUpdate&&l.onUpdate(m)},onStop:()=>{},onComplete:()=>{l.onComplete&&l.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const l=this.getStack();l&&l.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(g2),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:m}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&Tp(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Yt();const h=Ss(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const x=Ss(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+x}Js(o,c),Rr(o,m),un(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new h2),this.sharedNodes.get(l).add(o);const d=o.options.initialPromotionConfig;o.promote({transition:d?d.transition:void 0,preserveFollowOpacity:d&&d.shouldPreserveFollowOpacity?d.shouldPreserveFollowOpacity(o):void 0})}isLead(){const l=this.getStack();return l?l.lead===this:!0}getLead(){var o;const{layoutId:l}=this.options;return l?((o=this.getStack())==null?void 0:o.lead)||this:this}getPrevLead(){var o;const{layoutId:l}=this.options;return l?(o=this.getStack())==null?void 0:o.prevLead:void 0}getStack(){const{layoutId:l}=this.options;if(l)return this.root.sharedNodes.get(l)}promote({needsReset:l,transition:o,preserveFollowOpacity:c}={}){const d=this.getStack();d&&d.promote(this,c),l&&(this.projectionDelta=void 0,this.needsReset=!0),o&&this.setOptions({transition:o})}relegate(){const l=this.getStack();return l?l.relegate(this):!1}resetSkewAndRotation(){const{visualElement:l}=this.options;if(!l)return;let o=!1;const{latestValues:c}=l;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(o=!0),!o)return;const d={};c.z&&bl("z",l,d,this.animationValues);for(let m=0;m{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(su),this.root.sharedNodes.clear()}}}function b2(t){t.updateLayout()}function y2(t){var a;const s=((a=t.resumeFrom)==null?void 0:a.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&s&&t.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:n}=t.layout,{animationType:i}=t.options,l=s.source!==t.layout.source;i==="size"?Qs(h=>{const x=l?s.measuredBox[h]:s.layoutBox[h],u=Ss(x);x.min=r[h].min,x.max=x.min+u}):Tp(i,s.layoutBox,r)&&Qs(h=>{const x=l?s.measuredBox[h]:s.layoutBox[h],u=Ss(r[h]);x.max=x.min+u,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[h].max=t.relativeTarget[h].min+u)});const o=Dr();un(o,r,s.layoutBox);const c=Dr();l?un(c,t.applyTransform(n,!0),s.measuredBox):un(c,r,s.layoutBox);const d=!wp(o);let m=!1;if(!t.resumeFrom){const h=t.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:x,layout:u}=h;if(x&&u){const g=Yt();xn(g,s.layoutBox,x.layoutBox);const b=Yt();xn(b,r,u.layoutBox),Cp(g,b)||(m=!0),h.options.layoutRoot&&(t.relativeTarget=b,t.relativeTargetOrigin=g,t.relativeParent=h)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function v2(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 j2(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function N2(t){t.clearSnapshot()}function su(t){t.clearMeasurements()}function au(t){t.isLayoutDirty=!1}function w2(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function ru(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function C2(t){t.resolveTargetDelta()}function S2(t){t.calcProjection()}function A2(t){t.resetSkewAndRotation()}function T2(t){t.removeLeadSnapshot()}function nu(t,s,a){t.translate=zt(s.translate,0,a),t.scale=zt(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function iu(t,s,a,r){t.min=zt(s.min,a.min,r),t.max=zt(s.max,a.max,r)}function k2(t,s,a,r){iu(t.x,s.x,a.x,r),iu(t.y,s.y,a.y,r)}function R2(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const D2={duration:.45,ease:[.4,0,.1,1]},lu=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),ou=lu("applewebkit/")&&!lu("chrome/")?Math.round:aa;function cu(t){t.min=ou(t.min),t.max=ou(t.max)}function P2(t){cu(t.x),cu(t.y)}function Tp(t,s,a){return t==="position"||t==="preserve-aspect"&&!MC(eu(s),eu(a),.2)}function I2(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const E2=Ap({attachResizeListener:(t,s)=>Nn(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),yl={current:void 0},kp=Ap({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!yl.current){const t=new E2({});t.mount(window),t.setOptions({layoutScroll:!0}),yl.current=t}return yl.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),F2={pan:{Feature:QC},drag:{Feature:JC,ProjectionNode:kp,MeasureLayout:vp}};function du(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&&Mt.postRender(()=>i(s,En(s)))}class _2 extends Ka{mount(){const{current:s}=this.node;s&&(this.unmount=s1(s,(a,r)=>(du(this.node,r,"Start"),n=>du(this.node,n,"End"))))}unmount(){}}class L2 extends Ka{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=Dn(Nn(this.node.current,"focus",()=>this.onFocus()),Nn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function mu(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&&Mt.postRender(()=>i(s,En(s)))}class M2 extends Ka{mount(){const{current:s}=this.node;s&&(this.unmount=i1(s,(a,r)=>(mu(this.node,r,"Start"),(n,{success:i})=>mu(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const ro=new WeakMap,vl=new WeakMap,$2=t=>{const s=ro.get(t.target);s&&s(t)},O2=t=>{t.forEach($2)};function U2({root:t,...s}){const a=t||document;vl.has(a)||vl.set(a,{});const r=vl.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(O2,{root:t,...s})),r[n]}function B2(t,s,a){const r=U2(s);return ro.set(t,a),r.observe(t),()=>{ro.delete(t),r.unobserve(t)}}const V2={some:0,all:1};class z2 extends Ka{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:a,margin:r,amount:n="some",once:i}=s,l={root:a?a.current:void 0,rootMargin:r,threshold:typeof n=="number"?n:V2[n]},o=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:h}=this.node.getProps(),x=d?m:h;x&&x(c)};return B2(this.node.current,l,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:s,prevProps:a}=this.node;["amount","margin","root"].some(H2(s,a))&&this.startObserver()}unmount(){}}function H2({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const W2={inView:{Feature:z2},tap:{Feature:M2},focus:{Feature:L2},hover:{Feature:_2}},G2={layout:{ProjectionNode:kp,MeasureLayout:vp}},Y2={...PC,...W2,...F2,...G2},ts=Y1(Y2,iC),tn=[{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:Gt,color:"from-blue-500 to-indigo-600",estimatedTime:"5-7 days",steps:7,features:["Automatic IO confirmation","Budget blocking","Document verification","E-invoice generation","Credit note issuance"],disabled:!1},{id:"vendor-payment",name:"Vendor Payment",description:"Streamlined vendor payment approval with PO validation and financial controls",category:"Finance",icon:ex,color:"from-green-500 to-emerald-600",estimatedTime:"3-5 days",steps:5,features:["PO matching","Invoice verification","Multi-level approvals","Payment scheduling"],disabled:!0,comingSoon:!0}];function K2({open:t,onClose:s,onSelectTemplate:a}){var d,m,h;const[r,n]=p.useState(null),[i,l]=p.useState(!1);p.useEffect(()=>{const x=tt.getUserData();l((x==null?void 0:x.jobTitle)==="Dealer")},[]);const o=x=>{if(i)return;const u=tn.find(g=>g.id===x);u!=null&&u.disabled||n(x)},c=()=>{r&&(a(r),s())};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{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(mt,{className:"sr-only",children:"Select a Template"}),e.jsx(Dt,{className:"sr-only",children:"Choose from pre-configured templates with predefined workflows and approval chains for faster processing."}),e.jsx("button",{onClick:s,className:"!flex absolute top-6 left-6 z-50 w-10 h-10 rounded-full bg-white shadow-lg hover:shadow-xl border border-gray-200 items-center justify-center transition-all hover:scale-110","aria-label":"Go back",children:e.jsx(Ns,{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(ts.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(qu,{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:tn.map((x,u)=>{const g=x.icon,b=r===x.id,f=i||x.disabled;return e.jsx(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:u*.1},whileHover:f?{}:{scale:1.03},whileTap:f?{}:{scale:.98},children:e.jsxs(ee,{className:`h-full transition-all duration-300 border-2 ${f?"opacity-50 cursor-not-allowed border-gray-200":b?"cursor-pointer border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"cursor-pointer border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>o(x.id),children:[e.jsxs(ge,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl bg-gradient-to-br ${x.color} flex items-center justify-center shadow-md`,children:e.jsx(g,{className:"w-7 h-7 text-white"})}),b&&e.jsx(ts.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(yr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(fe,{className:"text-xl mb-2",children:x.name}),e.jsx($e,{className:"text-sm leading-relaxed",children:x.description}),i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-amber-50 border border-amber-200 rounded-lg",children:[e.jsx(ze,{className:"w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-amber-800",children:"Not accessible for Dealers"})]}),x.comingSoon&&!i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-blue-50 border border-blue-200 rounded-lg",children:[e.jsx(ze,{className:"w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-blue-800 font-semibold",children:"Coming Soon"})]})]})]}),e.jsxs(se,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(ne,{variant:"secondary",className:"text-xs",children:x.category})}),e.jsx(Ts,{}),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(st,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:x.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ot,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[x.steps," steps"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx("p",{className:"text-xs text-gray-500 font-semibold",children:"Key Features:"}),e.jsxs("div",{className:"space-y-1.5",children:[x.features.slice(0,3).map((y,v)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(De,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:y})]},v)),x.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",x.features.length-3," more features"]})]})]})]})]})},x.id)})}),e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"flex flex-col sm:flex-row justify-center gap-4 mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(E,{onClick:c,disabled:!r||i||((d=tn.find(x=>x.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=tn.find(x=>x.id===r))!=null&&m.disabled)?"bg-blue-600 hover:bg-blue-700":"bg-gray-400 cursor-not-allowed"}`,children:["Continue with Template",e.jsx(ss,{className:"w-4 h-4"})]})]}),e.jsx(Ei,{children:r&&e.jsx(ts.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:(h=tn.find(x=>x.id===r))==null?void 0:h.name})]})})})]})})]})})}function jr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=p.useState(100),[m,h]=p.useState(0),[x,u]=p.useState(null),[g,b]=p.useState(!1),[f,y]=p.useState(null),v=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),w=s.toLowerCase().includes("pdf"),C=v||w;p.useEffect(()=>{if(!l||!C||!a){u(null);return}return(async()=>{b(!0),y(null);try{let R=a;a.startsWith("/")&&!a.startsWith("//")&&(R=`${window.location.origin}${a}`);const F=await fetch(R,{headers:{Accept:w?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!F.ok){const T=await F.text().catch(()=>"");throw new Error(`Failed to load file: ${F.status} ${F.statusText}. ${T}`)}const $=await F.blob();if($.size===0)throw new Error("File is empty or could not be loaded");w&&!$.type.includes("pdf")&&$.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${$.type}`);const V=window.URL.createObjectURL($);u(V)}catch(N){console.error("Failed to load file for preview:",N),y(N instanceof Error?N.message:"Failed to load file for preview")}finally{b(!1)}})(),()=>{x&&(window.URL.revokeObjectURL(x),u(null))}},[l,a,C,w]);const k=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},S=()=>d(A=>Math.min(A+25,200)),_=()=>d(A=>Math.max(A-25,50)),D=()=>h(A=>(A+90)%360);return e.jsx(pt,{open:l,onOpenChange:o,children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(gt,{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(ht,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`â€ĸ ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[v&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:_,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(r0,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[c,"%"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:S,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(n0,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:D,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(tx,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(E,{variant:"outline",size:"sm",onClick:k,className:"gap-2 h-9",children:[e.jsx(Ct,{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(lt,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):f?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(ft,{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:f}),i&&n&&e.jsxs(E,{onClick:k,className:"gap-2",children:[e.jsx(Ct,{className:"h-4 w-4"}),"Download ",t]})]}):C&&x?e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:x,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"})}),w&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:x,className:"w-full h-full rounded-lg border-0",title:t,style:{minHeight:"70vh",height:"100%"},onError:()=>{y("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(ht,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),i&&n&&e.jsxs(E,{onClick:k,className:"gap-2",children:[e.jsx(Ct,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function Fn({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Dt,{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(Tt,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const Ys=async t=>{const s=t?{category:t}:{};return(await je.get("/users/configurations",{params:s})).data.data},X2=async t=>{const s={};return(await je.get("/admin/configurations",{params:s})).data.data},Z2=async(t,s)=>{await je.put(`/admin/configurations/${t}`,{configValue:s})},J2=async t=>{await je.post(`/admin/configurations/${t}/reset`)},Q2=async t=>{const s=t?{year:t}:{};return(await je.get("/admin/holidays",{params:s})).data.data},q2=async t=>(await je.post("/admin/holidays",t)).data.data,eS=async(t,s)=>(await je.put(`/admin/holidays/${t}`,s)).data.data,tS=async t=>{await je.delete(`/admin/holidays/${t}`)},sS=async()=>(await je.get("/config/activity-types")).data.data,aS=async t=>{const s={activeOnly:t.toString()};return(await je.get("/admin/activity-types",{params:s})).data.data},rS=async t=>(await je.post("/admin/activity-types",t)).data.data,nS=async(t,s)=>(await je.put(`/admin/activity-types/${t}`,s)).data.data,iS=async t=>{await je.delete(`/admin/activity-types/${t}`)},lS={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 oS(t,s,a){const[r,n]=p.useState(lS),[i,l]=p.useState(null),[o,c]=p.useState(t),[d,m]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[h,x]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[u,g]=p.useState([]);return p.useEffect(()=>{(async()=>{var y;try{const v=await Ys("DOCUMENT_POLICY"),w={};v.forEach(P=>{w[P.configKey]=P.configValue});const C=parseInt(w.MAX_FILE_SIZE_MB||"10"),S=(w.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(P=>P.trim().toLowerCase());x({maxFileSizeMB:C,allowedFileTypes:S});const _=await Ys("SYSTEM_SETTINGS"),D=await Ys("WORKFLOW_SHARING"),A=[..._,...D],N={};A.forEach(P=>{N[P.configKey]=P.configValue}),m({maxApprovalLevels:parseInt(N.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(N.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((y=N.ALLOW_ADD_SPECTATOR)==null?void 0:y.toLowerCase())==="true",maxSpectators:parseInt(N.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(v){console.error("Failed to load policies:",v)}})()},[]),p.useEffect(()=>{if(!t||!s)return;let f=!0;return(async()=>{try{c(!0);const y=await vs(s);if(!f||!y)return;const v=y.workflow||{},w=Array.isArray(y.approvals)?y.approvals:[],C=Array.isArray(y.participants)?y.participants:[],k=Array.isArray(y.documents)?y.documents.filter(R=>!R.isDeleted):[];g(k);const S=(v.priority||"").toString().toLowerCase(),_={standard:"standard",express:"express"},D=v.templateType==="TEMPLATE"?"existing-template":"custom",A=a.find(R=>R.id===D)||a[0]||null;l(A);const N=w.sort((R,O)=>(R.levelNumber||0)-(O.levelNumber||0)).map(R=>{const O=Number(R.tatHours||24),F=Math.floor(O/24),$=O%24;return{id:R.approverId||`temp-${R.levelNumber}`,name:R.approverName||R.approverEmail||"",email:R.approverEmail||"",role:R.levelName||`Level ${R.levelNumber}`,department:"",avatar:(R.approverName||R.approverEmail||"XX").substring(0,2).toUpperCase(),level:R.levelNumber||1,canClose:!1,tat:F>0?F:$,tatType:F>0?"days":"hours",userId:R.approverId}}),P=C.filter(R=>(R.participantType||R.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(R.userEmail||R.user_email||R.email):!1).map((R,O)=>{const F=R.userId||R.user_id||R.id,$=R.userName||R.user_name||R.name||"",V=R.userEmail||R.user_email||R.email||"",j=($||V||"XX").split(" ").map(U=>U[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:F||`spectator-${s}-${O}-${Date.now()}`,userId:F,name:$||V||"Spectator",email:V,role:"Spectator",department:R.department||"",avatar:j,level:1,canClose:!1}});n(R=>({...R,template:D,title:v.title||"",description:v.description||"",priority:_[S]||"standard",approvers:N,approverCount:N.length||1,spectators:P,maxLevel:Math.max(...N.map(O=>O.level||1),1)}))}catch(y){console.error("Failed to load draft:",y)}finally{f&&c(!1)}})(),()=>{f=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(f,y)=>{n(v=>({...v,[f]:y}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:d,documentPolicy:h,existingDocuments:u,setExistingDocuments:g}}const uu=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function cS(t,s,a){const[r,n]=p.useState(t?2:1),i=uu.length,l=h=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(h),o=()=>{switch(r){case 1:return s!==null;case 2:return a.title.trim()!==""&&a.description.trim()!==""&&a.priority!=="";case 3:return(a.approverCount||1)>0&&a.approvers.length===(a.approverCount||1)&&a.approvers.every(h=>{if(!h||!h.email||!l(h.email))return!1;if(!h.userId)return!0;const x=h.tatType||"hours";return x==="hours"?h.tat&&h.tat>0&&h.tat<=720:x==="days"?h.tat&&h.tat>0&&h.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:uu,isStepValid:o,nextStep:()=>{o()&&(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:h=>{h>=1&&h<=i&&n(h)},validateEmail:l}}function dS(){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:(x,u,g="")=>{s({open:!0,type:x,email:u,message:g})},closeValidationModal:()=>{s(x=>({...x,open:!1}))},openPolicyViolationModal:x=>{r({open:!0,violations:x})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:x=>{i({open:!0,errors:x})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function mS(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function uS(t,s,a){var n;const r=mS(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 xS(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return uS(a,n,n===s)})}function xu(t,s,a,r=!1){return{templateId:(s==null?void 0:s.id)||null,templateType:(s==null?void 0:s.id)==="custom"?"CUSTOM":"TEMPLATE",title:t.title,description:t.description,priorityUi:t.priority==="express"?"express":"standard",approverCount:t.approverCount||1,approvers:(t.approvers||[]).map(n=>({userId:(n==null?void 0:n.userId)||"",email:(n==null?void 0:n.email)||"",name:n==null?void 0:n.name,tat:(n==null?void 0:n.tat)||24,tatType:(n==null?void 0:n.tatType)||"hours"})),spectators:(t.spectators||[]).map(n=>({userId:(n==null?void 0:n.userId)||"",name:(n==null?void 0:n.name)||"",email:(n==null?void 0:n.email)||""})),ccList:[],participants:[],isDraft:r}}function hu(t,s,a,r=!1){const n=xS(t.approvers||[],t.approverCount||1);return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:n,participants:[],deleteDocumentIds:a.length>0?a:void 0,isDraft:r}}function hS(t,s){const a=t.slice(0,s);if(a.some(l=>!(l!=null&&l.email)||!l.email.trim()))return{valid:!1,message:"Please provide email addresses for all approvers."};const n=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return a.some(l=>!n.test((l==null?void 0:l.email)||""))?{valid:!1,message:"Please provide valid email addresses for all approvers."}:{valid:!0}}async function pu(t,s){return{id:(await Io(t,s||[],"SUPPORTING")).id}}async function gu(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await sN(t,s,a||[],r):await tN(t,s)}function pS({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=p.useState(!1),[m,h]=p.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var b,f;if(c||m)return;const g=hS(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const y=hu(t,n,r,!1);await gu(l,y,a,r),K.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been submitted and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const y=xu(t,s,n,!1),v=await pu(y,a);K.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been created and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:v.id,template:s})}}catch(y){console.error("Failed to submit workflow:",y),K.error("Failed to Submit Request",{description:((f=(b=y==null?void 0:y.response)==null?void 0:b.data)==null?void 0:f.message)||(y==null?void 0:y.message)||"An error occurred while submitting the request.",duration:5e3}),d(!1)}},handleSaveDraft:async()=>{var g,b;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||m)){h(!0);try{if(i&&l){const f=hu(t,n,r,!0);await gu(l,f,a,r),K.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const f=xu(t,s,n,!0),y=await pu(f,a);K.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:y.id,template:s})}}catch(f){console.error("Failed to save draft:",f),K.error("Failed to Save Draft",{description:((b=(g=f==null?void 0:f.response)==null?void 0:g.data)==null?void 0:b.message)||(f==null?void 0:f.message)||"An error occurred while saving the draft.",duration:5e3}),h(!1)}}}}}async function ia(t,s=10,a="default"){return await je.get("/users/search",{params:{q:t,limit:s,source:a}})}async function ra(t){var a;const s=await je.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function gS(t,s){return await je.post("/admin/users/assign-role",{email:t,role:s})}async function fS(t,s){return await je.put(`/admin/users/${t}/role`,{role:s})}async function bS(t,s=1,a=10){return await je.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function yS(){return await je.get("/admin/users/role-statistics")}async function vS(t){var a;const s=await je.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function jS(){var s,a;return((a=(s=(await je.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const dr={searchUsers:ia,getUserById:vS,ensureUserExists:ra,assignRole:gS,updateUserRole:fS,getUsersByRole:bS,getRoleStatistics:yS,getAllUsers:jS};async function NS(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 ia(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 ra({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 wS(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(D),a("template",D.id),a("category",D.category),a("priority",D.priority);const A=new Date;A.setDate(A.getDate()+D.suggestedSLA),a("slaEndDate",A),D.id!=="custom"&&D.id!=="existing-template"&&u(`/create-admin-request/${D.id}`)},handleTemplateSelection:D=>{D==="claim-management"?u("/claim-management"):D==="vendor-payment"?u("/vendor-payment"):x&&x({templateType:D})},nextStep:async()=>{var D;if(i()){if(n===1&&(t==null?void 0:t.id)==="existing-template"){b(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&h){const P=r.approverCount||1;if(P>m.maxApprovalLevels){h([{type:"Maximum Approval Levels Exceeded",message:`The request has ${P} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:P,maxValue:m.maxApprovalLevels}]);return}}const A=((D=c==null?void 0:c.email)==null?void 0:D.toLowerCase())||"",N=await wS(r.approvers,A);if(!N.success&&N.error){d(N.error.type,N.error.email,N.error.message);return}N.validatedApprovers&&a("approvers",N.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(D,A)=>{if(A){const N=D.documentId||D.document_id||"";y({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:Hr(N),fileSize:Number(D.fileSize||D.file_size||0),documentId:N})}else{const N=URL.createObjectURL(D);y({fileName:D.name,fileType:D.type||"application/octet-stream",fileUrl:N,fileSize:D.size,file:D})}},closePreview:()=>{f!=null&&f.fileUrl&&(f!=null&&f.file)&&URL.revokeObjectURL(f.fileUrl),y(null)}}}const fu=[{id:"custom",name:"Non-Templatized",description:"Create a custom request for unique business needs with full flexibility to define your own workflow and requirements",category:"General",icon:Ni,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:Re,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let br=null;const bu=()=>br,SS=async t=>{const a=(await je.post("/templates",t)).data.data,r={id:a.templateId||a.id,name:a.templateName||a.name,description:a.templateDescription||a.description,category:a.templateCategory||a.category,priority:a.priority||"medium",estimatedTime:a.estimatedTime||"Variable",approvers:a.approvalLevelsConfig||a.approvers||[],suggestedSLA:a.defaultTatHours||a.suggestedSLA||24,isActive:a.isActive,fields:a.userFieldMappings||a.fields};return br&&br.push(r),r},Mi=async()=>{var r;const a=(((r=(await je.get("/templates")).data)==null?void 0:r.data)||[]).map(n=>({id:n.templateId||n.id,name:n.templateName||n.name,description:n.templateDescription||n.description,category:n.templateCategory||n.category,priority:n.priority||"medium",estimatedTime:n.estimatedTime||"Variable",approvers:n.approvalLevelsConfig||n.approvers||[],suggestedSLA:n.defaultTatHours||n.suggestedSLA||24,isActive:n.isActive,fields:n.userFieldMappings||n.fields}));return br=a,a},AS=async(t,s)=>{const r=(await je.put(`/templates/${t}`,s)).data.data,n={id:r.templateId||r.id,name:r.templateName||r.name,description:r.templateDescription||r.description,category:r.templateCategory||r.category,priority:r.priority||"medium",estimatedTime:r.estimatedTime||"Variable",approvers:r.approvalLevelsConfig||r.approvers||[],suggestedSLA:r.defaultTatHours||r.suggestedSLA||24,isActive:r.isActive,fields:r.userFieldMappings||r.fields};return br&&(br=br.map(i=>i.id===t?n:i)),n};function Rp({currentStep:t,totalSteps:s,stepNames:a}){const r=Math.round(t/s*100),n=a.length<=3?"max-w-xl":"max-w-6xl";return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-2 sm:py-3 flex-shrink-0","data-testid":"wizard-stepper",children:e.jsxs("div",{className:`${n} mx-auto`,children:[e.jsxs("div",{className:"block sm:hidden","data-testid":"wizard-stepper-mobile",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-green-600 text-white flex items-center justify-center text-xs font-semibold","data-testid":"wizard-stepper-mobile-current-step",children:t}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-900","data-testid":"wizard-stepper-mobile-step-name",children:a[t-1]}),e.jsxs("p",{className:"text-xs text-gray-600","data-testid":"wizard-stepper-mobile-step-info",children:["Step ",t," of ",s]})]})]}),e.jsx("div",{className:"text-right",children:e.jsxs("p",{className:"text-xs font-medium text-green-600","data-testid":"wizard-stepper-mobile-progress",children:[r,"%"]})})]}),e.jsx("div",{className:"w-full bg-gray-200 h-1.5 rounded-full overflow-hidden","data-testid":"wizard-stepper-mobile-progress-bar",children:e.jsx("div",{className:"bg-green-600 h-full transition-all duration-300",style:{width:`${r}%`},"data-testid":"wizard-stepper-mobile-progress-fill"})})]}),e.jsxs("div",{className:"hidden sm:block","data-testid":"wizard-stepper-desktop",children:[e.jsx("div",{className:"flex items-center justify-center gap-4 mb-2","data-testid":"wizard-stepper-desktop-steps",children:a.map((i,l)=>e.jsxs("div",{className:"flex items-center flex-1 last:flex-none","data-testid":`wizard-stepper-desktop-step-${l+1}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-xs font-semibold flex-shrink-0 ${l+1e.jsx("span",{className:`${l+1===t?"font-semibold text-green-600":""}`,"data-testid":`wizard-stepper-desktop-label-${l+1}`,children:i},l))})]})]})})}function TS({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:l,submitting:o,savingDraft:c,loadingDraft:d,isEditing:m}){return e.jsx("div",{className:"fixed sm:relative bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0 shadow-lg sm:shadow-none z-50","data-testid":"wizard-footer",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2 sm:gap-4 max-w-6xl mx-auto",children:[e.jsxs(E,{variant:"outline",onClick:r,disabled:t===1,size:"sm",className:"sm:size-lg order-2 sm:order-1","data-testid":"wizard-footer-prev-button",children:[e.jsx(Ns,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Previous"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 order-1 sm:order-2","data-testid":"wizard-footer-actions",children:[e.jsx(E,{variant:"outline",onClick:l,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:d||o||c,"data-testid":"wizard-footer-save-draft-button",children:c?e.jsxs(e.Fragment,{children:[e.jsx(lt,{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(E,{onClick:i,disabled:!a||d||o||c,size:"sm",className:"sm:size-lg bg-green-600 hover:bg-green-700 flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-submit-button",children:o?e.jsxs(e.Fragment,{children:[e.jsx(lt,{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(sx,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(E,{onClick:n,disabled:!a,size:"sm",className:"sm:size-lg flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-next-button",children:[e.jsx("span",{className:"hidden sm:inline",children:"Next Step"}),e.jsx("span",{className:"sm:hidden",children:"Next"}),e.jsx(ss,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const yu=t=>{switch(t){case"high":return e.jsx(ha,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Ot,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(ta,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Ot,{className:"w-4 h-4 text-gray-600"})}};function kS({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=p.useState("main"),l=Ks(),o=m=>{m.id==="admin-templates-category"?i("admin"):n==="admin"?l(`/create-admin-request/${m.id}`):a(m)},c=n==="main"?[...t]:r;return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"min-h-full flex flex-col items-center justify-center py-8","data-testid":"template-selection-step",children:[e.jsxs("div",{className:"text-center mb-12 max-w-3xl","data-testid":"template-selection-header",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4","data-testid":"template-selection-title",children:n==="main"?"Choose Your Request Type":"Organization Templates"}),e.jsx("p",{className:"text-lg text-gray-600","data-testid":"template-selection-description",children:n==="main"?"Start with a pre-built template for faster approvals, or create a custom request tailored to your needs.":"Select a pre-configured workflow template defined by your organization."})]}),n==="admin"&&e.jsx("div",{className:"w-full max-w-6xl mb-6 flex justify-start",children:e.jsxs(E,{variant:"ghost",className:"gap-2",onClick:()=>i("main"),children:[e.jsx(Ns,{className:"w-4 h-4"}),"Back to All Types"]})}),e.jsx("div",{className:"w-full max-w-6xl grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8","data-testid":"template-selection-grid",children:c.length===0&&n==="admin"?e.jsxs("div",{className:"col-span-full text-center py-12 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed border-gray-200",children:[e.jsx(i0,{className:"w-12 h-12 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No admin templates available yet."})]}):c.map(m=>{var g;const x=m.id==="admin-templates-category",u=(s==null?void 0:s.id)===m.id;return e.jsx(ts.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${m.id}`,children:e.jsxs(ee,{className:`h-full transition-all duration-300 border-2 ${u?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200 cursor-pointer":x?"border-blue-200 bg-blue-50/30 hover:border-blue-400 hover:shadow-lg cursor-pointer":"border-gray-200 hover:border-blue-300 hover:shadow-lg cursor-pointer"}`,onClick:()=>o(m),"data-testid":`template-card-${m.id}-clickable`,children:[e.jsxs(ge,{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 ${u||x?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${m.id}-icon`,children:e.jsx(m.icon,{className:`w-7 h-7 ${u||x?"text-blue-600":"text-gray-600"}`})}),u&&e.jsx(ts.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},"data-testid":`template-card-${m.id}-selected-indicator`,children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center",children:e.jsx(yr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsx(fe,{className:"text-xl","data-testid":`template-card-${m.id}-name`,children:m.name}),!1]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),yu(m.priority)]})]})]}),e.jsxs(se,{className:"pt-0 space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed line-clamp-2","data-testid":`template-card-${m.id}-description`,children:m.description}),!x&&e.jsxs(e.Fragment,{children:[e.jsx(Ts,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-estimated-time`,children:[e.jsx(st,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:m.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-approvers-count`,children:[e.jsx(cs,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[((g=m.commonApprovers)==null?void 0:g.length)||0," approvers"]})]})]})]}),x&&e.jsx("div",{className:"pt-2",children:e.jsx("p",{className:"text-xs text-blue-600 font-medium flex items-center gap-1",children:"Click to browse templates →"})})]})]})},m.id)})}),e.jsx(Ei,{children:s&&e.jsx(ts.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(ee,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Ur,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-sla",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Suggested SLA"}),e.jsxs("p",{className:"text-blue-700 mt-1",children:[s.suggestedSLA," hours"]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-priority",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[yu(s.priority),e.jsx("span",{className:"text-blue-700 capitalize",children:s.priority})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-duration",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Estimated Duration"}),e.jsx("p",{className:"text-blue-700 mt-1",children:s.estimatedTime})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-approvers",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((d=s.commonApprovers)==null?void 0:d.length)>0?s.commonApprovers.map((m,h)=>e.jsx(ne,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${h}`,children:m},`${s.id}-approver-${h}-${m}`)):e.jsx("span",{className:"text-sm text-gray-500 italic",children:"No specific approvers defined"})})]})]})]})})})]})}function Oe({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:ke("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 RS({className:t,...s}){return e.jsx(uf,{"data-slot":"radio-group",className:ke("grid gap-3",t),...s})}function vu({className:t,...s}){return e.jsx(xf,{"data-slot":"radio-group-item",className:ke("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(hf,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(l0,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function DS({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(ts.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(Re,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"basic-information-title",children:"Basic Information"}),e.jsxs("p",{className:"text-gray-600","data-testid":"basic-information-description",children:["Provide the essential details for your ",(s==null?void 0:s.name)||"request","."]})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"basic-information-form",children:[e.jsxs("div",{"data-testid":"basic-information-title-field",children:[e.jsx(re,{htmlFor:"title",className:"text-base font-semibold",children:"Request Title *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"Be specific and descriptive. This will be visible to all participants."}),e.jsx(Oe,{id:"title",placeholder:"e.g., Approval on new office location",value:t.title,onChange:r=>a("title",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-title-input"})]}),e.jsxs("div",{"data-testid":"basic-information-description-field",children:[e.jsx(re,{htmlFor:"description",className:"text-base font-semibold",children:"Detailed Description *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(Rn,{value:t.description||"",onChange:r=>a("description",r),placeholder:"Provide comprehensive details about your request including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px","data-testid":"basic-information-description-textarea"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6","data-testid":"basic-information-priority-section",children:e.jsxs("div",{"data-testid":"basic-information-priority-field",children:[e.jsx(re,{className:"text-base font-semibold",children:"Priority Level *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"select priority for your request"}),e.jsxs(RS,{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(vu,{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(xo,{className:"w-4 h-4 text-red-600"}),e.jsx(re,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(ne,{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(vu,{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(st,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(ne,{variant:"secondary",className:"text-xs",children:"DEFAULT"})]}),e.jsx("p",{className:"text-xs text-gray-600",children:"Includes working days in TAT - regular processing timeline"})]})]})]})]})}),((s==null?void 0:s.fields.amount)||(s==null?void 0:s.fields.vendor)||(s==null?void 0:s.fields.timeline)||(s==null?void 0:s.fields.impact))&&e.jsxs("div",{className:"border-t pt-6","data-testid":"basic-information-additional-details",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Additional Details"}),e.jsxs("div",{className:"space-y-6",children:[(s==null?void 0:s.fields.amount)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4","data-testid":"basic-information-amount-field",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(Oe,{id:"amount",placeholder:"Enter amount",value:t.amount,onChange:r=>a("amount",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-amount-input"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(We,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Ye,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"USD",children:"USD ($)"}),e.jsx(Y,{value:"EUR",children:"EUR (â‚Ŧ)"}),e.jsx(Y,{value:"GBP",children:"GBP (ÂŖ)"}),e.jsx(Y,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(re,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(Oe,{id:"vendor",placeholder:"Enter vendor or supplier name",value:t.vendor,onChange:r=>a("vendor",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-vendor-input"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{"data-testid":"basic-information-cost-center-field",children:[e.jsx(re,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(Oe,{id:"costCenter",placeholder:"e.g., Marketing, IT, Operations",value:t.costCenter,onChange:r=>a("costCenter",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-cost-center-input"})]}),e.jsxs("div",{"data-testid":"basic-information-project-field",children:[e.jsx(re,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(Oe,{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 Dp(){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 h=c.slice(1),u=((m=(await ia(h,d)).data)==null?void 0:m.data)||[];s(u)}catch(h){console.error("User search failed:",h),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await ra({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 Pp(){const[t,s]=p.useState({}),[a,r]=p.useState({}),n=p.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(o,c,d=10)=>{if(n.current[o]&&clearTimeout(n.current[o]),!c||!c.startsWith("@")||c.length<2){s(m=>({...m,[o]:[]})),r(m=>({...m,[o]:!1}));return}r(m=>({...m,[o]:!0})),n.current[o]=setTimeout(async()=>{var m;try{const h=c.slice(1),u=((m=(await ia(h,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:u}))}catch(h){console.error(`User search failed for index ${o}:`,h),s(x=>({...x,[o]:[]}))}finally{r(h=>({...h,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function PS({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var h;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=Pp();p.useEffect(()=>{const x=t.approverCount||1,u=t.approvers||[];if(u.lengthx&&s("approvers",u.slice(0,x))},[t.approverCount,s]);const d=(x,u)=>{var y,v,w,C,k;const g=[...t.approvers],f=((y=g[x])==null?void 0:y.email)!==u;if(g[x]={...g[x],email:u,level:x+1,userId:f||(v=g[x])==null?void 0:v.userId,name:f||(w=g[x])==null?void 0:w.name,department:f||(C=g[x])==null?void 0:C.department,avatar:f||(k=g[x])==null?void 0:k.avatar},s("approvers",g),!u||!u.startsWith("@")||u.length<2){c(x);return}o(x,u,10)},m=async(x,u)=>{var g,b;try{if((g=t.approvers)==null?void 0:g.some((C,k)=>{var S,_;return k!==x&&(C.userId===u.userId||((S=C.email)==null?void 0:S.toLowerCase())===((_=u.email)==null?void 0:_.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((b=t.spectators)==null?void 0:b.some(C=>{var k,S;return C.userId===u.userId||((k=C.email)==null?void 0:k.toLowerCase())===((S=u.email)==null?void 0:S.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 v=await ra({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[x]={...w[x],email:u.email,name:u.displayName||[u.firstName,u.lastName].filter(Boolean).join(" "),userId:v.userId,level:x+1},s("approvers",w),c(x)}catch(f){console.error("Failed to ensure user exists:",f),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(ts.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(cs,{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(ee,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(Va,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx($e,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(se,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(re,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const x=t.approverCount||1,u=Math.max(1,x-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(ho,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-2xl font-semibold w-12 text-center","data-testid":"approval-workflow-count-display",children:t.approverCount||1}),e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const u=(t.approverCount||1)+1;if(u>r.maxApprovalLevels){n([{type:"Maximum Approval Levels Exceeded",message:`Cannot add more than ${r.maxApprovalLevels} approval levels. Please remove an approver level or contact your administrator.`,currentValue:u,maxValue:r.maxApprovalLevels}]);return}s("approverCount",u)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(gs,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Maximum ",r.maxApprovalLevels," approver",r.maxApprovalLevels!==1?"s":""," allowed. Each approver will review sequentially."]})]})})]}),e.jsxs(ee,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(hs,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs($e,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsx("div",{className:"p-4 rounded-lg border-2 border-blue-200 bg-blue-50","data-testid":"approval-workflow-initiator-card",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center",children:e.jsx(Vt,{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(ne,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-sm text-blue-700",children:"Creates and submits the request"})]})]})}),Array.from({length:t.approverCount||1},(x,u)=>{var y,v;const g=u+1,b=g===(t.approverCount||1),f=t.approvers[u]||{email:"",tat:""};return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${g}`,children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-6 bg-gray-300"})}),e.jsx("div",{className:`p-4 rounded-lg border-2 transition-all ${f.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 ${f.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:g})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",g]}),b&&e.jsx(ne,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(re,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),f.email&&f.userId&&e.jsxs(ne,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Oe,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:f.email||"",onChange:w=>d(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-${g}-email-input`}),(l[u]||(((y=i[u])==null?void 0:y.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:l[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:(v=i[u])==null?void 0:v.map(w=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(u,w),"data-testid":`approval-workflow-approver-${g}-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-${g}-tat-field`,children:[e.jsx(re,{htmlFor:`tat-${g}`,className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Oe,{id:`tat-${g}`,type:"number",placeholder:f.tatType==="days"?"7":"24",min:"1",max:f.tatType==="days"?"30":"720",value:f.tat||"",onChange:w=>{const C=[...t.approvers];C[u]={...C[u],tat:parseInt(w.target.value)||"",level:g,tatType:f.tatType||"hours"},s("approvers",C)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(We,{value:f.tatType||"hours",onValueChange:w=>{const C=[...t.approvers];C[u]={...C[u],tatType:w,level:g,tat:""},s("approvers",C)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(Ye,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},g)})]})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ur,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900 mb-1",children:"Approval Flow Summary"}),e.jsxs("p",{className:"text-sm text-blue-700",children:["Your request will follow this sequence: ",e.jsx("strong",{children:"You (Initiator)"})," → ",Array.from({length:t.approverCount||1},(x,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(st,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const y=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+y:b+y/24},0))||0,u=Math.ceil(x);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:(h=t.approvers)==null?void 0:h.map((x,u)=>{const g=Number(x.tat||0),f=(x.tatType||"hours")==="days"?g*24:g;return g?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",u+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[f," ",f===1?"hour":"hours"]})]})},u):null})}),(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const y=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+y*24:b+y},0))||0,u=Math.ceil(x/8);return x===0?null:e.jsxs("div",{className:"bg-white/80 p-3 rounded border border-emerald-200",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[x,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children: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 IS({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=p.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=Dp(),h=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},x=async g=>{var b,f;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(w=>{var C,k;return w.userId===g.userId||((C=w.email)==null?void 0:C.toLowerCase())===((k=g.email)==null?void 0:k.toLowerCase())}),v=(b=t.approvers)==null?void 0:b.some(w=>{var C,k;return w.userId===g.userId||((C=w.email)==null?void 0:C.toLowerCase())===((k=g.email)==null?void 0:k.toLowerCase())});if(y){a({type:"error",email:g.email,message:"This user is already added as a spectator."});return}if(v){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 w=await m(g),C={id:w.userId,userId:w.userId,name:w.displayName||g.email.split("@")[0],email:w.email,avatar:(w.displayName||w.email).substring(0,2).toUpperCase(),role:"Spectator",department:w.department||"",level:1,canClose:!1},k=[...t.spectators,C];s("spectators",k),i(""),d()}catch{a({type:"error",email:g.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(w=>{var C;return((C=w.email)==null?void 0:C.toLowerCase())===n.toLowerCase()}),v=(f=t.approvers)==null?void 0:f.some(w=>{var C;return((C=w.email)==null?void 0:C.toLowerCase())===n.toLowerCase()});if(y){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(v){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}}},u=g=>{const b=t.spectators.filter(f=>f.id!==g);s("spectators",b)};return e.jsxs(ts.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(ht,{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(ee,{"data-testid":"participants-spectators-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{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(ht,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(ne,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx($e,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2","data-testid":"participants-spectators-add-section",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-full",children:[e.jsx(Oe,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>h(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.preventDefault(),await x())},className:"text-sm w-full","data-testid":"participants-spectators-email-input"}),(o||l.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:o?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:l.map(g=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>x(g),"data-testid":`participants-spectators-search-result-${g.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:g.displayName||g.email}),e.jsx("div",{className:"text-xs text-gray-600",children:g.email})]},g.userId))})})]}),e.jsx(E,{size:"sm",onClick:()=>x(),disabled:!n||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n),"data-testid":"participants-spectators-add-button",children:"Add"})]}),e.jsxs("p",{className:"text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded p-2 flex items-center gap-1",children:[e.jsx(Ur,{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(Zt,{className:"h-6 w-6",children:e.jsx(Jt,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(ft,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function ES({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:c,onDocumentErrors:d,fileInputRef:m}){const h=b=>{const f=Array.from(b.target.files||[]);if(f.length===0)return;const y=t.maxFileSizeMB*1024*1024,v=[],w=[];f.forEach(C=>{if(C.size>y){v.push({fileName:C.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(C.size/1048576).toFixed(2)}MB`});return}const k=C.name.toLowerCase(),S=k.substring(k.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(S)){v.push({fileName:C.name,reason:`File type "${S}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}w.push(C)}),w.length>0&&i([...a,...w]),v.length>0&&d&&d(v),b.target&&(b.target.value="")},x=b=>{const f=a.filter((y,v)=>v!==b);i(f)},u=b=>{o([...n,b])},g=(b,f=!1)=>{if(f){const y=(b.fileType||b.file_type||"").toLowerCase(),v=(b.originalFileName||b.fileName||"").toLowerCase();return y.includes("image")||y.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}else{const y=(b.type||"").toLowerCase(),v=(b.name||"").toLowerCase();return y.includes("image")||y.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}};return e.jsxs(ts.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(zs,{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(ee,{"data-testid":"documents-upload-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs($e,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(se,{children:e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-gray-400 transition-colors","data-testid":"documents-upload-area",children:[e.jsx(zs,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"click to browse"}),e.jsx("input",{type:"file",multiple:!0,accept:t.allowedFileTypes.map(b=>`.${b}`).join(","),onChange:h,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(E,{variant:"outline",size:"lg",type:"button",onClick:()=>{var b;return(b=m.current)==null?void 0:b.click()},"data-testid":"documents-browse-button",children:[e.jsx(gs,{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(b=>b.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(ee,{"data-testid":"documents-existing-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ne,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length," file",r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length!==1?"s":""]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(b=>{const f=b.documentId||b.document_id||"";return n.includes(f)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${f}`,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(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.originalFileName||b.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:b.fileSize?(Number(b.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!0)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>c(b,!0),"data-testid":`documents-existing-${f}-preview`,children:e.jsx(ht,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(f),"data-testid":`documents-existing-${f}-delete`,children:e.jsx(ft,{className:"h-4 w-4 text-red-600"})})]})]},f)})})})]}),a.length>0&&e.jsxs(ee,{"data-testid":"documents-new-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ne,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((b,f)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${f}`,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(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(b.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!1)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>c(b,!1),"data-testid":`documents-new-${f}-preview`,children:e.jsx(ht,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>x(f),"data-testid":`documents-new-${f}-remove`,children:e.jsx(ft,{className:"h-4 w-4"})})]})]},f))})})]})]})]})}const FS=t=>{switch(t){case"high":return e.jsx(ha,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Ot,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(ta,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Ot,{className:"w-4 h-4 text-gray-600"})}};function _S({formData:t,selectedTemplate:s}){return e.jsxs(ts.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(De,{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(ee,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(sx,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6","data-testid":"review-submit-overview-grid",children:[e.jsxs("div",{"data-testid":"review-submit-overview-type",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Request Type"}),e.jsx("p",{className:"text-green-800 mt-1",children:s==null?void 0:s.name}),e.jsx(ne,{variant:"outline",className:"mt-2 text-xs border-green-300 text-green-700",children:s==null?void 0:s.category})]}),e.jsxs("div",{"data-testid":"review-submit-overview-priority",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[FS(t.priority),e.jsx("span",{className:"text-green-800 capitalize",children:t.priority})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-workflow",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Workflow Type"}),e.jsx("p",{className:"text-green-800 mt-1 capitalize",children:t.workflowType}),e.jsxs("p",{className:"text-sm text-green-700",children:[t.approverCount||1," Level",(t.approverCount||1)>1?"s":""]})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-title",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Request Title"}),e.jsx("p",{className:"text-green-800 font-medium mt-1 text-lg",children:t.title})]})]})]}),e.jsxs(ee,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(re,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(sa,{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(Da,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{className:"font-semibold text-blue-900",children:"Financial Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Amount"}),e.jsxs("p",{className:"font-semibold text-blue-900",children:[t.amount," ",t.currency]})]}),t.costCenter&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Cost Center"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.costCenter})]})]})]})]})]}),e.jsxs(ee,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(cs,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx($e,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(se,{className:"space-y-6",children:e.jsx("div",{className:"space-y-4","data-testid":"review-submit-approval-levels",children:Array.from({length:t.approverCount||1},(a,r)=>{const n=r+1,i=n===(t.approverCount||1),l=t.approvers[r];return e.jsx("div",{className:"p-4 bg-white rounded-lg border border-orange-200","data-testid":`review-submit-approval-level-${n}`,children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${l!=null&&l.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:n})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",n]}),i&&e.jsx(ne,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Email Address"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:(l==null?void 0:l.email)||"Not assigned"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"TAT (Turn Around Time)"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l!=null&&l.tat?`${l.tat} ${l.tatType==="days"?"day":"hour"}${l.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(ee,{"data-testid":"review-submit-participants-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(ht,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(se,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(re,{className:"font-semibold text-sm",children:["Spectators (",t.spectators.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:t.spectators.map(a=>e.jsxs(ne,{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(ee,{"data-testid":"review-submit-documents-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(zs,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs($e,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"review-submit-documents-list",children:t.documents.map((a,r)=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-gray-50 rounded-lg border","data-testid":`review-submit-document-${r}`,children:[e.jsx(Re,{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(ee,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(se,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(De,{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 LS({isEditing:t,currentStep:s,totalSteps:a,stepNames:r,onBack:n}){return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0","data-testid":"create-request-header",children:e.jsxs("div",{className:"flex items-center justify-between max-w-6xl mx-auto gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-1 min-w-0",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"create-request-back-button",children:e.jsx(Ns,{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 MS({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(Ei,{mode:"wait",children:t})})})}function $S({modal:t,onClose:s}){return e.jsx(pt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Dt,{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(Ni,{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(Tt,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function OS({modal:t,documentPolicy:s,onClose:a}){return e.jsx(pt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Dt,{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(Tt,{children:e.jsx(E,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function ju({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Ea(),i=Ks(),l=n.requestId||a||"",o=r&&!!l,{user:c}=Kt(),[d,m]=p.useState([]);p.useEffect(()=>{(async()=>{try{const rt=(await Mi()).map(ut=>({id:ut.id,name:ut.name,description:ut.description,category:ut.category,icon:Re,estimatedTime:ut.estimatedTime,commonApprovers:ut.approvers.map(nt=>nt.name),workflowApprovers:ut.approvers,suggestedSLA:ut.suggestedSLA,priority:ut.priority,fields:ut.fields||{}}));m(rt)}catch(_e){console.error("Failed to fetch admin templates:",_e)}})()},[]);const h=p.useMemo(()=>[...fu,...d],[d]),{formData:x,updateFormData:u,selectedTemplate:g,setSelectedTemplate:b,loadingDraft:f,systemPolicy:y,documentPolicy:v,existingDocuments:w,setExistingDocuments:C}=oS(o,l,h),{currentStep:k,totalSteps:S,stepNames:_,isStepValid:D,nextStep:A,prevStep:N}=cS(o,g,x),[P,R]=p.useState([]),[O,F]=p.useState([]),$=p.useRef(null),{validationModal:V,policyViolationModal:T,documentErrorModal:j,openValidationModal:U,closeValidationModal:I,openPolicyViolationModal:M,closePolicyViolationModal:W,openDocumentErrorModal:G,closeDocumentErrorModal:ce}=dS(),{submitting:te,savingDraft:L,handleSubmit:z,handleSaveDraft:H}=pS({formData:x,selectedTemplate:g,documents:P,documentsToDelete:O,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:ye,setShowTemplateModal:ae,previewDocument:me,selectTemplate:Q,handleTemplateSelection:oe,nextStep:Ce,prevStep:Ee,handlePreviewDocument:be,closePreview:q}=CS({selectedTemplate:g,setSelectedTemplate:b,updateFormData:u,formData:x,currentStep:k,isStepValid:D,wizardNextStep:A,wizardPrevStep:N,user:c,openValidationModal:U,systemPolicy:y,onPolicyViolation:M,onSubmit:s}),ue=p.useCallback(()=>{if(k===1){i("/dashboard",{replace:!0});return}k===3||k===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Ee()},[k,t,i,Ee]),Ae=p.useRef(!0),Ue=p.useRef(!1);p.useEffect(()=>{Ae.current&&x.documents&&x.documents.length>0&&!Ue.current&&(R(x.documents),Ue.current=!0),Ae.current=!1},[x.documents]);const Z=p.useRef(!1),Te=p.useRef(P);p.useEffect(()=>{if(Z.current){Z.current=!1,Te.current=P;return}Te.current!==P&&(u("documents",P),Te.current=P)},[P]);const Xe=()=>{switch(k){case 1:return e.jsx(kS,{templates:fu,selectedTemplate:g,onSelectTemplate:Q,adminTemplates:d});case 2:return e.jsx(DS,{formData:x,selectedTemplate:g,updateFormData:u});case 3:return e.jsx(PS,{formData:x,updateFormData:u,systemPolicy:y,onValidationError:pe=>U(pe.type,pe.email,pe.message),onPolicyViolation:M});case 4:return e.jsx(IS,{formData:x,updateFormData:u,onValidationError:pe=>U(pe.type,pe.email,pe.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(ES,{documentPolicy:v,isEditing:o,documents:P,existingDocuments:w,documentsToDelete:O,onDocumentsChange:R,onExistingDocumentsChange:C,onDocumentsToDeleteChange:F,onPreviewDocument:be,onDocumentErrors:pe=>G(pe),fileInputRef:$});case 6:return e.jsx(_S,{formData:x,selectedTemplate:g});default:return null}};return f?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(LS,{isEditing:o,currentStep:k,totalSteps:S,stepNames:_,onBack:ue}),e.jsx(Rp,{currentStep:k,totalSteps:S,stepNames:_}),e.jsx(MS,{children:Xe()}),e.jsx(TS,{currentStep:k,totalSteps:S,isStepValid:D(),onPrev:Ee,onNext:Ce,onSubmit:z,onSaveDraft:H,submitting:te,savingDraft:L,loadingDraft:f,isEditing:o}),e.jsx(K2,{open:ye,onClose:()=>ae(!1),onSelectTemplate:oe}),me&&e.jsx(jr,{fileName:me.fileName,fileType:me.fileType,fileUrl:me.fileUrl,fileSize:me.fileSize,open:!!me,onClose:q,onDownload:async()=>{if(me.file){const pe=document.createElement("a");pe.href=me.fileUrl,pe.download=me.fileName,document.body.appendChild(pe),pe.click(),document.body.removeChild(pe)}else me.documentId&&await ps(me.documentId)},attachmentId:me.documentId}),e.jsx($S,{modal:V,onClose:I}),e.jsx(OS,{modal:j,documentPolicy:v,onClose:ce}),e.jsx(Fn,{open:T.open,onClose:W,violations:T.violations,policyDetails:{maxApprovalLevels:y.maxApprovalLevels,maxParticipants:y.maxParticipants,allowSpectators:y.allowSpectators,maxSpectators:y.maxSpectators}})]})}function $i({className:t,...s}){return e.jsx(pf,{"data-slot":"tabs",className:ke("flex flex-col gap-2",t),...s})}function Oi({className:t,...s}){return e.jsx(gf,{"data-slot":"tabs-list",className:ke("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function qt({className:t,...s}){return e.jsx(ff,{"data-slot":"tabs-trigger",className:ke("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 es({className:t,...s}){return e.jsx(bf,{"data-slot":"tabs-content",className:ke("flex-1 outline-none",t),...s})}function hc(t,s=[],a){const[r,n]=p.useState(null),[i,l]=p.useState(!1),[o,c]=p.useState(!0),[d,m]=p.useState(null),[h,x]=p.useState(null),[u,g]=p.useState(!1),b=(k,S)=>(k||S||"NA").toString().split(" ").map(D=>D[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),f=k=>{const S=(k||"").toUpperCase();return S==="IN_PROGRESS"?"in-review":S==="PENDING"?"pending":S==="APPROVED"?"approved":S==="REJECTED"?"rejected":S==="CLOSED"?"closed":S==="SKIPPED"?"skipped":(k||"").toLowerCase()},y=p.useCallback(async()=>{var k,S,_,D,A,N,P,R,O,F,$,V,T;l(!0);try{const j=await ks.getWorkflowDetails(t);if(!j){console.warn("[useRequestDetails] No details returned from API");return}const U=j.workflow||{},I=Array.isArray(j.approvals)?j.approvals:[],M=Array.isArray(j.participants)?j.participants:[],W=Array.isArray(j.documents)?j.documents:[],G=j.summary||{},ce=Array.isArray(j.tatAlerts)?j.tatAlerts:[];ce.length>0;const te=(G==null?void 0:G.currentLevel)||U.currentLevel||1,L=I.map(Z=>{const Te=Z.levelNumber||0,Xe=(Z.status||"").toString().toUpperCase(),pe=Z.levelId||Z.level_id;let _e=f(Z.status);Te>te&&Xe!=="APPROVED"&&Xe!=="REJECTED"?_e="waiting":Te===te&&Xe==="PENDING"&&(_e="pending");const rt=ce.filter(ut=>ut.levelId===pe);return{step:Te,levelId:pe,role:Z.levelName||Z.approverName||"Approver",status:_e,approver:Z.approverName||Z.approverEmail,approverId:Z.approverId||Z.approver_id,approverEmail:Z.approverEmail,tatHours:Number(Z.tatHours||0),elapsedHours:Number(Z.elapsedHours||0),remainingHours:Number(Z.remainingHours||0),tatPercentageUsed:Number(Z.tatPercentageUsed||0),actualHours:Z.levelEndTime&&Z.levelStartTime?Math.max(0,(new Date(Z.levelEndTime).getTime()-new Date(Z.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:Z.comments||void 0,timestamp:Z.actionDate||void 0,levelStartTime:Z.levelStartTime||Z.tatStartTime,tatAlerts:rt,skipReason:Z.skipReason||void 0,isSkipped:Xe==="SKIPPED"||Z.isSkipped||!1}}),z=M.filter(Z=>(Z.participantType||Z.participant_type||"").toUpperCase()==="SPECTATOR").map(Z=>({name:Z.userName||Z.user_name||Z.userEmail||Z.user_email,role:"Spectator",email:Z.userEmail||Z.user_email,avatar:b(Z.userName||Z.user_name,Z.userEmail||Z.user_email)})),H=Z=>{var Xe,pe;if(!Z)return;const Te=M.find(_e=>_e.userId===Z||_e.user_id===Z);return Te!=null&&Te.userName||Te!=null&&Te.user_name?Te.userName||Te.user_name:U.initiatorId===Z?((Xe=U.initiator)==null?void 0:Xe.displayName)||((pe=U.initiator)==null?void 0:pe.email):Z},ye=W.map(Z=>{const Te=Number(Z.fileSize||Z.file_size||0),Xe=(Te/(1024*1024)).toFixed(2)+" MB";return{documentId:Z.documentId||Z.document_id,name:Z.originalFileName||Z.fileName||Z.file_name,fileType:Z.fileType||Z.file_type||"",size:Xe,sizeBytes:Te,uploadedBy:H(Z.uploadedBy||Z.uploaded_by),uploadedAt:Z.uploadedAt||Z.uploaded_at}}),ae=Array.isArray(j.activities)?j.activities.filter(Z=>(Z.type||"").toLowerCase()!=="sla_warning"):[];let me=null;if(U.isPaused||!1)try{me=await Zd(U.requestId)}catch{}let oe=null,Ce=null,Ee=null,be=null;if(U.workflowType==="CLAIM_MANAGEMENT"||U.templateType==="claim-management")try{const Z=await je.get(`/dealer-claims/${U.requestId}`),Te=((k=Z.data)==null?void 0:k.data)||Z.data;if(Te){oe=Te.claimDetails||Te.claim_details,Ce=Te.proposalDetails||Te.proposal_details,Ee=Te.completionDetails||Te.completion_details,be=Te.internalOrder||Te.internal_order||null;const Xe=Te.budgetTracking||Te.budget_tracking||null,pe=Te.invoice||null,_e=Te.creditNote||Te.credit_note||null,rt=Te.completionExpenses||Te.completion_expenses||null;oe&&(oe.budgetTracking=Xe,oe.invoice=pe,oe.creditNote=_e,oe.completionExpenses=rt)}else console.warn("[useRequestDetails] No claimData found in response")}catch(Z){console.error("[useRequestDetails] Error fetching claim details:",{error:(Z==null?void 0:Z.message)||Z,status:(S=Z==null?void 0:Z.response)==null?void 0:S.status,statusText:(_=Z==null?void 0:Z.response)==null?void 0:_.statusText,responseData:(D=Z==null?void 0:Z.response)==null?void 0:D.data,requestId:U.requestId})}const q={...U,id:U.requestNumber||U.requestId,requestId:U.requestId,requestNumber:U.requestNumber,title:U.title,description:U.description,status:f(U.status),priority:(U.priority||"").toString().toLowerCase(),workflowType:U.workflowType||(U.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:L,approvals:I,participants:M,documents:ye,spectators:z,summary:G,sla:(G==null?void 0:G.sla)||U.sla||null,initiator:{name:((A=U.initiator)==null?void 0:A.displayName)||((N=U.initiator)==null?void 0:N.email),role:((P=U.initiator)==null?void 0:P.designation)||void 0,department:((R=U.initiator)==null?void 0:R.department)||void 0,email:((O=U.initiator)==null?void 0:O.email)||void 0,phone:((F=U.initiator)==null?void 0:F.phone)||void 0,avatar:b(($=U.initiator)==null?void 0:$.displayName,(V=U.initiator)==null?void 0:V.email)},createdAt:U.createdAt,updatedAt:U.updatedAt,totalSteps:U.totalLevels||1,currentStepRaw:(G==null?void 0:G.currentLevel)||U.currentLevel||1,currentStep:Math.min(Math.max(1,(G==null?void 0:G.currentLevel)||U.currentLevel||1),U.totalLevels||1),auditTrail:ae,conclusionRemark:U.conclusionRemark||null,closureDate:U.closureDate||null,pauseInfo:me||null,claimDetails:oe||null,proposalDetails:Ce||null,completionDetails:Ee||null,internalOrder:be||null,budgetTracking:(oe==null?void 0:oe.budgetTracking)||null,invoice:(oe==null?void 0:oe.invoice)||null,creditNote:(oe==null?void 0:oe.creditNote)||null,completionExpenses:(oe==null?void 0:oe.completionExpenses)||null};n(q);const ue=(T=a==null?void 0:a.email)==null?void 0:T.toLowerCase(),Ae=I.find(Z=>{const Te=(Z.status||"").toString().toUpperCase(),Xe=(Z.approverEmail||"").toLowerCase(),pe=Z.levelNumber||0;return(Te==="PENDING"||Te==="IN_PROGRESS"||Te==="PAUSED")&&Xe===ue&&pe===te});x(Ae||null);const Ue=a==null?void 0:a.userId;if(Ue){const Z=M.some(Te=>(Te.participantType||Te.participant_type||"").toUpperCase()==="SPECTATOR"&&(Te.userId||Te.user_id)===Ue);g(Z)}else g(!1)}catch(j){console.error("[useRequestDetails] Error refreshing details:",j),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);p.useEffect(()=>{if(!t){c(!1);return}let k=!0;return c(!0),m(null),(async()=>{var S,_,D,A,N,P,R,O,F,$,V,T,j,U;try{const I=await ks.getWorkflowDetails(t);if(!k||!I){k&&c(!1);return}const M=I.workflow||{},W=Array.isArray(I.approvals)?I.approvals:[],G=Array.isArray(I.participants)?I.participants:[],ce=Array.isArray(I.documents)?I.documents:[],te=I.summary||{},L=Array.isArray(I.tatAlerts)?I.tatAlerts:[],z=(M.priority||"").toString().toLowerCase(),H=(te==null?void 0:te.currentLevel)||M.currentLevel||1,ye=W.map(pe=>{const _e=pe.levelNumber||0,rt=(pe.status||"").toString().toUpperCase(),ut=pe.levelId||pe.level_id;let nt=f(pe.status);rt==="PAUSED"?nt="paused":_e>H&&rt!=="APPROVED"&&rt!=="REJECTED"?nt="waiting":_e===H&&(rt==="PENDING"||rt==="IN_PROGRESS")&&(nt=rt==="IN_PROGRESS"?"in-review":"pending");const Ps=L.filter(Xs=>Xs.levelId===ut);return{step:_e,levelId:ut,role:pe.levelName||pe.approverName||"Approver",status:nt,approver:pe.approverName||pe.approverEmail,approverId:pe.approverId||pe.approver_id,approverEmail:pe.approverEmail,tatHours:Number(pe.tatHours||0),elapsedHours:Number(pe.elapsedHours||0),remainingHours:Number(pe.remainingHours||0),tatPercentageUsed:Number(pe.tatPercentageUsed||0),actualHours:pe.elapsedHours!==void 0&&pe.elapsedHours!==null?Number(pe.elapsedHours):void 0,comment:pe.comments||void 0,timestamp:pe.actionDate||void 0,levelStartTime:pe.levelStartTime||pe.tatStartTime,tatAlerts:Ps}}),ae=G.filter(pe=>(pe.participantType||"").toUpperCase()==="SPECTATOR").map(pe=>({name:pe.userName||pe.userEmail,role:"Spectator",avatar:b(pe.userName,pe.userEmail)})),me=pe=>{var rt,ut;if(!pe)return;const _e=G.find(nt=>nt.userId===pe);return _e!=null&&_e.userName?_e.userName:M.initiatorId===pe?((rt=M.initiator)==null?void 0:rt.displayName)||((ut=M.initiator)==null?void 0:ut.email):pe},Q=ce.map(pe=>{const _e=Number(pe.fileSize||0),rt=(_e/(1024*1024)).toFixed(2)+" MB";return{documentId:pe.documentId||pe.document_id,name:pe.originalFileName||pe.fileName,fileType:pe.fileType||pe.file_type||"",size:rt,sizeBytes:_e,uploadedBy:me(pe.uploadedBy),uploadedAt:pe.uploadedAt}}),oe=Array.isArray(I.activities)?I.activities.filter(pe=>(pe.type||"").toLowerCase()!=="sla_warning"):[];let Ce=null;if(M.isPaused||!1)try{Ce=await Zd(M.requestId)}catch{}let be=null,q=null,ue=null,Ae=null;if(M.workflowType==="CLAIM_MANAGEMENT"||M.templateType==="claim-management")try{const pe=await je.get(`/dealer-claims/${M.requestId}`),_e=((S=pe.data)==null?void 0:S.data)||pe.data;if(_e){be=_e.claimDetails||_e.claim_details,q=_e.proposalDetails||_e.proposal_details,ue=_e.completionDetails||_e.completion_details,Ae=_e.internalOrder||_e.internal_order||null;const rt=_e.budgetTracking||_e.budget_tracking||null,ut=_e.invoice||null,nt=_e.creditNote||_e.credit_note||null,Ps=_e.completionExpenses||_e.completion_expenses||null;be&&(be.budgetTracking=rt,be.invoice=ut,be.creditNote=nt,be.completionExpenses=Ps)}}catch(pe){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(pe==null?void 0:pe.message)||pe,status:(_=pe==null?void 0:pe.response)==null?void 0:_.status,requestId:M.requestId})}const Ue={id:M.requestNumber||M.requestId,requestId:M.requestId,title:M.title,description:M.description,priority:z,status:f(M.status),workflowType:M.workflowType||(M.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:te,initiator:{name:((D=M.initiator)==null?void 0:D.displayName)||((A=M.initiator)==null?void 0:A.email),role:((N=M.initiator)==null?void 0:N.designation)||void 0,department:((P=M.initiator)==null?void 0:P.department)||void 0,email:((R=M.initiator)==null?void 0:R.email)||void 0,phone:((O=M.initiator)==null?void 0:O.phone)||void 0,avatar:b((F=M.initiator)==null?void 0:F.displayName,($=M.initiator)==null?void 0:$.email)},createdAt:M.createdAt,updatedAt:M.updatedAt,totalSteps:M.totalLevels||1,currentStepRaw:(te==null?void 0:te.currentLevel)||M.currentLevel||1,currentStep:Math.min(Math.max(1,(te==null?void 0:te.currentLevel)||M.currentLevel||1),M.totalLevels||1),approvalFlow:ye,approvals:W,documents:Q,spectators:ae,auditTrail:oe,conclusionRemark:M.conclusionRemark||null,closureDate:M.closureDate||null,pauseInfo:Ce||null,claimDetails:be||null,proposalDetails:q||null,completionDetails:ue||null,internalOrder:Ae||null,budgetTracking:(be==null?void 0:be.budgetTracking)||null,invoice:(be==null?void 0:be.invoice)||null,creditNote:(be==null?void 0:be.creditNote)||null,completionExpenses:(be==null?void 0:be.completionExpenses)||null};n(Ue);const Z=(V=a==null?void 0:a.email)==null?void 0:V.toLowerCase(),Te=W.find(pe=>{const _e=(pe.status||"").toString().toUpperCase(),rt=(pe.approverEmail||"").toLowerCase(),ut=pe.levelNumber||0;return(_e==="PENDING"||_e==="IN_PROGRESS"||_e==="PAUSED")&&rt===Z&&ut===H});x(Te||null);const Xe=a==null?void 0:a.userId;if(Xe){const pe=G.some(_e=>(_e.participantType||"").toUpperCase()==="SPECTATOR"&&_e.userId===Xe);g(pe)}else g(!1)}catch(I){if(console.error("[useRequestDetails] Error loading request details:",I),k){if(((T=I==null?void 0:I.response)==null?void 0:T.status)===403){const M=((U=(j=I==null?void 0:I.response)==null?void 0:j.data)==null?void 0:U.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:M})}n(null)}}finally{k&&c(!1)}})(),()=>{k=!1}},[t,a]);const v=p.useMemo(()=>{if(r)return r;const k=s.find(S=>S.id===t||S.requestNumber===t||S.request_number===t);return k||null},[t,s,r]),w=p.useMemo(()=>{var _,D,A;if(!v||!a)return!1;const k=(_=a==null?void 0:a.email)==null?void 0:_.toLowerCase(),S=(A=(D=v.initiator)==null?void 0:D.email)==null?void 0:A.toLowerCase();return k===S},[v,a]),C=p.useMemo(()=>{var S;if(!v)return[];const k=[];return(S=v.initiator)!=null&&S.email&&k.push({email:v.initiator.email.toLowerCase(),participantType:"INITIATOR",name:v.initiator.name}),v.approvalFlow&&Array.isArray(v.approvalFlow)&&v.approvalFlow.forEach(_=>{_.approverEmail&&k.push({email:_.approverEmail.toLowerCase(),participantType:"APPROVER",name:_.approver})}),v.spectators&&Array.isArray(v.spectators)&&v.spectators.forEach(_=>{_.email&&k.push({email:_.email.toLowerCase(),participantType:"SPECTATOR",name:_.name})}),v.participants&&Array.isArray(v.participants)&&v.participants.forEach(_=>{const D=(_.userEmail||_.email||"").toLowerCase(),A=(_.participantType||_.participant_type||"").toUpperCase(),N=_.userName||_.user_name||_.name;D&&A&&!k.find(P=>P.email===D)&&k.push({email:D,participantType:A,name:N})}),k},[v]);return p.useEffect(()=>{if(!t||!r)return;const k=Lr();if(!k)return;const S=_=>{((_==null?void 0:_.requestId)===r.requestId||(_==null?void 0:_.requestNumber)===t)&&y()};return k.on("request:updated",S),()=>{k.off("request:updated",S)}},[t,r,y]),{request:v,apiRequest:r,loading:o,refreshing:i,refreshDetails:y,currentApprovalLevel:h,isSpectator:u,isInitiator:w,existingParticipants:C,accessDenied:d}}function Ip(t,s,a,r){const[n,i]=p.useState([]),[l,o]=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,h=t;return(async()=>{var b;try{const f=await ks.getWorkflowDetails(t);(b=f==null?void 0:f.workflow)!=null&&b.requestId&&m&&(h=f.workflow.requestId)}catch(f){console.error("[useRequestSocket] Failed to resolve UUID:",f)}if(!m)return;const x=Lr();if(!x){console.error("[useRequestSocket] Socket not available");return}const u=r==null?void 0:r.userId,g=()=>{Ml(x,h,u)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),Ax(x,h))}})(),()=>{m=!1}},[t,r]),p.useEffect(()=>{!t||!s||(async()=>{try{const m=await Fr(t),h=s.auditTrail||[],x=[...m,...h];x.sort((u,g)=>{const b=new Date(u.createdAt||u.created_at||u.timestamp||0).getTime(),f=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return b-f}),i(x)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),p.useEffect(()=>{if(!t)return;const m=Lr();if(!m)return;const h=u=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await Fr(t),b=(s==null?void 0:s.auditTrail)||[],f=[...g,...b].sort((y,v)=>{const w=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime(),C=new Date(v.createdAt||v.created_at||v.timestamp||0).getTime();return w-C});i(f)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},x=u=>{const g=u.type==="breach"?"⏰":u.type==="threshold2"?"âš ī¸":"âŗ";(async()=>{try{const b=await ks.getWorkflowDetails(t);b&&(Array.isArray(b.tatAlerts)&&b.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:u.message,icon:"/favicon.ico",tag:`tat-${u.requestId}-${u.type}`,requireInteraction:!1}))}catch(b){console.error("[useRequestSocket] Failed to refresh after TAT alert:",b)}})()};return m.on("noteHandler",h),m.on("worknote:new",h),m.on("tat:alert",x),()=>{m.off("noteHandler",h),m.off("worknote:new",h),m.off("tat:alert",x)}},[t,a,s]),p.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function nn(t,s,a="SUPPORTING"){var l;const r=new FormData;r.append("file",t),r.append("requestId",s),r.append("category",a);const n=await je.post("/documents",r,{headers:{"Content-Type":"multipart/form-data"}}),i=((l=n.data)==null?void 0:l.data)||n.data;return{documentId:(i==null?void 0:i.documentId)||(i==null?void 0:i.document_id)||"",storageUrl:(i==null?void 0:i.storageUrl)||(i==null?void 0:i.storage_url),fileName:(i==null?void 0:i.fileName)||(i==null?void 0:i.file_name)||t.name,originalFileName:(i==null?void 0:i.originalFileName)||(i==null?void 0:i.original_file_name)||t.name}}function Ep(t,s){const[a,r]=p.useState(!1),[n,i]=p.useState(null),[l,o]=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 Ys("DOCUMENT_POLICY"),b={};g.forEach(w=>{b[w.configKey]=w.configValue});const f=parseInt(b.MAX_FILE_SIZE_MB||"10"),v=(b.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(w=>w.trim().toLowerCase());o({maxFileSizeMB:f,allowedFileTypes:v})}catch(g){console.error("Failed to load document policy:",g)}})()},[]);const m=u=>{const g=l.maxFileSizeMB*1024*1024;if(u.size>g)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${l.maxFileSizeMB}MB. Current size: ${(u.size/(1024*1024)).toFixed(2)}MB`};const b=u.name.toLowerCase(),f=b.substring(b.lastIndexOf(".")+1);return l.allowedFileTypes.includes(f)?{valid:!0}:{valid:!1,reason:`File type "${f}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},h=async u=>{var v,w;const g=u.target.files;if(!g||g.length===0)return;const b=Array.from(g),f=[],y=[];if(b.forEach(C=>{const k=m(C);k.valid?y.push(C):f.push({fileName:C.name,reason:k.reason||"Unknown validation error"})}),f.length>0&&d({show:!0,errors:f}),y.length===0){u.target&&(u.target.value="");return}r(!0);try{const C=y[0],k=t==null?void 0:t.requestId;if(!k){K.error("Request ID not found");return}C&&await nn(C,k,"SUPPORTING"),await s(),y.length{const u=document.createElement("input");u.type="file",u.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),u.onchange=h,u.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}const US="modulepreload",BS=function(t){return"/"+t},Nu={},jl=function(s,a,r){let n=Promise.resolve();if(a&&a.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));n=Promise.allSettled(a.map(c=>{if(c=BS(c),c in Nu)return;Nu[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":US,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((x,u)=>{h.addEventListener("load",x),h.addEventListener("error",()=>u(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return n.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};function Fp(t,s,a,r,n,i,l){const[o,c]=p.useState(""),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(!1),[b,f]=p.useState(0),[y,v]=p.useState(!1),[w,C]=p.useState(!1),[k,S]=p.useState(0),_=async()=>{var R;const N=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),P=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(N||P){c(N||P),g(!!P);return}try{const{getConclusion:O}=await jl(async()=>{const{getConclusion:$}=await import("./conclusionApi-CzJL-0h7.js");return{getConclusion:$}},__vite__mapDeps([0,1,2,3,4,5,6,7])),F=await O(t.requestId||s);F&&(F.aiGeneratedRemark||F.finalRemark)&&(c(F.finalRemark||F.aiGeneratedRemark||""),g(!!F.aiGeneratedRemark))}catch(O){((R=O==null?void 0:O.response)==null?void 0:R.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",O)}},D=async()=>{if(!w)try{m(!0),v(!1);const{generateConclusion:N}=await jl(async()=>{const{generateConclusion:F}=await import("./conclusionApi-CzJL-0h7.js");return{generateConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7])),P=await N(t.requestId||s),R=b+1;if(f(R),!(P!=null&&P.aiGeneratedRemark)||P.aiGeneratedRemark.toLowerCase().includes("unable to generate")||P.aiGeneratedRemark.toLowerCase().includes("sorry")){const F=k+1;S(F),F>=2?(C(!0),i==null||i({success:!1,title:"AI Generation Limit Reached",message:"We're unable to process a conclusion remark at this time after 2 attempts. Please proceed with a manual approach using the editor below."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process a conclusion remark at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0),c((P==null?void 0:P.aiGeneratedRemark)||""),g(!1);return}c(P.aiGeneratedRemark),g(!0),S(0),R>=2&&(C(!0),i==null||i({success:!0,title:"Maximum Attempts Reached",message:"You've reached the maximum of 2 regeneration attempts. Feel free to manually edit the current suggestion to fit your specific needs."}),l==null||l(!0))}catch(N){console.error("[useConclusionRemark] AI generation failed:",N);const P=k+1;S(P),g(!1),P>=2?(C(!0),i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. Since the maximum of 2 attempts is reached, please proceed with a manual approach."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0)}finally{m(!1)}},A=async()=>{var P,R;const N=o.replace(/<[^>]*>/g,"").trim();if(!N){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),l==null||l(!0);return}if(N.length>2e3){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark exceeds 2000 characters limit"}),l==null||l(!0);return}try{x(!0);const{finalizeConclusion:O}=await jl(async()=>{const{finalizeConclusion:F}=await import("./conclusionApi-CzJL-0h7.js");return{finalizeConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await O(t.requestId||s,o),i==null||i({success:!0,title:"Request Closed with Successful Completion",message:"The request has been finalized and moved to Closed Requests."}),l==null||l(!0),await r(),setTimeout(()=>{n?(n(),setTimeout(()=>{window.location.hash="#/closed-requests"},100)):window.location.hash="#/closed-requests"},2e3)}catch(O){i==null||i({success:!1,title:"Error",message:((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{x(!1)}};return p.useEffect(()=>{var F;const N=(F=t==null?void 0:t.status)==null?void 0:F.toLowerCase();if(!((N==="approved"||N==="rejected"||N==="closed")&&a&&!o))return;const R=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),O=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);R||O?(c(R||O),g(!!O)):_()},[t==null?void 0:t.status,t==null?void 0:t.conclusionRemark,t==null?void 0:t.aiGeneratedConclusion,a,o]),{conclusionRemark:o,setConclusionRemark:c,conclusionLoading:d,conclusionSubmitting:h,aiGenerated:u,handleGenerateConclusion:D,handleFinalizeConclusion:A,generationAttempts:b,generationFailed:y,maxAttemptsReached:w}}function _p(t,s,a){const[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState(!1),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(!1),[b,f]=p.useState(null),[y,v]=p.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:h,setShowSkipApproverModal:x,showActionStatusModal:u,setShowActionStatusModal:g,skipApproverData:b,setSkipApproverData:f,actionStatus:y,setActionStatus:v,handleApproveConfirm:async D=>{var N,P;const A=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!A){alert("Approval level not found");return}await an(t,A,D||""),await new Promise(R=>setTimeout(R,500)),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Approved successfully")},handleRejectConfirm:async D=>{var N,P;if(!(D!=null&&D.trim())){alert("Comments & remarks are required");return}const A=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!A){alert("Approval level not found");return}await Sr(t,A,D.trim(),D.trim()),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Rejected successfully")},handleAddApprover:async(D,A,N)=>{var P,R;try{await Vx(t,D,A,N),await a(),c(!1),v==null||v({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${A}h TAT`}),g==null||g(!0)}catch(O){throw v==null||v({success:!1,title:"Failed to Add Approver",message:((R=(P=O==null?void 0:O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to add approver. Please try again."}),g==null||g(!0),O}},handleSkipApprover:async D=>{var A,N;if(b)try{await Zj(t,b.levelId,D),await a(),x(!1),f(null),v==null||v({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),g==null||g(!0)}catch(P){throw v==null||v({success:!1,title:"Failed to Skip Approver",message:((N=(A=P==null?void 0:P.response)==null?void 0:A.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),P}},handleAddSpectator:async D=>{var A,N;try{await zx(t,D),await a(),m(!1),v==null||v({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),g==null||g(!0)}catch(P){throw v==null||v({success:!1,title:"Failed to Add Spectator",message:((N=(A=P==null?void 0:P.response)==null?void 0:A.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),P}}}}const VS=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 Or({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(Re,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900","data-testid":`${n}-name`,children:t.name}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${n}-metadata`,children:[t.size&&e.jsxs("span",{children:[t.size," â€ĸ "]}),t.uploadedBy&&e.jsxs("span",{children:["Uploaded by ",t.uploadedBy," on "]}),Qt(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&VS(t.fileType)&&s&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>s({fileName:t.name,fileType:t.fileType,documentId:t.documentId,fileSize:t.sizeBytes}),title:"Preview file","data-testid":`${n}-preview-btn`,children:e.jsx(ht,{className:"w-4 h-4"})}),a&&e.jsx(E,{variant:"ghost",size:"sm",onClick:async()=>{if(!t.documentId){alert("Document ID not available");return}try{await a(t.documentId)}catch{alert("Failed to download document")}},title:"Download file","data-testid":`${n}-download-btn`,children:e.jsx(Ct,{className:"w-4 h-4"})})]})]})}function zS({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l}){return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(ee,{children:[e.jsx(ge,{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(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx($e,{className:"text-xs sm:text-sm mt-1",children:"Documents attached while creating the request"})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsxs(E,{size:"sm",onClick:n,disabled:a||t.status==="closed",className:"gap-1 sm:gap-2 h-8 sm:h-9 text-xs sm:text-sm shrink-0","data-testid":"upload-document-btn",children:[e.jsx(zs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a?"Uploading...":t.status==="closed"?"Closed":"Upload",e.jsx("span",{className:"hidden sm:inline",children:t.status==="closed"?"":"Document"})]}),e.jsxs("p",{className:"text-xs text-gray-500 whitespace-nowrap",children:["Max ",r.maxFileSizeMB,"MB"]})]})]})}),e.jsx(se,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((o,c)=>e.jsx(Or,{document:o,onPreview:d=>i(d),onDownload:l,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(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(As,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(se,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((o,c)=>e.jsx(Or,{document:{documentId:o.attachmentId||"",name:o.name,fileType:o.type||"",size:o.size?`${(o.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:o.size,uploadedBy:o.uploadedBy,uploadedAt:o.uploadedAt},onPreview:d=>i(d),onDownload:async d=>{const{downloadWorkNoteAttachment:m}=require("@/services/workflowApi");await m(d)},testId:"worknote-attachment"},o.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 HS=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"}}},WS=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}}},GS=t=>{switch(t){case"approval":case"approved":return e.jsx(De,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(wt,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(As,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx($t,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(wi,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Re,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(st,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(vi,{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(kt,{className:"w-5 h-5 text-gray-600"})}};function YS({request:t}){return e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(kt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(se,{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:GS(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(kt,{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 Lp({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsx(gt,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[a?e.jsx(De,{className:"w-5 h-5 text-green-600"}):e.jsx(ze,{className:"w-5 h-5 text-red-600"}),r||(a?"Success":"Error")]})}),e.jsx("div",{className:"py-6",children:e.jsx("div",{className:"flex flex-col items-center text-center",children:a?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mb-4",children:e.jsx(De,{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(wt,{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(Tt,{children:e.jsx(E,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function Mp({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=p.useState(""),[l,o]=p.useState(!1),[c,d]=p.useState([]),[m,h]=p.useState(!1),[x,u]=p.useState(null),g=p.useRef(null),b=p.useRef(null),[f,y]=p.useState({open:!1,type:"error",email:"",message:""}),[v,w]=p.useState({open:!1,violations:[]}),[C,k]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});p.useEffect(()=>{t&&(async()=>{var P;try{const R=await Ys("WORKFLOW_SHARING"),O=await Ys("TAT_SETTINGS"),F=[...R,...O],$={};F.forEach(V=>{$[V.configKey]=V.configValue}),k({maxApprovalLevels:parseInt($.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt($.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((P=$.ALLOW_ADD_SPECTATOR)==null?void 0:P.toLowerCase())==="true",maxSpectators:parseInt($.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(R){console.error("Failed to load system policy:",R)}})()},[t]);const S=async()=>{var T,j;const N=n.trim().toLowerCase();if(!N){y({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(N)){y({open:!0,type:"error",email:N,message:"Please enter a valid email address"});return}const R=r.find(U=>(U.email||"").toLowerCase()===N);if(R){const U=((T=R.participantType)==null?void 0:T.toUpperCase())||"PARTICIPANT",I=R.name||N;if(U==="INITIATOR"){y({open:!0,type:"error",email:N,message:`${I} is the request initiator and cannot be added as a spectator.`});return}else if(U==="APPROVER"){y({open:!0,type:"error",email:N,message:`${I} is already an approver on this request and cannot be added as a spectator.`});return}else if(U==="SPECTATOR"){y({open:!0,type:"error",email:N,message:`${I} is already a spectator on this request.`});return}else{y({open:!0,type:"error",email:N,message:`${I} is already a participant on this request.`});return}}const O=[];C.allowSpectators||O.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const $=r.filter(U=>(U.participantType||"").toUpperCase()==="SPECTATOR").length;$>=C.maxSpectators&&O.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:$,maxValue:C.maxSpectators});const V=r.length+1;if(V>C.maxParticipants&&O.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:V,maxValue:C.maxParticipants}),O.length>0){w({open:!0,violations:O});return}if(!x||x.email.toLowerCase()!==N)try{const I=((j=(await ia(N,1)).data)==null?void 0:j.data)||[];if(I.length===0){y({open:!0,type:"not-found",email:N,message:""});return}const M=I[0];await ra({userId:M.userId,email:M.email,displayName:M.displayName,firstName:M.firstName,lastName:M.lastName,department:M.department,phone:M.phone,mobilePhone:M.mobilePhone,designation:M.designation,jobTitle:M.jobTitle,manager:M.manager,employeeId:M.employeeId,employeeNumber:M.employeeNumber,secondEmail:M.secondEmail,location:M.location})}catch(U){console.error("Failed to validate spectator:",U),y({open:!0,type:"error",email:N,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(N),i(""),u(null),s()}catch(U){console.error("Failed to add spectator:",U)}finally{o(!1)}},_=()=>{l||(i(""),u(null),d([]),h(!1),s())};p.useEffect(()=>{c.length>0&&b.current&&b.current.scrollTo({top:b.current.scrollHeight,behavior:"smooth"})},[c.length]),p.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const D=N=>{if(i(N),x&&x.email.toLowerCase()!==N.toLowerCase()&&u(null),g.current&&clearTimeout(g.current),!N||!N.startsWith("@")||N.length<2){d([]),h(!1);return}h(!0),g.current=setTimeout(async()=>{var P;try{const R=N.slice(1),F=((P=(await ia(R,10)).data)==null?void 0:P.data)||[];d(F)}catch(R){console.error("Search failed:",R),d([])}finally{h(!1)}},300)},A=async N=>{try{await ra({userId:N.userId,email:N.email,displayName:N.displayName,firstName:N.firstName,lastName:N.lastName,department:N.department,phone:N.phone,mobilePhone:N.mobilePhone,designation:N.designation,jobTitle:N.jobTitle,manager:N.manager,employeeId:N.employeeId,employeeNumber:N.employeeNumber,secondEmail:N.secondEmail,location:N.location}),i(N.email),u(N),d([]),h(!1)}catch(P){console.error("Failed to ensure user exists:",P),y({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(pt,{open:t,onOpenChange:_,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:_,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:l,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(gt,{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(ht,{className:"w-5 h-5 text-purple-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:b,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a 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(Ci,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Oe,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:N=>D(N.target.value),className:"pl-10 h-11 border-gray-300",disabled:l,autoFocus:!0}),(m||c.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:m?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):c.length>0?e.jsx("ul",{className:"divide-y",children:c.map(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>A(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zt,{className:"h-8 w-8",children:e.jsx(Jt,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(N.displayName||N.email).split(" ").map(P=>P[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:N.displayName||[N.firstName,N.lastName].filter(Boolean).join(" ")||N.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:N.email}),N.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:N.designation})]})]})},N.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:_,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:S,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(ht,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(pt,{open:f.open,onOpenChange:N=>y(P=>({...P,open:N})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:f.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[f.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:f.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(Ni,{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."]})})]}),f.type==="error"&&e.jsxs(e.Fragment,{children:[f.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:f.email}),"."]}),f.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:f.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:()=>y(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(Fn,{open:v.open,onClose:()=>w({open:!1,violations:[]}),violations:v.violations,policyDetails:{maxApprovalLevels:C.maxApprovalLevels,maxParticipants:C.maxParticipants,allowSpectators:C.allowSpectators,maxSpectators:C.maxSpectators}})]})}function $p({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=p.useState(""),[d,m]=p.useState(24),[h,x]=p.useState(null),[u,g]=p.useState(!1),[b,f]=p.useState([]),[y,v]=p.useState(!1),[w,C]=p.useState(null),k=p.useRef(null),S=p.useRef(null),[_,D]=p.useState({open:!1,type:"error",email:"",message:""}),A=n.filter(j=>j&&(j.status==="approved"||j.status==="rejected"||j.status==="skipped")),N=Math.max(1,A.length+1),P=Math.max(1,n.length+1),R=P>=N?Array.from({length:P-N+1},(j,U)=>N+U):[N];p.useEffect(()=>{R.length>0&&h===null&&x(R[0]||null)},[R.length,h]);const O=async()=>{var G,ce;const j=o.trim().toLowerCase();if(!j){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(j)){D({open:!0,type:"error",email:j,message:"Please enter a valid email address"});return}if(!d||d<=0){D({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(d>720){D({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!h){D({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(h0?Math.max(...n.map(te=>te.levelNumber),0):0,M=h>I?h:I+1;if(i&&M>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${h} would result in ${M} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:M,maxValue:i}]):D({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${I} level(s).`});return}const W=r.find(te=>(te.email||"").toLowerCase()===j);if(W){const te=((G=W.participantType)==null?void 0:G.toUpperCase())||"PARTICIPANT",L=W.name||j;if(te==="INITIATOR"){D({open:!0,type:"error",email:j,message:`${L} is the request initiator and cannot be added as an approver.`});return}else if(te==="APPROVER"){D({open:!0,type:"error",email:j,message:`${L} is already an approver on this request.`});return}else if(te==="SPECTATOR"){D({open:!0,type:"error",email:j,message:`${L} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{D({open:!0,type:"error",email:j,message:`${L} is already a participant on this request.`});return}}if(!w||w.email.toLowerCase()!==j)try{const L=((ce=(await ia(j,1)).data)==null?void 0:ce.data)||[];if(L.length===0){D({open:!0,type:"not-found",email:j,message:""});return}const z=L[0];await ra({userId:z.userId,email:z.email,displayName:z.displayName,firstName:z.firstName,lastName:z.lastName,department:z.department,phone:z.phone,mobilePhone:z.mobilePhone,designation:z.designation,jobTitle:z.jobTitle,manager:z.manager,employeeId:z.employeeId,employeeNumber:z.employeeNumber,secondEmail:z.secondEmail,location:z.location})}catch(te){console.error("Failed to validate approver:",te),D({open:!0,type:"error",email:j,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(j,d,h),c(""),m(24),x(null),C(null),s()}catch(te){console.error("Failed to add approver:",te)}finally{g(!1)}},F=()=>{u||(c(""),m(24),x(null),C(null),f([]),v(!1),s())},$=j=>{const U=j.toLowerCase();return U==="approved"?e.jsx(De,{className:"w-4 h-4 text-green-600"}):U==="rejected"?e.jsx(wt,{className:"w-4 h-4 text-red-600"}):U==="skipped"?e.jsx(ze,{className:"w-4 h-4 text-orange-600"}):U==="in-review"||U==="pending"?e.jsx(st,{className:"w-4 h-4 text-blue-600"}):e.jsx(st,{className:"w-4 h-4 text-gray-400"})};p.useEffect(()=>{b.length>0&&S.current&&S.current.scrollTo({top:S.current.scrollHeight,behavior:"smooth"})},[b.length]),p.useEffect(()=>()=>{k.current&&clearTimeout(k.current)},[]);const V=j=>{if(c(j),w&&w.email.toLowerCase()!==j.toLowerCase()&&C(null),k.current&&clearTimeout(k.current),!j||!j.startsWith("@")||j.length<2){f([]),v(!1);return}v(!0),k.current=setTimeout(async()=>{var U;try{const I=j.slice(1),W=((U=(await ia(I,10)).data)==null?void 0:U.data)||[];f(W)}catch(I){console.error("Search failed:",I),f([])}finally{v(!1)}},300)},T=async j=>{try{await ra({userId:j.userId,email:j.email,displayName:j.displayName,firstName:j.firstName,lastName:j.lastName,department:j.department,phone:j.phone,mobilePhone:j.mobilePhone,designation:j.designation,jobTitle:j.jobTitle,manager:j.manager,employeeId:j.employeeId,employeeNumber:j.employeeNumber,secondEmail:j.secondEmail,location:j.location}),c(j.email),C(j),f([]),v(!1)}catch(U){console.error("Failed to ensure user exists:",U),D({open:!0,type:"error",email:j.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(pt,{open:t,onOpenChange:F,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:F,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:u,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(gt,{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(cs,{className:"w-5 h-5 text-blue-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:S,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a new approver at a specific level. Existing approvers at and after the selected level will be shifted down."}),i&&e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-2",children:e.jsxs("p",{className:"text-xs text-blue-800",children:["â„šī¸ Max: ",i," level",i!==1?"s":"",n.length>0&&e.jsxs("span",{className:"ml-2",children:["(",Math.max(...n.map(j=>j.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-semibold text-gray-700",children:"Current Approval Levels"}),e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-2 border rounded-lg p-3 bg-gray-50",children:n.map(j=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${j.status==="approved"?"bg-green-100 border border-green-200":j.status==="rejected"?"bg-red-100 border border-red-200":j.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:j.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:j.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[j.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[$(j.status),e.jsx(ne,{variant:"outline",className:`text-xs ${j.status==="approved"?"bg-green-50 text-green-700 border-green-300":j.status==="rejected"?"bg-red-50 text-red-700 border-red-300":j.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:j.status})]})]},j.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:["â„šī¸ New approver can only be added at level ",N," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(We,{value:(h==null?void 0:h.toString())||"",onValueChange:j=>x(Number(j)),disabled:u,children:[e.jsx(Ye,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select level"})}),e.jsx(Ke,{children:R.map(j=>e.jsx(Y,{value:j.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",j]}),j<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",j,")"]})]})},j))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Choose where to insert the new approver. Existing levels will be automatically shifted."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{type:"number",min:"1",max:"720",value:d,onChange:j=>m(Number(j.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(st,{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(Ci,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Oe,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:j=>V(j.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(y||b.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:y?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):b.length>0?e.jsx("ul",{className:"divide-y",children:b.map(j=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>T(j),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zt,{className:"h-8 w-8",children:e.jsx(Jt,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(j.displayName||j.email).split(" ").map(U=>U[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:j.displayName||[j.firstName,j.lastName].filter(Boolean).join(" ")||j.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:j.email}),j.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:j.designation})]})]})},j.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:F,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:O,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!o.trim()||!h||!d,children:[e.jsx(cs,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${h||"?"}`]})]})]}),e.jsx(pt,{open:_.open,onOpenChange:j=>D(U=>({...U,open:j})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:_.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[_.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:_.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(Ni,{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."]})})]}),_.type==="error"&&e.jsxs(e.Fragment,{children:[_.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:_.email}),"."]}),_.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:_.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:()=>D(j=>({...j,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const KS=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"}},XS=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},ZS=t=>{const s=t.replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,(a,r,n,i)=>{const l=n+a.length,o=i[l];return!o||/\s|[.,!?;:]|@/.test(o)?'@'+r+"":a}).replace(/\n/g,"
");return ba(s)},JS=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",wu=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Re,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(d0,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Re,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Re,{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(Wn,{className:`${s} text-purple-600`}):e.jsx(vi,{className:`${s} text-gray-600`})};function Op({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:c=[],onAddApprover:d,maxApprovalLevels:m,onPolicyViolation:h}){const x=Ea(),u=t||x.requestId||"",[g,b]=p.useState(""),[f,y]=p.useState(""),[v,w]=p.useState(!1),[C,k]=p.useState([]),[S,_]=p.useState(!1),[D,A]=p.useState([]),[N,P]=p.useState(null),[R,O]=p.useState(null),[F,$]=p.useState(!1),[V,T]=p.useState(!1),[j,U]=p.useState(!1),[I,M]=p.useState({success:!0,title:"",message:""}),W=p.useRef(null),G=p.useRef(null),ce=p.useRef(null),te=p.useRef(!1),[L,z]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[H,ye]=p.useState({open:!1,errors:[]}),ae=p.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[me,Q]=p.useState([]),oe=me.filter(X=>X.status==="online"),Ce=C.filter(X=>X.content.toLowerCase().includes(f.toLowerCase())||X.user.name.toLowerCase().includes(f.toLowerCase())),Ee=p.useMemo(()=>o!==void 0?o:!N||me.length===0?!1:me.some(X=>{const we=X.userId||X.user_id,J=(X.role||"").toString().toUpperCase(),Le=(X.participantType||X.participant_type||"").toString().toUpperCase();return we===N&&(J==="SPECTATOR"||Le==="SPECTATOR")}),[o,N,me]);p.useEffect(()=>{},[me]),p.useEffect(()=>{!u||!N||s||(async()=>{try{const X=await Fr(u),we=Array.isArray(X)?X.map(J=>{const Le=J.userId||J.user_id;return{id:J.noteId||J.id||String(Math.random()),user:{name:J.userName||"User",avatar:(J.userName||"U").slice(0,2).toUpperCase(),role:J.userRole||"Participant"},content:J.message||"",timestamp:J.createdAt||new Date().toISOString(),isCurrentUser:Le===N,attachments:Array.isArray(J.attachments)?J.attachments.map(Fe=>({attachmentId:Fe.attachmentId||Fe.attachment_id,name:Fe.fileName||Fe.file_name||Fe.name,fileName:Fe.fileName||Fe.file_name||Fe.name,url:Fe.storageUrl||Fe.storage_url||Fe.url||"#",type:Fe.fileType||Fe.file_type||Fe.type||"file",fileType:Fe.fileType||Fe.file_type||Fe.type||"file",fileSize:Fe.fileSize||Fe.file_size})):void 0}}):[];k(we)}catch(X){console.error("[WorkNoteChat] Failed to load messages:",X)}})()},[u,N,s]);const be=p.useMemo(()=>{const X=[];return C.forEach(we=>{we.attachments&&we.attachments.length>0&&we.attachments.forEach(J=>{X.push({attachmentId:J.attachmentId||J.attachment_id,name:J.fileName||J.file_name||J.name||"Untitled",fileName:J.fileName||J.file_name||J.name||"Untitled",size:J.fileSize||J.file_size,type:J.fileType||J.file_type||J.type||"file",uploadedBy:we.user.name,uploadedAt:we.timestamp,url:J.storageUrl||J.storage_url||J.url||"#"})})}),X},[C]);p.useEffect(()=>{i&&be.length>=0&&i(be)},[be,i]);const q=p.useMemo(()=>me.map(X=>({email:(X.email||"").toLowerCase(),participantType:X.role==="Initiator"?"INITIATOR":X.role==="Approver"?"APPROVER":X.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:X.name})),[me]),ue=X=>{if(!X)return"Participant";switch(X.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()}},Ae=()=>{var X;(X=W.current)==null||X.scrollIntoView({behavior:"smooth"})};p.useEffect(()=>{Ae()},[C]);const Ue=X=>{switch(X.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()}};p.useEffect(()=>{te.current||u&&(async()=>{try{const X=await vs(u),we=Array.isArray(X==null?void 0:X.participants)?X.participants:[];if(we.length===0)return;const J=we.map(Me=>{const Ze=Me.participantType||Me.participant_type||"participant",Be=Me.userId||Me.user_id||"";return{name:Me.userName||Me.user_name||Me.user_email||Me.userEmail||"User",avatar:(Me.userName||Me.user_name||Me.user_email||"U").toString().split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ue(Ze.toString()),status:"offline",email:Me.userEmail||Me.user_email||"",permissions:["read","write","mention"],userId:Be}});te.current=!0,Q(J);let Le=0;const Fe=3,Ve=()=>{ce.current&&ce.current.connected?(ce.current.emit("request:online-users",{requestId:u}),Le++,Le()=>{u&&(te.current=!1)},[u]),p.useEffect(()=>{const X=localStorage.getItem("userData");if(X)try{const we=JSON.parse(X),J=(we==null?void 0:we.id)||(we==null?void 0:we.userId)||(we==null?void 0:we.user_id)||null;P(J)}catch(we){console.error("[WorkNoteChat] Failed to parse userData:",we)}},[]),p.useEffect(()=>{(async()=>{try{const we=await Ys("DOCUMENT_POLICY"),J={};we.forEach(Me=>{J[Me.configKey]=Me.configValue});const Le=parseInt(J.MAX_FILE_SIZE_MB||"10"),Ve=(J.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Me=>Me.trim().toLowerCase());z({maxFileSizeMB:Le,allowedFileTypes:Ve})}catch(we){console.error("Failed to load document policy:",we)}})()},[]),p.useEffect(()=>{if(!N)return;let X=u;return(async()=>{var we;try{const J=await vs(u);(we=J==null?void 0:J.workflow)!=null&&we.requestId&&(X=J.workflow.requestId)}catch{}try{const J=Lr();r?Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)):(Ml(J,X,N),Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)));const Le=at=>{const et=(at==null?void 0:at.note)||at;if(!et)return;const yt=et.noteId||et.id;k(rs=>{if(rs.some(St=>St.id===yt))return rs;const Pt=et.userName||et.user_name||"User",la=et.userRole||et.user_role,pa=ue(la),Fa=et.userId||et.user_id,wa={id:yt||String(Date.now()),user:{name:Pt,avatar:Pt.split(" ").map(St=>St[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:pa},content:et.message||"",timestamp:et.createdAt||new Date().toISOString(),isCurrentUser:Fa===N,attachments:Array.isArray(et.attachments)?et.attachments.map(St=>({attachmentId:St.attachmentId||St.attachment_id,name:St.fileName||St.file_name||St.name,fileName:St.fileName||St.file_name||St.name,url:St.storageUrl||St.storage_url||St.url||"#",type:St.fileType||St.file_type||St.type||"file",fileType:St.fileType||St.file_type||St.type||"file",fileSize:St.fileSize||St.file_size})):void 0};return[...rs,wa]})},Fe=at=>{Q(et=>et.length===0||!et.find(Pt=>Pt.userId===at.userId)?et:et.map(Pt=>Pt.userId===at.userId?{...Pt,status:"online"}:Pt))},Ve=at=>{at.userId!==N&&Q(et=>et.length===0||!et.find(Pt=>Pt.userId===at.userId)?et:et.map(Pt=>Pt.userId===at.userId?{...Pt,status:"offline"}:Pt))},Me=at=>{Q(et=>et.length===0?et:et.map(rs=>{const Pt=rs.userId||"";if(Pt===N)return{...rs,status:"online"};const pa=at.userIds.includes(Pt);return{...rs,status:pa?"online":"offline"}}))},Ze=()=>{Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)),r||Ml(J,X,N),te.current&&(J.emit("request:online-users",{requestId:X}),setTimeout(()=>J.emit("request:online-users",{requestId:X}),300),setTimeout(()=>J.emit("request:online-users",{requestId:X}),800))},Be=at=>{console.error("[WorkNoteChat] ❌ Socket error:",at)},qe=at=>{console.warn("[WorkNoteChat] âš ī¸ Socket disconnected:",at),Q(et=>et.map(yt=>yt.userId===N?yt:{...yt,status:"offline"}))},fs=at=>{at.includes("presence")||at.includes("worknote")||at.includes("request")};J.on("connect",Ze),J.on("disconnect",qe),J.on("error",Be),J.on("worknote:new",Le),J.on("presence:join",Fe),J.on("presence:leave",Ve),J.on("presence:online",Me),J.onAny(fs),ce.current=J,J.connected&&te.current&&(J.emit("request:online-users",{requestId:X}),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},300),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},800),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},1500));const Ht=()=>{J.off("connect",Ze),J.off("disconnect",qe),J.off("error",Be),J.off("worknote:new",Le),J.off("presence:join",Fe),J.off("presence:leave",Ve),J.off("presence:online",Me),J.offAny(fs),r||Ax(J,X),ce.current=null};window.__wn_cleanup=Ht}catch{}})(),()=>{var we;try{(we=window.__wn_cleanup)==null||we.call(window)}catch{}}},[u,N,r]);const Z=async()=>{if(g.trim()||D.length>0){const X=Xs(g),we=X.map(Fe=>{const Ve=me.find(Me=>Me.name.toLowerCase().includes(Fe.toLowerCase()));return Ve==null?void 0:Ve.userId}).filter(Boolean),J=D.map(Fe=>({name:Fe.name,url:URL.createObjectURL(Fe),type:Fe.type.split("/")[1]||"file"})),Le={id:Date.now().toString(),user:{name:"You",avatar:"YO",role:"Current User"},content:g,timestamp:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),mentions:X,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:J.length>0?J:void 0,isCurrentUser:!0};if(a)try{await a(g,D)}catch{}else try{await Bx(u,{message:g,mentions:we},D);const Fe=await Fr(u),Ve=Array.isArray(Fe)?Fe.map(Me=>{const Ze=Me.userId||Me.user_id;return{id:Me.noteId||Me.id||String(Math.random()),user:{name:Me.userName||"User",avatar:(Me.userName||"U").slice(0,2).toUpperCase(),role:Me.userRole||"Participant"},content:Me.message||"",timestamp:Me.createdAt||new Date().toISOString(),isCurrentUser:Ze===N,attachments:Array.isArray(Me.attachments)?Me.attachments.map(Be=>({attachmentId:Be.attachmentId||Be.attachment_id,name:Be.fileName||Be.file_name||Be.name,fileName:Be.fileName||Be.file_name||Be.name,url:Be.storageUrl||Be.storage_url||Be.url||"#",type:Be.fileType||Be.file_type||Be.type||"file",fileType:Be.fileType||Be.file_type||Be.type||"file",fileSize:Be.fileSize||Be.file_size})):void 0}}):[];k(Ve)}catch{k(Fe=>[...Fe,Le])}b(""),A([])}};p.useEffect(()=>{if(s&&Array.isArray(s))try{const we=s.filter(J=>(J.type||"").toLowerCase()!=="sla_warning").map(J=>{var Fe;if(J.type||J.activityType||J.isSystem)return{id:J.id||`activity-${J.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:J.details||J.action||J.content||"",timestamp:J.timestamp||J.createdAt||J.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const Ve=J.userName||J.user_name||((Fe=J.user)==null?void 0:Fe.name)||"User",Me=J.userRole||J.user_role,Ze=ue(Me),Be=J.userId||J.user_id;return{id:J.noteId||J.note_id||J.id||String(Math.random()),user:{name:Ve,avatar:Ve.split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ze},content:J.message||J.content||"",timestamp:J.createdAt||J.created_at||J.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(J.attachments)?J.attachments.map(qe=>({attachmentId:qe.attachmentId||qe.attachment_id,name:qe.fileName||qe.file_name||qe.name,fileName:qe.fileName||qe.file_name||qe.name,url:qe.storageUrl||qe.storage_url||qe.url||"#",type:qe.fileType||qe.file_type||qe.type||"file",fileType:qe.fileType||qe.file_type||qe.type||"file",fileSize:qe.fileSize||qe.file_size})):void 0,isCurrentUser:Be===N}}}).sort((J,Le)=>new Date(J.timestamp).getTime()-new Date(Le.timestamp).getTime());k(we)}catch(X){console.error("[WorkNoteChat] Error mapping messages:",X)}else(async()=>{try{const X=await Fr(u),we=Array.isArray(X)?X.map(J=>{const Le=J.userName||J.user_name||"User",Fe=J.userRole||J.user_role,Ve=ue(Fe),Me=J.userId||J.user_id;return{id:J.noteId||J.note_id||J.id||String(Math.random()),user:{name:Le,avatar:Le.split(" ").map(Ze=>Ze[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ve},content:J.message||"",timestamp:J.createdAt||J.created_at||new Date().toISOString(),attachments:Array.isArray(J.attachments)?J.attachments.map(Ze=>({attachmentId:Ze.attachmentId||Ze.attachment_id,name:Ze.fileName||Ze.file_name||Ze.name,fileName:Ze.fileName||Ze.file_name||Ze.name,url:Ze.storageUrl||Ze.storage_url||Ze.url||"#",type:Ze.fileType||Ze.file_type||Ze.type||"file",fileType:Ze.fileType||Ze.file_type||Ze.type||"file",fileSize:Ze.fileSize||Ze.file_size})):void 0,isCurrentUser:Me===N}}):[];k(we)}catch(X){console.error("[WorkNoteChat] Error loading work notes:",X)}})()},[s,u,me]);const Te=X=>{const we=L.maxFileSizeMB*1024*1024;if(X.size>we)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${L.maxFileSizeMB}MB. Current size: ${(X.size/(1024*1024)).toFixed(2)}MB`};const J=X.name.toLowerCase(),Le=J.substring(J.lastIndexOf(".")+1);return L.allowedFileTypes.includes(Le)?{valid:!0}:{valid:!1,reason:`File type "${Le}" is not allowed. Allowed types: ${L.allowedFileTypes.join(", ")}`}},Xe=X=>{if(!X.target.files||X.target.files.length===0)return;const we=Array.from(X.target.files),J=[],Le=[];we.forEach(Fe=>{const Ve=Te(Fe);Ve.valid?Le.push(Fe):J.push({fileName:Fe.name,reason:Ve.reason||"Unknown validation error"})}),J.length>0&&ye({open:!0,errors:J}),Le.length>0&&(A(Fe=>[...Fe,...Le]),Le.length{A(we=>we.filter((J,Le)=>Le!==X)),G.current&&(G.current.value="")},_e=X=>{b(we=>we+X),w(!1)},rt=()=>{var X;(X=G.current)==null||X.click()},ut=async X=>{var we,J;try{await zx(u,X);const Le=await vs(u),Fe=Array.isArray(Le==null?void 0:Le.participants)?Le.participants:[];if(Fe.length){const Ve=Fe.map(Me=>{const Ze=Me.participantType||Me.participant_type||"participant",Be=Me.userId||Me.user_id||"",qe=Me.userName||Me.user_name||Me.userEmail||Me.user_email||"User",fs=Me.userEmail||Me.user_email||"",Ht=qe.split(" ").map(at=>at[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:qe,avatar:Ht,role:Ue(Ze),status:"offline",email:fs,lastSeen:void 0,permissions:["read"],userId:Be}});Q(Ve),ce.current&&ce.current.connected&&ce.current.emit("request:online-users",{requestId:u})}$(!1),M({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),U(!0)}catch(Le){throw console.error("Failed to add spectator:",Le),M({success:!1,title:"Failed to Add Spectator",message:((J=(we=Le==null?void 0:Le.response)==null?void 0:we.data)==null?void 0:J.error)||"Failed to add spectator. Please try again."}),U(!0),Le}},nt=async(X,we,J)=>{var Le,Fe;if(d)await d(X,we,J),T(!1);else try{await Vx(u,X,we,J);const Ve=await vs(u),Me=Array.isArray(Ve==null?void 0:Ve.participants)?Ve.participants:[];if(Me.length){const Ze=Me.map(Be=>{const qe=Be.participantType||Be.participant_type||"participant",fs=Be.userId||Be.user_id||"",Ht=Be.userName||Be.user_name||Be.userEmail||Be.user_email||"User",at=Be.userEmail||Be.user_email||"",et=Ht.split(" ").map(yt=>yt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Ht,avatar:et,role:Ue(qe),status:"offline",email:at,lastSeen:void 0,permissions:["read"],userId:fs}});Q(Ze),ce.current&&ce.current.connected&&ce.current.emit("request:online-users",{requestId:u})}T(!1),M({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${J} with ${we}h TAT`}),U(!0)}catch(Ve){throw console.error("Failed to add approver:",Ve),M({success:!1,title:"Failed to Add Approver",message:((Fe=(Le=Ve==null?void 0:Ve.response)==null?void 0:Le.data)==null?void 0:Fe.error)||"Failed to add approver. Please try again."}),U(!0),Ve}},Ps=["😊","😂","đŸ¤Ŗ","😁","😃","😄","😅","😆","😉","😌","😍","đŸĨ°","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","đŸ˜ļ","🙄","😏","😒","🙃","đŸ˜Ŧ","🤐","😴","đŸ˜Ē","đŸ˜ĩ","đŸ¤¯","đŸ¤Ē","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","â˜šī¸","😮","đŸ˜¯","😲","đŸ˜ŗ","đŸĨē","đŸ˜Ļ","😧","😨","😰","đŸ˜Ĩ","đŸ˜ĸ","😭","😱","😖","đŸ˜Ŗ","😞","😓","😩","đŸ˜Ģ","đŸĨą","😤","😡","😠","đŸ¤Ŧ","😈","đŸ‘ŋ","💀","â˜ ī¸","💩","🤡","👹","đŸ‘ē","đŸ‘ģ","👋","🤚","đŸ–ī¸","✋","🖖","👌","🤌","🤏","âœŒī¸","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","â˜ī¸","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","đŸ’Ē","đŸĻž","đŸĻŋ","đŸĻĩ","đŸĻļ","👂","đŸĻģ","👃","🧠","â¤ī¸","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","âŖī¸","💕","💞","💓","💗","💖","💘","💝","💟","â¤ī¸â€đŸ”Ĩ","đŸ’ŧ","📊","📈","📉","đŸ’ģ","âŒ¨ī¸","đŸ–Ĩī¸","đŸ–¨ī¸","đŸ–ąī¸","💾","đŸ’ŋ","📱","â˜Žī¸","📞","📟","📠","📧","âœ‰ī¸","📨","📩","📮","đŸ“Ē","đŸ“Ģ","đŸ“Ŧ","📭","📄","📃","📑","📝","âœī¸","âœ’ī¸","đŸ–Šī¸","đŸ–‹ī¸","📏","📐","📌","📍","đŸ—‚ī¸","📁","📂","✅","âœ”ī¸","â˜‘ī¸","đŸŽ¯","đŸŽ–ī¸","🏆","đŸĨ‡","đŸĨˆ","đŸĨ‰","⭐","🌟","✨","đŸ’Ģ","đŸ”Ĩ","đŸ’Ĩ","⚡","đŸ’¯","🎉","🎊","🎈","âš ī¸","đŸšĢ","❌","⛔","🚷","đŸš¯","🚱","đŸšŗ","🔞","đŸ“ĩ","❗","❓","❕","❔","â€ŧī¸","â‰ī¸","đŸ’ĸ","đŸ’Ŧ","💭","đŸ—¯ī¸","⏰","âąī¸","â˛ī¸","âŗ","⌛","📅","📆","đŸ—“ī¸","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","đŸŽ¯","🎲","🎰","🧩","🔍","🔎","🔑","đŸ—ī¸","🔒","🔓","🔐","🔏","🔔","🔕","đŸ“Ŗ","đŸ“ĸ","💡","đŸ”Ļ","🏮","➕","➖","âœ–ī¸","➗","â™žī¸","â€ŧī¸","â‰ī¸","❓","❔","❕","🔄","🔃","🔂","â–ļī¸","â¸ī¸","â¯ī¸","âšī¸","âēī¸","â­ī¸","âŽī¸","⏊","âĒ","âĢ","âŦ","â—€ī¸","đŸ”ŧ","đŸ”Ŋ","âžĄī¸","âŦ…ī¸","âŦ†ī¸","âŦ‡ī¸","â†—ī¸","â†˜ī¸","â†™ī¸","â†–ī¸","â†•ī¸","â†”ī¸","â†Ēī¸","â†Šī¸","â¤´ī¸"],Xs=X=>{const we=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,J=[];let Le;for(;(Le=we.exec(X))!==null;)if(Le[1]){const Fe=Le.index+Le[0].length,Ve=X.slice(Fe),Me=X[Fe];(Ve.startsWith("@")||!Me||/\s|[.,!?;:]|@/.test(Me))&&J.push(Le[1].trim())}return J},Na=X=>{X.key==="Enter"&&!X.shiftKey&&(X.preventDefault(),Z())},Xa=(X,we)=>{k(J=>J.map(Le=>{if(Le.id===X){const Fe=Le.reactions||[],Ve=Fe.find(Me=>Me.emoji===we);if(Ve)if(Ve.users.includes("You")){if(Ve.users=Ve.users.filter(Me=>Me!=="You"),Ve.users.length===0)return{...Le,reactions:Fe.filter(Me=>Me.emoji!==we)}}else Ve.users.push("You");else Fe.push({emoji:we,users:["You"]});return{...Le,reactions:Fe}}return Le}))};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(As,{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:ae.title}),e.jsx(ne,{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:[oe.slice(0,3).map((X,we)=>e.jsx(Zt,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:"bg-blue-500 text-white text-xs font-semibold",children:X.avatar})},we)),oe.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:["+",oe.length-3]})]})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>_(!S),className:"lg:hidden",children:e.jsx(cs,{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(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Oe,{placeholder:"Search messages...",value:f,onChange:X=>y(X.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:[Ce.map(X=>{const we=X.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${X.isSystem?"justify-center":we?"justify-end":""}`,children:[!X.isSystem&&!we&&e.jsx(Zt,{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(Jt,{className:`text-white font-semibold text-xs sm:text-sm ${X.user.role==="Initiator"?"bg-green-600":X.user.role==="Current User"?"bg-blue-500":X.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:X.user.avatar})}),e.jsx("div",{className:`${we?"max-w-[70%]":"flex-1"} min-w-0 ${X.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:X.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(kt,{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:X.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:Qt(X.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${we?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[X.user.name," ",we&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(ne,{variant:"outline",className:"text-xs flex-shrink-0",children:X.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(st,{className:"w-3 h-3"}),Qt(X.timestamp)]}),X.isHighPriority&&e.jsxs(ne,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(o0,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${we?"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:ZS(X.content)}}),X.attachments&&X.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:X.attachments.map((J,Le)=>{const Fe=J.fileSize||J.file_size,Ve=J.fileName||J.file_name||J.name,Me=J.fileType||J.file_type||J.type||"",Ze=J.attachmentId||J.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(wu,{type:Me})}),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:Ve}),Fe&&e.jsx("p",{className:"text-xs text-gray-500",children:JS(Fe)})]}),Ze&&(()=>{const Be=(Me||"").toLowerCase();return Be.includes("image")||Be.includes("pdf")||Be.includes("jpg")||Be.includes("jpeg")||Be.includes("png")||Be.includes("gif")})()&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-purple-100 hover:text-purple-600",onClick:Be=>{Be.preventDefault(),Be.stopPropagation();const qe=eN(Ze);O({fileName:Ve,fileType:Me,fileUrl:qe,fileSize:Fe,attachmentId:Ze})},title:"Preview file",children:e.jsx(ht,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-blue-100 hover:text-blue-600",onClick:async Be=>{if(Be.preventDefault(),Be.stopPropagation(),!Ze){K.error("Cannot download: Attachment ID missing");return}try{await Jd(Ze)}catch{K.error("Failed to download file")}},title:"Download file",children:e.jsx(Ct,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Le)})})}),X.reactions&&X.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:[X.reactions.map((J,Le)=>e.jsxs("button",{onClick:()=>Xa(X.id,J.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${J.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:J.emoji}),e.jsx("span",{className:"text-xs font-medium",children:J.users.length})]},Le)),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>w(!v),children:e.jsx(gs,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!X.isSystem&&we&&e.jsx(Zt,{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(Jt,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:X.user.avatar})})]},X.id)}),e.jsx("div",{ref:W})]})}),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:G,onChange:Xe,className:"hidden",multiple:!0,accept:L.allowedFileTypes.map(X=>`.${X}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((X,we)=>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(wu,{type:X.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:X.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(X.size/1024).toFixed(1)," KB"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>pe(we),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(ft,{className:"h-3 w-3 text-red-600"})})]},we))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const X=g.lastIndexOf("@"),we=X>=0;if(!we)return null;const J=g.slice(X+1),Le=J.trim(),Fe=J.endsWith(" "),Ve=Le.length>0,Me=Le.includes(" ")&&!Fe,Ze=Fe&&Ve;if(!(we&&J.length<=20&&!Me&&!Ze))return null;const qe=Le.toLowerCase(),fs=me.filter(Ht=>Ht.userId===N?!1:qe?Ht.name.toLowerCase().includes(qe):!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:fs.length>0?fs.map((Ht,at)=>e.jsxs("button",{type:"button",onClick:et=>{et.preventDefault(),et.stopPropagation();const yt=g.lastIndexOf("@"),rs=g.slice(0,yt);b(rs+"@"+Ht.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(Zt,{className:"h-10 w-10",children:e.jsx(Jt,{className:`text-white text-sm font-semibold ${Ht.role==="Initiator"?"bg-green-600":Ht.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:Ht.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:Ht.name}),e.jsx("p",{className:"text-xs text-gray-600",children:Ht.role})]})]},at)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:qe?`No participants found matching "${qe}"`:"No other participants available"})})]})})(),e.jsx(Ds,{placeholder:"Type your message... Use @username to mention someone",value:g,onChange:X=>b(X.target.value),onKeyPress:Na,className:"min-h-[50px] sm:min-h-[60px] resize-none border-gray-200 focus:ring-blue-500 focus:border-blue-500 w-full text-sm",rows:2}),v&&e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border border-gray-200 rounded-lg shadow-xl p-3 z-50 w-full sm:w-96 max-h-80 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 sticky top-0 bg-white pb-2 border-b",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-700",children:"Pick an emoji"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>w(!1),className:"h-6 w-6 p-0",children:e.jsx(ft,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:Ps.map((X,we)=>e.jsx("button",{onClick:()=>_e(X),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:X,children:X},we))})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-shrink-0",children:[e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:rt,title:"Attach file",children:e.jsx(vi,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>w(!v),title:"Add emoji",children:e.jsx(c0,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>b(X=>X+"@"),title:"Mention someone",children:e.jsx(Ci,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto flex-shrink-0",children:[e.jsxs("span",{className:"text-xs text-gray-500 hidden md:inline whitespace-nowrap",children:[g.length,"/2000"]}),e.jsxs(E,{onClick:Z,disabled:!g.trim()&&D.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(ax,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),S&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>_(!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 ${S?"fixed right-0 top-0 bottom-0 z-50 shadow-xl":"hidden lg:flex"} @@ -44,7 +44,7 @@ Activity has been automatically created for claim ${n}. All stakeholders have been notified. This is an automated message.`,h=o||m;return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-2xl lg:max-w-[1000px] max-w-2xl",children:[e.jsx(gt,{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(Ra,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(mt,{className:"text-lg leading-none font-semibold",children:"Email Notification Template"}),e.jsxs(Dt,{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(Vt,{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(Ra,{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(Si,{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:h})}),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(ot,{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(ne,{className:"bg-blue-50 text-blue-700 border-blue-200",children:["Step ",a]}),e.jsx(ne,{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(E,{variant:"outline",onClick:s,className:"h-9",children:[e.jsx(ft,{className:"w-4 h-4 mr-2"}),"Close"]})})]})})}function MA({isOpen:t,onClose:s,onApprove:a,onReject:r,onRequestRevision:n,proposalData:i,dealerName:l="Dealer",activityName:o="Activity",requestId:c,request:d,previousProposalData:m}){const[h,x]=p.useState(""),[u,g]=p.useState(!1),[b,f]=p.useState(null),[y,v]=p.useState(!1),w=(d==null?void 0:d.internalOrder)||(d==null?void 0:d.internal_order),k=((w==null?void 0:w.ioBlockedAmount)||(w==null?void 0:w.io_blocked_amount)||0)>0,[S,_]=p.useState(null),D=p.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const T=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(T)?T.reduce((j,U)=>{const I=typeof U=="object"&&U.amount||0;return j+(Number(I)||0)},0):0},[i]),A=T=>{if(!T)return"—";try{return new Date(T).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return T}},N=T=>{if(!T.name)return!1;const j=T.name.toLowerCase();return j.endsWith(".pdf")||j.endsWith(".jpg")||j.endsWith(".jpeg")||j.endsWith(".png")||j.endsWith(".gif")||j.endsWith(".webp")},P=T=>{let j=T.url||T.storageUrl||"";const U=T.id||T.documentId||"";if(!U&&!j){K.error("Document preview not available");return}if(j&&!j.startsWith("http")&&!j.startsWith("blob:")){const I="https://reflow-uat.royalenfield.com",M=I.endsWith("/")?I.slice(0,-1):I,W=j.startsWith("/")?j:`/${j}`;j=`${M}${W}`}_({name:T.name||"Document",url:j||(U?Hr(U):""),type:(T.name||"").toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg",id:U})};p.useEffect(()=>()=>{S!=null&&S.url&&S.url.startsWith("blob:")&&window.URL.revokeObjectURL(S.url)},[S]);const R=async()=>{if(!h.trim()){K.error("Please provide approval comments");return}try{g(!0),f("approve"),await a(h),$(),s()}catch(T){console.error("Failed to approve proposal:",T),K.error("Failed to approve proposal. Please try again.")}finally{g(!1),f(null)}},O=async()=>{if(!h.trim()){K.error("Please provide rejection reason");return}try{g(!0),f("reject"),await r(h),$(),s()}catch(T){console.error("Failed to reject proposal:",T),K.error("Failed to reject proposal. Please try again.")}finally{g(!1),f(null)}},F=async()=>{if(!h.trim()){K.error("Please provide reasons for requesting a revision");return}if(!n){K.error("Revision feature is not available");return}try{g(!0),f("revision"),await n(h),$(),s()}catch(T){console.error("Failed to request revision:",T),K.error("Failed to request revision. Please try again.")}finally{g(!1),f(null)}},$=()=>{x(""),f(null)},V=()=>{u||($(),s())};return t?e.jsxs(pt,{open:t,onOpenChange:V,children:[e.jsxs(dt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(gt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(mt,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(De,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600"}),"Requestor Evaluation & Confirmation"]}),e.jsx(Dt,{className:"text-xs lg:text-sm",children:"Step 2: Review dealer proposal and make a decision"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",l]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",o]})]}),e.jsxs("div",{className:"mt-1 text-amber-600 font-medium",children:["Decision: ",e.jsx("strong",{children:"Confirms?"})," (YES → Continue to Dept Lead / NO → Request is cancelled)"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden min-h-0 py-3 lg:py-4 px-6",children:[m&&e.jsx("div",{className:"mb-6",children:e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg overflow-hidden cursor-pointer hover:bg-amber-100/50 transition-colors",onClick:()=>v(!y),children:[e.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4 text-amber-700"}),e.jsx("span",{className:"text-sm font-semibold text-amber-900",children:"Reference: Previous Proposal Details (last revision)"}),e.jsxs(ne,{variant:"secondary",className:"bg-amber-200 text-amber-800 text-[10px]",children:["₹",Number(m.totalEstimatedBudget||m.totalBudget||0).toLocaleString("en-IN")]})]}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:y?e.jsx(ho,{className:"w-4 h-4"}):e.jsx(gs,{className:"w-4 h-4"})})]}),y&&e.jsxs("div",{className:"px-4 pb-4 border-t border-amber-200 space-y-4 bg-white/50",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 text-xs mt-3",children:[m.expectedCompletionDate&&e.jsxs("div",{className:"flex items-center gap-1.5 text-gray-700",children:[e.jsx(ot,{className:"w-3.5 h-3.5 text-gray-500"}),e.jsx("span",{className:"font-medium",children:"Expected Completion:"}),e.jsx("span",{children:new Date(m.expectedCompletionDate).toLocaleDateString("en-IN")})]}),m.documentUrl&&e.jsx("div",{className:"flex items-center gap-1.5",children:N({name:m.documentUrl})?e.jsxs(e.Fragment,{children:[e.jsx(ht,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:m.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"View Previous Document"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("a",{href:m.documentUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline font-medium flex items-center gap-1",children:"Download Previous Document"})]})})]}),(m.costItems||m.costBreakup)&&(m.costItems||m.costBreakup).length>0&&e.jsxs("div",{className:"w-full pt-2 border-t border-amber-200/50",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-2 flex items-center gap-1",children:[e.jsx(ln,{className:"w-3 h-3"}),"Previous Cost Breakdown"]}),e.jsx("div",{className:"border rounded-md overflow-hidden text-[10px]",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-600",children:e.jsxs("tr",{children:[e.jsx("th",{className:"p-2 font-medium",children:"Description"}),e.jsx("th",{className:"p-2 font-medium text-right",children:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y",children:[(m.costItems||m.costBreakup).map((T,j)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:T.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(T.amount).toLocaleString("en-IN")]})]},j)),e.jsxs("tr",{className:"bg-gray-50 font-bold border-t",children:[e.jsx("td",{className:"p-2 text-gray-900",children:"Total"}),e.jsxs("td",{className:"p-2 text-right text-gray-900",children:["₹",Number(m.totalEstimatedBudget||m.totalBudget||0).toLocaleString("en-IN")]})]})]})]})})]}),m.otherDocuments&&m.otherDocuments.length>0&&e.jsxs("div",{className:"w-full pt-2 border-t border-amber-200/50",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-1.5 flex items-center gap-1",children:[e.jsx(Re,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:m.otherDocuments.map((T,j)=>e.jsx(Or,{document:{documentId:T.documentId||T.id||"",name:T.originalFileName||T.fileName||T.name||"Supporting Document",fileType:(T.originalFileName||T.fileName||T.name||"").split(".").pop()||"file",uploadedAt:T.uploadedAt||new Date().toISOString()},onPreview:N({name:T.originalFileName||T.fileName||T.name||""})?()=>P(T):void 0,onDownload:async U=>{if(U)await ps(U);else{let I=T.storageUrl||T.documentUrl;if(I&&!I.startsWith("http")){const M="https://reflow-uat.royalenfield.com",W=M.endsWith("/")?M.slice(0,-1):M,G=I.startsWith("/")?I:`/${I}`;I=`${W}${G}`}I&&window.open(I,"_blank")}}},j))})]}),(m.comments||m.dealerComments)&&e.jsxs("div",{className:"w-full pt-2 border-t border-amber-200/50",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-1 flex items-center gap-1",children:[e.jsx(As,{className:"w-3 h-3"}),"Previous Comments"]}),e.jsxs("div",{className:"text-[10px] text-gray-600 bg-white p-2 border border-gray-100 rounded italic",children:['"',m.comments||m.dealerComments,'"']})]})]})]})}),e.jsxs("div",{className:"space-y-4 lg:space-y-0 lg:grid lg:grid-cols-2 lg:gap-6 lg:items-start lg:content-start",children:[e.jsxs("div",{className:"space-y-4 lg:space-y-4 flex flex-col",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4 text-blue-600"}),"Proposal Document"]})}),i!=null&&i.proposalDocument?e.jsxs("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 lg:gap-3 min-w-0 flex-1",children:[e.jsx(Re,{className:"w-5 h-5 lg:w-6 lg:h-6 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-xs lg:text-sm text-gray-900 truncate",title:i.proposalDocument.name,children:i.proposalDocument.name}),(i==null?void 0:i.submittedAt)&&e.jsxs("p",{className:"text-xs text-gray-500 truncate",children:["Submitted on ",A(i.submittedAt)]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:i.proposalDocument.id&&e.jsxs(e.Fragment,{children:[N(i.proposalDocument)&&e.jsx("button",{type:"button",onClick:()=>P(i.proposalDocument),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(ht,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var T;try{(T=i.proposalDocument)!=null&&T.id&&await ps(i.proposalDocument.id)}catch(j){console.error("Failed to download document:",j),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Ct,{className:"w-5 h-5 text-gray-600"})})]})})]}):e.jsx("p",{className:"text-xs text-gray-500 italic",children:"No proposal document available"})]}),(i==null?void 0:i.otherDocuments)&&i.otherDocuments.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4 text-gray-600"}),"Other Supporting Documents"]}),e.jsxs(ne,{variant:"secondary",className:"text-xs",children:[i.otherDocuments.length," file(s)"]})]}),e.jsx("div",{className:"space-y-2 max-h-[150px] lg:max-h-[140px] overflow-y-auto",children:i.otherDocuments.map((T,j)=>e.jsxs("div",{className:"border rounded-lg p-2 lg:p-3 bg-gray-50 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 lg:gap-3 min-w-0 flex-1",children:[e.jsx(Re,{className:"w-4 h-4 lg:w-5 lg:h-5 text-gray-600 flex-shrink-0"}),e.jsx("p",{className:"text-xs lg:text-sm font-medium text-gray-900 truncate",title:T.name,children:T.name})]}),T.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[N(T)&&e.jsx("button",{type:"button",onClick:()=>P(T),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(ht,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{T.id&&await ps(T.id)}catch(U){console.error("Failed to download document:",U),K.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Ct,{className:"w-5 h-5 text-gray-600"})})]})]},j))})]})]}),e.jsxs("div",{className:"space-y-4 lg:space-y-4 flex flex-col",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(ln,{className:"w-4 h-4 text-green-600"}),"Cost Breakup"]})}),(()=>{const T=i!=null&&i.costBreakup?Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[]:[];return T&&Array.isArray(T)&&T.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden max-h-[200px] lg:max-h-[180px] overflow-y-auto",children:[e.jsx("div",{className:"bg-gray-50 px-3 lg:px-4 py-2 border-b sticky top-0",children:e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-xs lg: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:T.map((j,U)=>e.jsxs("div",{className:"px-3 lg:px-4 py-2 lg:py-3 grid grid-cols-2 gap-4",children:[e.jsx("div",{className:"text-xs lg:text-sm text-gray-700",children:(j==null?void 0:j.description)||"N/A"}),e.jsxs("div",{className:"text-xs lg:text-sm font-semibold text-gray-900 text-right",children:["₹",(Number(j==null?void 0:j.amount)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]},(j==null?void 0:j.id)||(j==null?void 0:j.description)||U))})]}),e.jsx("div",{className:"border-2 border-[--re-green] rounded-lg p-2.5 lg:p-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"w-4 h-4 text-[--re-green]"}),e.jsx("span",{className:"font-semibold text-xs lg:text-sm text-gray-700",children:"Total Estimated Budget"})]}),e.jsxs("div",{className:"text-lg lg:text-xl font-bold text-[--re-green]",children:["₹",D.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}):e.jsx("p",{className:"text-xs text-gray-500 italic",children:"No cost breakdown available"})})()]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(ot,{className:"w-4 h-4 text-purple-600"}),"Expected Completion Date"]})}),e.jsx("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50",children:e.jsx("p",{className:"text-sm lg:text-base font-semibold text-gray-900",children:i!=null&&i.expectedCompletionDate?A(i.expectedCompletionDate):"Not specified"})})]})]}),e.jsx("div",{className:"space-y-2 border-t pt-3 lg:pt-3 lg:col-span-2 mt-2",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 lg:gap-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("h3",{className:"font-semibold text-sm lg:text-base flex items-center gap-2",children:[e.jsx(As,{className:"w-4 h-4 text-blue-600"}),"Dealer Comments"]})}),e.jsx("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50 max-h-[150px] lg:max-h-[140px] overflow-y-auto",children:e.jsx("p",{className:"text-xs text-gray-700 whitespace-pre-wrap",children:(i==null?void 0:i.dealerComments)||"No comments provided"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"font-semibold text-sm lg:text-base",children:"Your Decision & Comments"}),e.jsx(Ds,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:h,onChange:T=>x(T.target.value),className:"min-h-[150px] lg:min-h-[140px] text-xs lg:text-sm w-full"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[h.length," characters"]})]})]})}),!h.trim()&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-2 flex items-start gap-2 lg:col-span-2",children:[e.jsx(wt,{className:"w-3.5 h-3.5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-amber-800",children:"Please provide comments before making a decision. Comments are required and will be visible to all participants."})]})]})]}),e.jsxs(Tt,{className:"flex flex-col gap-2 sm:flex-row sm:justify-end px-6 pb-6 pt-3 lg:pt-4 flex-shrink-0 border-t bg-gray-50",children:[e.jsx(E,{variant:"outline",onClick:V,disabled:u,className:"border-2 w-full sm:w-auto",children:"Cancel"}),e.jsxs("div",{className:"flex flex-col gap-2 w-full sm:w-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(E,{onClick:F,disabled:!h.trim()||u,variant:"secondary",className:"bg-amber-100 hover:bg-amber-200 text-amber-900 border border-amber-200 w-full sm:w-auto",children:u&&b==="revision"?"Requesting...":e.jsxs(e.Fragment,{children:[e.jsx(As,{className:"w-4 h-4 mr-2"}),"Request Revised Quotation"]})}),e.jsx(E,{onClick:O,disabled:!h.trim()||u,variant:"destructive",className:"bg-red-600 hover:bg-red-700 w-full sm:w-auto",children:u&&b==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),"Reject (Cancel Request)"]})}),e.jsx(E,{onClick:R,disabled:!h.trim()||!k||u,className:"bg-green-600 hover:bg-green-700 text-white disabled:opacity-50 disabled:cursor-not-allowed w-full sm:w-auto",title:k?"":"Please block IO budget before approving",children:u&&b==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Approve (Continue to Dept Lead)"]})})]}),!k&&e.jsx("p",{className:"text-xs text-red-600 text-center sm:text-left",children:"Please block IO budget in the IO Tab before approving"})]})]})]}),S&&e.jsx(jr,{fileName:S.name,fileType:S.type||"",fileUrl:S.url,fileSize:S.size,attachmentId:S.id,onDownload:ps,open:!!S,onClose:()=>_(null)})]}):null}function $A({isOpen:t,onClose:s,snapshot:a,type:r,title:n}){const[i,l]=p.useState(null);if(!a)return null;const o=r==="PROPOSAL",c=u=>Number(u||0).toLocaleString("en-IN",{maximumFractionDigits:2,style:"currency",currency:"INR"}),d=u=>{if(!u)return null;try{return new Date(u).toLocaleDateString("en-IN",{day:"numeric",month:"short",year:"numeric"})}catch{return u}},m=u=>{if(!u)return!1;const g=u.toLowerCase();return g.endsWith(".pdf")||!!g.match(/\.(jpg|jpeg|png|gif|webp)$/i)},h=u=>{var b;const g=(b=(u||"").split(".").pop())==null?void 0:b.toLowerCase();return g==="pdf"?"pdf":["jpg","jpeg","png","gif","webp"].includes(g||"")?"image":"file"},x=u=>{const g=u.fileName||u.originalFileName||(o?"Proposal Document":"Completion Document"),b=u.documentId||"",f=g.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let y="";if(b)y=Hr(b);else if(y=u.storageUrl||u.documentUrl||"",y&&!y.startsWith("http")){const v="https://reflow-uat.royalenfield.com",w=v.endsWith("/")?v.slice(0,-1):v,C=y.startsWith("/")?y:`/${y}`;y=`${w}${C}`}l({fileName:g,fileType:f,documentId:b,fileUrl:y,fileSize:u.sizeBytes})};return e.jsxs(e.Fragment,{children:[e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"max-w-2xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden",children:[e.jsxs(gt,{className:"px-6 py-4 border-b",children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[o?e.jsx(Re,{className:"w-5 h-5 text-blue-600"}):e.jsx(Gt,{className:"w-5 h-5 text-green-600"}),n||(o?"Proposal Snapshot Details":"Completion Snapshot Details")]}),e.jsxs(Dt,{children:["View detailed snapshot of the ",o?"proposal":"completion request"," at this version."]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 px-6 py-4",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsx("p",{className:"text-xs text-gray-500 font-medium mb-1",children:o?"Total Budget":"Total Expenses"}),e.jsx("p",{className:`text-lg font-bold ${o?"text-blue-700":"text-green-700"}`,children:c(a.totalBudget||a.totalExpenses)})]}),o&&a.expectedCompletionDate&&e.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg border border-gray-100",children:[e.jsxs("p",{className:"text-xs text-gray-500 font-medium mb-1 flex items-center gap-1",children:[e.jsx(ot,{className:"w-3 h-3"}),"Expected Completion"]}),e.jsx("p",{className:"text-sm font-semibold text-gray-700",children:d(a.expectedCompletionDate)})]})]}),a.documentUrl&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1",children:"Primary Document"}),e.jsx(Or,{document:{documentId:"",name:o?"Proposal Document":"Completion Document",fileType:h(a.documentUrl),uploadedAt:new Date().toISOString()},onPreview:m(a.documentUrl)?()=>x({fileName:o?"Proposal Document":"Completion Document",documentUrl:a.documentUrl}):void 0,onDownload:async()=>{let u=a.documentUrl;if(!u.startsWith("http")){const g="https://reflow-uat.royalenfield.com",b=g.endsWith("/")?g.slice(0,-1):g,f=u.startsWith("/")?u:`/${u}`;u=`${b}${f}`}window.open(u,"_blank")}})]}),a.otherDocuments&&a.otherDocuments.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1 flex items-center justify-between",children:[e.jsx("span",{children:"Supporting Documents"}),e.jsxs(ne,{variant:"secondary",className:"text-[10px] h-5",children:[a.otherDocuments.length," Files"]})]}),e.jsx("div",{className:"space-y-2",children:a.otherDocuments.map((u,g)=>e.jsx(Or,{document:{documentId:u.documentId||"",name:u.originalFileName||u.fileName||"Supporting Document",fileType:h(u.originalFileName||u.fileName||""),uploadedAt:u.uploadedAt||new Date().toISOString()},onPreview:m(u.originalFileName||u.fileName||"")?()=>x(u):void 0,onDownload:u.documentId?ps:async()=>{let b=u.storageUrl||u.documentUrl;if(b&&!b.startsWith("http")){const f="https://reflow-uat.royalenfield.com",y=f.endsWith("/")?f.slice(0,-1):f,v=b.startsWith("/")?b:`/${b}`;b=`${y}${v}`}b&&window.open(b,"_blank")}},g))})]}),(a.costItems||a.expenses)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1",children:o?"Cost Breakdown":"Expenses Breakdown"}),e.jsx("div",{className:"border rounded-md overflow-hidden text-sm",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-600 text-xs uppercase",children:e.jsxs("tr",{children:[e.jsx("th",{className:"p-3 font-medium",children:"Description"}),e.jsx("th",{className:"p-3 font-medium text-right",children:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-100",children:[(a.costItems||a.expenses).length>0?(a.costItems||a.expenses).map((u,g)=>e.jsxs("tr",{className:"bg-white hover:bg-gray-50/50",children:[e.jsx("td",{className:"p-3 text-gray-800",children:u.description}),e.jsx("td",{className:"p-3 text-right text-gray-900 font-medium tabular-nums",children:c(u.amount)})]},g)):e.jsx("tr",{children:e.jsx("td",{colSpan:2,className:"p-4 text-center text-gray-500 italic text-xs",children:"No breakdown items available"})}),e.jsxs("tr",{className:"bg-gray-50/80 font-semibold text-gray-900 border-t-2 border-gray-100",children:[e.jsx("td",{className:"p-3",children:"Total"}),e.jsx("td",{className:"p-3 text-right tabular-nums",children:c(a.totalBudget||a.totalExpenses)})]})]})]})})]}),a.comments&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1 flex items-center gap-1",children:[e.jsx(Ju,{className:"w-4 h-4"}),"Comments"]}),e.jsx("div",{className:"bg-gray-50 rounded-lg p-3 text-sm text-gray-700 italic border border-gray-100",children:a.comments})]})]})}),e.jsx("div",{className:"px-6 py-4 border-t bg-gray-50 flex justify-end",children:e.jsx(E,{onClick:s,children:"Close"})})]})}),i&&e.jsx(jr,{fileName:i.fileName,fileType:i.fileType,fileUrl:i.fileUrl,fileSize:i.fileSize,attachmentId:i.documentId,onDownload:ps,open:!!i,onClose:()=>l(null)})]})}async function OA(t){var s;try{const a=await je.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 UA(t){var s;try{const a=await je.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 BA(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 je.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 VA(t,s){var a;try{const r=new FormData;r.append("activityCompletionDate",s.activityCompletionDate),s.numberOfParticipants!==void 0&&r.append("numberOfParticipants",s.numberOfParticipants.toString()),s.closedExpenses&&r.append("closedExpenses",JSON.stringify(s.closedExpenses)),s.totalClosedExpenses!==void 0&&r.append("totalClosedExpenses",s.totalClosedExpenses.toString()),s.completionDescription&&r.append("completionDescription",s.completionDescription),s.completionDocuments&&s.completionDocuments.forEach(i=>{r.append("completionDocuments",i)}),s.activityPhotos&&s.activityPhotos.forEach(i=>{r.append("activityPhotos",i)});const n=await je.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 zA(t,s){var a;try{const r=await je.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 Zp(t,s){var a;try{const r={ioNumber:s.ioNumber,ioRemark:s.ioRemark||""};s.ioAvailableBalance!==void 0&&(r.availableBalance=s.ioAvailableBalance),s.ioBlockedAmount!==void 0&&(r.blockedAmount=s.ioBlockedAmount),s.ioRemainingBalance!==void 0&&(r.remainingBalance=s.ioRemainingBalance);const n=await je.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 HA(t,s){var a;try{const r=await je.put(`/dealer-claims/${t}/e-invoice`,s);return((a=r.data)==null?void 0:a.data)||r.data}catch(r){throw console.error("[DealerClaimAPI] Error updating e-invoice:",r),r}}async function WA(t){var s;try{const a=await je.post(`/dealer-claims/${t}/credit-note/send`);return((s=a.data)==null?void 0:s.data)||a.data}catch(a){throw console.error("[DealerClaimAPI] Error sending credit note to dealer:",a),a}}async function GA(t,s,a){var r;try{const n={};t&&(n.dateRange=t),s&&(n.startDate=s),a&&(n.endDate=a);const i=await je.get("/dealer-claims/dashboard",{params:n});return((r=i.data)==null?void 0:r.data)||i.data}catch(n){throw console.error("[DealerClaimAPI] Error fetching dealer dashboard:",n),n}}const Cr=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}}},YA=t=>{switch(t){case"approved":return e.jsx(De,{className:"w-5 h-5 text-green-600"});case"pending":return e.jsx(st,{className:"w-5 h-5 text-blue-600"});case"rejected":return e.jsx(De,{className:"w-5 h-5 text-red-600"});default:return e.jsx(st,{className:"w-5 h-5 text-gray-400"})}},KA=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"}},XA=(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",ZA=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 JA({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n,documentPolicy:i}){var pa,Fa,wa,St,Ca,Za,Ja,Qa,qa,er,tr,_a,ga,La,It,ns,Os,sr,ar,oa,vt,is,Is,Zs,Nr,ca,Ma,Kr,Xr,Zr,yc,vc,jc,Nc,wc,Cc,Sc,Ac,Tc,kc,Rc,Dc,Pc,Ic,Ec,Fc,_c,Lc,Mc,$c,Oc,Uc,Bc,Vc,zc,Hc,Wc,Gc,Yc,Kc,Xc,Zc,Jc,Qc,qc,ed,td,sd,ad,rd,nd,id,ld,od,cd,dd,md,ud,xd,hd,pd,gd,fd,bd,yd,vd,jd,Nd,wd,Cd,Sd,Ad;const[l,o]=p.useState(!1),[c,d]=p.useState(!1),[m,h]=p.useState(!1),[x,u]=p.useState(!1),[g,b]=p.useState(!1),[f,y]=p.useState(!1),[v,w]=p.useState(!1),[C,k]=p.useState(null),[S,_]=p.useState(!1),[D,A]=p.useState(null),[N,P]=p.useState([]),[R,O]=p.useState(!1),[F,$]=p.useState(new Set),[V,T]=p.useState(null),[j,U]=p.useState([]),[I,M]=p.useState(0);p.useEffect(()=>{(async()=>{if(t!=null&&t.id||t!=null&&t.requestId){const Ie=t.id||t.requestId;try{const xe=await vs(Ie),ie=(xe==null?void 0:xe.approvalLevels)||(xe==null?void 0:xe.approvals)||[];if(ie&&ie.length>0){const he=ie.map(de=>{var Se;return{step:de.levelNumber||de.level_number||0,levelNumber:de.levelNumber||de.level_number||0,levelName:de.levelName||de.level_name,approver:de.approverName||de.approver_name||"",approverEmail:(de.approverEmail||de.approver_email||"").toLowerCase(),status:((Se=de.status)==null?void 0:Se.toLowerCase())||"waiting",tatHours:de.tatHours||de.tat_hours||24,elapsedHours:de.elapsedHours||de.elapsed_hours,approvedAt:de.actionDate||de.action_date,comment:de.comments||de.comment,levelId:de.levelId||de.level_id}}).sort((de,Se)=>(de.levelNumber||0)-(Se.levelNumber||0));U(de=>de.length!==he.length||de.some((Ne,ve)=>{const bt=he[ve];return!bt||Ne.levelNumber!==bt.levelNumber||Ne.levelName!==bt.levelName||Ne.approverEmail!==bt.approverEmail||Ne.status!==bt.status})?he:de)}else U([])}catch(xe){console.warn("Failed to load approval flows from API:",xe),t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&U(t.approvalFlow)}}else t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&U(t.approvalFlow)})()},[t==null?void 0:t.id,t==null?void 0:t.requestId,t==null?void 0:t.totalLevels,I]),p.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const B=t.id||t.requestId;(async()=>{try{const xe=await vs(B),ie=(xe==null?void 0:xe.approvalLevels)||(xe==null?void 0:xe.approvals)||[];if(ie&&ie.length>0){const he=ie.map(de=>{var Se;return{step:de.levelNumber||de.level_number||0,levelNumber:de.levelNumber||de.level_number||0,levelName:de.levelName||de.level_name,approver:de.approverName||de.approver_name||"",approverEmail:(de.approverEmail||de.approver_email||"").toLowerCase(),status:((Se=de.status)==null?void 0:Se.toLowerCase())||"waiting",tatHours:de.tatHours||de.tat_hours||24,elapsedHours:de.elapsedHours||de.elapsed_hours,approvedAt:de.actionDate||de.action_date,comment:de.comments||de.comment,levelId:de.levelId||de.level_id}}).sort((de,Se)=>(de.levelNumber||0)-(Se.levelNumber||0));U(he)}}catch(xe){console.warn("Failed to load approval flows from API:",xe)}})()}},[t==null?void 0:t.currentStep,t==null?void 0:t.totalLevels]);const W=async()=>{M(B=>B+1),await new Promise(B=>setTimeout(B,500)),n==null||n(),G()},G=async()=>{if(t!=null&&t.id||t!=null&&t.requestId)try{const Ie=[...await rN(t.id||t.requestId)||[]].sort((xe,ie)=>new Date(ie.createdAt).getTime()-new Date(xe.createdAt).getTime());P(Ie)}catch(B){console.warn("Failed to load version history:",B)}};p.useEffect(()=>{G()},[t==null?void 0:t.id,t==null?void 0:t.requestId,I]);const ce=(B,Ie,xe)=>{var de;const ie=((t==null?void 0:t.totalLevels)||0)>5||(((de=t==null?void 0:t.approvalLevels)==null?void 0:de.length)||0)>5;if(Ie&&Ie.trim()&&(Ie.toLowerCase().includes("additional approver")||!/^step\s+\d+$/i.test(Ie)))return Ie;const he=ie?{1:"Dealer - Proposal Submission",2:"Requestor Evaluation & Confirmation",3:"Department Lead Approval",4:"Activity Creation",5:"Dealer - Completion Documents",6:"Requestor - Claim Approval",7:"E-Invoice Generation",8:"Credit Note from SAP"}:{1:"Dealer - Proposal Submission",2:"Requestor Evaluation & Confirmation",3:"Department Lead Approval",4:"Dealer - Completion Documents",5:"Requestor - Claim Approval",6:"E-Invoice Generation",7:"Credit Note from SAP"};return he[B]?he[B]:xe&&xe!=="Unknown"&&xe!=="System"?`Additional Approver - ${xe}`:`Additional Approver - Step ${B}`},te=(B,Ie,xe)=>{var Se;if(Ie&&Ie.toLowerCase().includes("additional approver"))return xe&&xe!=="Unknown"&&xe!=="System"?`${xe} will review and approve this request as an additional approver.`:"Additional approver will review and approve this request.";const he=((t==null?void 0:t.totalLevels)||0)>5||(((Se=t==null?void 0:t.approvalLevels)==null?void 0:Se.length)||0)>5;if(Ie&&Ie.trim()){const Ne=Ie.toLowerCase();if(Ne.includes("dealer")&&Ne.includes("proposal"))return"Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests";if(Ne.includes("requestor")&&(Ne.includes("evaluation")||Ne.includes("confirmation")))return"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)";if(Ne.includes("department lead"))return"Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)";if(Ne.includes("activity creation"))return"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.";if(Ne.includes("dealer")&&(Ne.includes("completion")||Ne.includes("documents")))return"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description";if(Ne.includes("requestor")&&(Ne.includes("claim")||Ne.includes("approval")))return"Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.";if(Ne.includes("e-invoice")||Ne.includes("invoice generation")||Ne.includes("dms"))return"E-Invoice will be generated upon settlement initiation.";if(Ne.includes("credit note")||Ne.includes("sap"))return"Got credit note from SAP. Review and send to dealer to complete the claim management process."}const de=he?{1:"Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests",2:"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)",3:"Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)",4:"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.",5:"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description",6:"Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.",7:"E-Invoice will be generated upon settlement initiation.",8:"Got credit note from SAP. Review and send to dealer to complete the claim management process."}:{1:"Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests",2:"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)",3:"Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)",4:"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description",5:"Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.",6:"E-Invoice will be generated upon settlement initiation.",7:"Got credit note from SAP. Review and send to dealer to complete the claim management process."};return de[B]?de[B]:xe&&xe!=="Unknown"&&xe!=="System"?`${xe} will review and approve this request.`:`Step ${B} approval required.`},L=B=>{if(!N||N.length===0||!B)return{current:null,previous:null};const ie=[...N.filter(Se=>{var Ne;return!!(Se.levelName&&Se.levelName.trim()===B.trim()||(Ne=Se.snapshotData)!=null&&Ne.levelName&&Se.snapshotData.levelName.trim()===B.trim())})].sort((Se,Ne)=>{if(Ne.version!==Se.version)return Ne.version-Se.version;const ve=Se.snapshotType==="APPROVE"?1:Se.snapshotType==="PROPOSAL"||Se.snapshotType==="COMPLETION"?2:3,bt=Ne.snapshotType==="APPROVE"?1:Ne.snapshotType==="PROPOSAL"||Ne.snapshotType==="COMPLETION"?2:3;return ve-bt}).filter((Se,Ne,ve)=>Se.snapshotType==="WORKFLOW"?!ve.some(xt=>xt.snapshotType==="APPROVE"&&xt.levelName===Se.levelName&&xt.version>=Se.version):!0),he=ie.length>0?ie[0]:null,de=ie.length>1?ie[1]:null;return{current:he,previous:de,all:ie}},z=(t==null?void 0:t.currentLevel)||(t==null?void 0:t.current_level)||(t==null?void 0:t.currentStep),H=z!=null?Number(z):null,ye=((t==null?void 0:t.status)||"").toUpperCase(),ae=ye==="REJECTED",me=ye==="CLOSED",Q=!ae&&!me&&(ye==="PENDING"||ye==="IN_PROGRESS"||ye==="IN-PROGRESS"),oe=j.find(B=>{var ie,he;const Ie=B.levelId||B.level_id,xe=(ie=t==null?void 0:t.approvals)==null?void 0:ie.find(de=>de.levelId===Ie);return((he=xe==null?void 0:xe.status)==null?void 0:he.toLowerCase())==="rejected"}),Ce=oe?Number(oe.levelNumber||oe.level_number||oe.step||0):null,Ee=j.map((B,Ie)=>{var da,ds,le,ct,Ut,ms,Nt;const xe=Number(B.levelNumber||B.level_number||B.step||Ie+1),ie=B.levelName||B.level_name,he=(da=t==null?void 0:t.approvals)==null?void 0:da.find(Pe=>Pe.levelId===B.levelId);let de;if(ie&&ie.toLowerCase().includes("department lead")||xe===3){const Pe=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);(Pe!=null&&Pe.ioNumber||Pe!=null&&Pe.io_number)&&(de={ioNumber:Pe.ioNumber||Pe.io_number||"",blockedAmount:Pe.ioBlockedAmount||Pe.io_blocked_amount||0,availableBalance:Pe.ioAvailableBalance||Pe.io_available_balance||0,remainingBalance:Pe.ioRemainingBalance||Pe.io_remaining_balance||0,organizedBy:((ds=Pe.organizer)==null?void 0:ds.displayName)||((le=Pe.organizer)==null?void 0:le.name)||Pe.organizedBy||B.approver||"N/A",organizedAt:Pe.organizedAt||Pe.organized_at||B.approvedAt||(t==null?void 0:t.updatedAt)||""})}let Ne;xe===6&&(he!=null&&he.dmsDetails?Ne={dmsNumber:he.dmsDetails.dmsNumber||"",dmsRemarks:he.dmsDetails.dmsRemarks||"",pushedBy:he.dmsDetails.pushedBy||B.approver,pushedAt:he.dmsDetails.pushedAt||B.approvedAt||""}:t!=null&&t.dmsNumber&&(Ne={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||((ct=t.dmsDetails)==null?void 0:ct.dmsRemarks)||"",pushedBy:B.approver,pushedAt:B.approvedAt||t.updatedAt||""}));let ve;if(ae||me)((Ut=he==null?void 0:he.status)==null?void 0:Ut.toLowerCase())==="rejected"?ve="rejected":Ce!==null&&xe>Ce?ve="waiting":((ms=he==null?void 0:he.status)==null?void 0:ms.toLowerCase())==="approved"?ve="approved":Ce!==null&&xeH,ve="waiting");else if(Q&&H!==null&&H>0)if(xe>H)ve="waiting";else if(xeIe.step===H):null;be=B&&(B.status==="pending"||B.status==="in_progress")?B:Ee.find(Ie=>{var ie;const xe=((ie=Ie.status)==null?void 0:ie.toLowerCase())||"";return xe==="pending"||xe==="in_progress"||xe==="in-review"||xe==="in_review"}),q=be?be.step:H||(t==null?void 0:t.currentStep)||1}else q=H||(t==null?void 0:t.currentStep)||1;const ue=((pa=s==null?void 0:s.email)==null?void 0:pa.toLowerCase())||"",Ae=((Fa=t==null?void 0:t.dealerEmail)==null?void 0:Fa.toLowerCase())||((St=(wa=t==null?void 0:t.dealer)==null?void 0:wa.email)==null?void 0:St.toLowerCase())||((Za=(Ca=t==null?void 0:t.claimDetails)==null?void 0:Ca.dealerEmail)==null?void 0:Za.toLowerCase())||((Qa=(Ja=t==null?void 0:t.claimDetails)==null?void 0:Ja.dealer_email)==null?void 0:Qa.toLowerCase())||"",Ue=Ae&&ue===Ae,Z=j.find(B=>(B.step||B.levelNumber||B.level_number)===q),Te=((Z==null?void 0:Z.approverEmail)||"").toLowerCase(),Xe=Te&&ue===Te,pe=((er=(qa=t==null?void 0:t.initiator)==null?void 0:qa.email)==null?void 0:er.toLowerCase())||((tr=t==null?void 0:t.initiatorEmail)==null?void 0:tr.toLowerCase())||"",_e=j.find(B=>{const Ie=(B.approverEmail||"").toLowerCase(),xe=(B.levelName||"").toLowerCase();return pe&&Ie===pe||xe.includes("requestor evaluation")||xe.includes("requestor")&&xe.includes("confirmation")}),rt=_e&&(_e.step||_e.levelNumber||_e.level_number)||2,ut=_e||j.find(B=>(B.step||B.levelNumber||B.level_number)===2),nt=((ut==null?void 0:ut.approverEmail)||"").toLowerCase(),Ps=nt&&ue===nt,Xs=j.find(B=>(B.step||B.levelNumber||B.level_number)===1),Na=((Xs==null?void 0:Xs.approverEmail)||"").toLowerCase(),Xa=Na&&ue===Na,X=j.find(B=>(B.levelName||"").toLowerCase().includes("department lead")),we=((X==null?void 0:X.approverEmail)||"").toLowerCase(),J=we&&ue===we,Le=async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId;B.proposalDocument&&await nn(B.proposalDocument,ie,"APPROVAL");for(const de of B.otherDocuments)await nn(de,ie,"SUPPORTING");const he=B.costBreakup.reduce((de,Se)=>de+(Se.totalAmt||Se.amount||0),0);await BA(ie,{proposalDocument:B.proposalDocument||void 0,costBreakup:B.costBreakup.map(de=>({description:de.description,amount:de.amount,gstRate:de.gstRate,gstAmt:de.gstAmt,cgstRate:de.cgstRate,cgstAmt:de.cgstAmt,sgstRate:de.sgstRate,sgstAmt:de.sgstAmt,igstRate:de.igstRate,igstAmt:de.igstAmt,utgstRate:de.utgstRate,utgstAmt:de.utgstAmt,cessRate:de.cessRate,cessAmt:de.cessAmt,totalAmt:de.totalAmt})),totalEstimatedBudget:he,expectedCompletionDate:B.expectedCompletionDate,dealerComments:B.dealerComments}),K.success("Proposal submitted successfully"),W()}catch(ie){console.error("Failed to submit proposal:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to submit proposal. Please try again.";throw K.error(he),ie}},Fe=async B=>{var Ie,xe,ie,he,de;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Se=t.id||t.requestId,Ne=await vs(Se),ve=(Ne==null?void 0:Ne.approvalLevels)||(Ne==null?void 0:Ne.approvals)||[],bt=((xe=(Ie=t==null?void 0:t.initiator)==null?void 0:Ie.email)==null?void 0:xe.toLowerCase())||((ie=t==null?void 0:t.initiatorEmail)==null?void 0:ie.toLowerCase())||"",xt=ve.find(jt=>{const da=(jt.approverEmail||jt.approver_email||"").toLowerCase(),ds=(jt.levelName||jt.level_name||"").toLowerCase(),le=jt.levelNumber||jt.level_number;return bt&&da===bt||ds.includes("requestor evaluation")||ds.includes("requestor")&&ds.includes("confirmation")||le===rt})||ve.find(jt=>(jt.levelNumber||jt.level_number)===2);if(!(xt!=null&&xt.levelId)&&!(xt!=null&&xt.level_id))throw new Error("Initiator approval level not found");const ls=xt.levelId||xt.level_id;await an(Se,ls,B),K.success("Proposal approved successfully"),W()}catch(Se){console.error("Failed to approve proposal:",Se);const Ne=((de=(he=Se==null?void 0:Se.response)==null?void 0:he.data)==null?void 0:de.message)||(Se==null?void 0:Se.message)||"Failed to approve proposal. Please try again.";throw K.error(Ne),Se}},Ve=async B=>{var Ie,xe,ie,he,de;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Se=t.id||t.requestId,Ne=await vs(Se),ve=(Ne==null?void 0:Ne.approvalLevels)||(Ne==null?void 0:Ne.approvals)||[],bt=((xe=(Ie=t==null?void 0:t.initiator)==null?void 0:Ie.email)==null?void 0:xe.toLowerCase())||((ie=t==null?void 0:t.initiatorEmail)==null?void 0:ie.toLowerCase())||"",xt=ve.find(jt=>{const da=(jt.approverEmail||jt.approver_email||"").toLowerCase(),ds=(jt.levelName||jt.level_name||"").toLowerCase(),le=jt.levelNumber||jt.level_number;return bt&&da===bt||ds.includes("requestor evaluation")||ds.includes("requestor")&&ds.includes("confirmation")||le===rt})||ve.find(jt=>(jt.levelNumber||jt.level_number)===2);if(!(xt!=null&&xt.levelId)&&!(xt!=null&&xt.level_id))throw new Error("Initiator approval level not found");const ls=xt.levelId||xt.level_id;await Sr(Se,ls,"Proposal rejected by requestor",B),K.success("Proposal rejected. Request has been cancelled."),W()}catch(Se){console.error("Failed to reject proposal:",Se);const Ne=((de=(he=Se==null?void 0:Se.response)==null?void 0:he.data)==null?void 0:de.message)||(Se==null?void 0:Se.message)||"Failed to reject proposal. Please try again.";throw K.error(Ne),Se}},Me=async B=>{var Ie,xe,ie,he,de;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Se=t.id||t.requestId,Ne=await vs(Se),ve=(Ne==null?void 0:Ne.approvalLevels)||(Ne==null?void 0:Ne.approvals)||[],bt=((xe=(Ie=t==null?void 0:t.initiator)==null?void 0:Ie.email)==null?void 0:xe.toLowerCase())||((ie=t==null?void 0:t.initiatorEmail)==null?void 0:ie.toLowerCase())||"",xt=ve.find(jt=>{const da=(jt.approverEmail||jt.approver_email||"").toLowerCase(),ds=(jt.levelName||jt.level_name||"").toLowerCase(),le=jt.levelNumber||jt.level_number;return bt&&da===bt||ds.includes("requestor evaluation")||ds.includes("requestor")&&ds.includes("confirmation")||le===rt})||ve.find(jt=>(jt.levelNumber||jt.level_number)===2);if(!(xt!=null&&xt.levelId)&&!(xt!=null&&xt.level_id))throw new Error("Initiator approval level not found");const ls=xt.levelId||xt.level_id;await Sr(Se,ls,"Revised Quotation Requested",B),K.success("Revision requested. Request returned to dealer."),W()}catch(Se){console.error("Failed to request revision:",Se);const Ne=((de=(he=Se==null?void 0:Se.response)==null?void 0:he.data)==null?void 0:de.message)||(Se==null?void 0:Se.message)||"Failed to request revision. Please try again.";throw K.error(Ne),Se}},Ze=async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId,he=await vs(ie),de=(he==null?void 0:he.approvalLevels)||(he==null?void 0:he.approvals)||[],Se=de.find(ve=>(ve.levelName||ve.level_name||"").toLowerCase().includes("department lead"))||de.find(ve=>(ve.levelNumber||ve.level_number)===3);if(!(Se!=null&&Se.levelId)&&!(Se!=null&&Se.level_id))throw new Error("Department Lead approval level not found");const Ne=Se.levelId||Se.level_id;await Zp(ie,{ioNumber:B.ioNumber}),await an(ie,Ne,B.comments),K.success("Request approved and IO organized successfully"),W()}catch(ie){console.error("Failed to approve and organize IO:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to approve request. Please try again.";throw K.error(he),ie}},Be=async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId,he=B.closedExpenses.map(de=>({description:de.description,amount:de.amount,gstRate:de.gstRate,gstAmt:de.gstAmt,cgstRate:de.cgstRate,cgstAmt:de.cgstAmt,sgstRate:de.sgstRate,sgstAmt:de.sgstAmt,igstRate:de.igstRate,igstAmt:de.igstAmt,utgstRate:de.utgstRate,utgstAmt:de.utgstAmt,cessRate:de.cessRate,cessAmt:de.cessAmt,totalAmt:de.totalAmt}));if(await VA(ie,{activityCompletionDate:B.activityCompletionDate,numberOfParticipants:B.numberOfParticipants,closedExpenses:he,totalClosedExpenses:B.totalClosedExpenses,completionDocuments:B.completionDocuments,activityPhotos:B.activityPhotos,completionDescription:B.completionDescription}),B.invoicesReceipts&&B.invoicesReceipts.length>0)for(const de of B.invoicesReceipts)await nn(de,ie,"SUPPORTING");B.attendanceSheet&&await nn(B.attendanceSheet,ie,"SUPPORTING"),K.success("Completion documents submitted successfully"),W()}catch(ie){console.error("Failed to submit completion documents:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to submit completion documents. Please try again.";throw K.error(he),ie}},qe=async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId,he=new Date().toISOString().slice(0,10);await HA(ie,{eInvoiceDate:he}),K.success("E-Invoice generation initiated successfully."),W()}catch(ie){console.error("[DealerClaimWorkflowTab] Error generating e-invoice:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to generate e-invoice. Please try again.";throw K.error(he),ie}},fs=async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId,he=await vs(ie),de=(he==null?void 0:he.approvalLevels)||(he==null?void 0:he.approvals)||[],Se=de.find(ve=>(ve.levelName||ve.level_name||"").toLowerCase().includes("department lead"))||de.find(ve=>(ve.levelNumber||ve.level_number)===3);if(!(Se!=null&&Se.levelId)&&!(Se!=null&&Se.level_id))throw new Error("Department Lead approval level not found");const Ne=Se.levelId||Se.level_id;await Sr(ie,Ne,"Dept Lead rejected - More clarification required",B),K.success("Request rejected. Request has been cancelled."),W()}catch(ie){console.error("Failed to reject request:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to reject request. Please try again.";throw K.error(he),ie}},[Ht,at]=p.useState(null);p.useEffect(()=>{if(!t){at(null);return}(async()=>{try{const Ie=t.id||t.requestId;if(!Ie){at(null);return}const xe=await vs(Ie),ie=(xe==null?void 0:xe.documents)||[],he=t.proposalDetails||(xe==null?void 0:xe.proposalDetails)||{},de=ie.find(ve=>ve.category==="APPROVAL"||ve.type==="proposal"||ve.documentCategory==="APPROVAL"),Se=ie.filter(ve=>ve.category==="SUPPORTING"||ve.type==="supporting"||ve.documentCategory==="SUPPORTING");let Ne=he.costBreakup||[];if(typeof Ne=="string")try{Ne=JSON.parse(Ne)}catch(ve){console.warn("Failed to parse costBreakup JSON:",ve),Ne=[]}Array.isArray(Ne)||(Ne=[]),at({proposalDocument:de?{name:de.fileName||de.file_name||de.name,id:de.documentId||de.document_id||de.id}:void 0,costBreakup:Ne,expectedCompletionDate:he.expectedCompletionDate||"",otherDocuments:Se.map(ve=>({name:ve.fileName||ve.file_name||ve.name,id:ve.documentId||ve.document_id||ve.id})),dealerComments:he.dealerComments||"",submittedAt:he.submittedAt})}catch(Ie){console.warn("Failed to load proposal data:",Ie);const xe=t.proposalDetails||{};let ie=xe.costBreakup||[];if(typeof ie=="string")try{ie=JSON.parse(ie)}catch(he){console.warn("Failed to parse costBreakup JSON:",he),ie=[]}Array.isArray(ie)||(ie=[]),at({proposalDocument:void 0,costBreakup:ie,expectedCompletionDate:xe.expectedCompletionDate||"",otherDocuments:[],dealerComments:xe.dealerComments||"",submittedAt:xe.submittedAt})}})()},[t]);const[et,yt]=p.useState(null);p.useEffect(()=>{if(!t){yt(null);return}(async()=>{try{const Ie=t.id||t.requestId;if(!Ie){yt(null);return}const xe=await vs(Ie),ie=(xe==null?void 0:xe.documents)||[],he=[],de=[],Se=[];let Ne=null;ie.forEach(ve=>{const bt=(ve.category||ve.documentCategory||ve.type||"").toUpperCase(),xt=(ve.fileName||ve.file_name||ve.name||"").toLowerCase(),ls={name:ve.fileName||ve.file_name||ve.name,id:ve.documentId||ve.document_id||ve.id,url:ve.url||ve.storageUrl||ve.storage_url};bt==="COMPLETION"||bt==="COMPLETION_DOCUMENT"?he.push(ls):bt==="ACTIVITY_PHOTO"||bt==="PHOTO"||bt==="IMAGE"?de.push(ls):bt==="ATTENDANCE"||bt==="ATTENDANCE_SHEET"?Ne=ls:(bt==="SUPPORTING"||bt==="INVOICE"||bt==="RECEIPT")&&(!Ne&&(xt.includes("attendance")||xt.includes("participant"))?Ne=ls:Se.push(ls))}),he.length===0&&de.length===0&&t.completionDetails,yt({completionDocuments:he,activityPhotos:de,invoicesReceipts:Se,attendanceSheet:Ne})}catch(Ie){console.warn("Failed to load completion documents:",Ie),yt(null)}})()},[t]);const rs=async()=>{try{const B=t.id||t.requestId;if(!B){K.error("Request ID not found");return}if(!t.invoice&&!t.irn){K.error("Invoice not generated yet");return}const Ie=tt.getAccessToken(),xe=`https://reflow-uat.royalenfield.com/api/v1//dealer-claims/${B}/e-invoice/pdf?token=${Ie}`;window.open(xe,"_blank")}catch(B){console.error("Failed to preview invoice:",B),K.error("Failed to open invoice preview")}},Pt=((_a=t==null?void 0:t.claimDetails)==null?void 0:_a.dealerName)||((ga=t==null?void 0:t.dealerInfo)==null?void 0:ga.name)||"Dealer",la=((La=t==null?void 0:t.claimDetails)==null?void 0:La.activityName)||((It=t==null?void 0:t.activityInfo)==null?void 0:It.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(ee,{children:[e.jsx(ge,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx($e,{className:"mt-2",children:"Approval process for dealer claim management"})]})})}),e.jsxs(se,{children:[(t==null?void 0:t.status)==="rejected"&&!(t!=null&&t.closureDate||t!=null&&t.closure_date)&&a?e.jsxs("div",{className:"mb-6 p-4 bg-amber-50 border-l-4 border-amber-500 rounded-lg flex items-start gap-4 shadow-sm",children:[e.jsx("div",{className:"p-2 bg-amber-100 rounded-full",children:e.jsx(as,{className:"w-5 h-5 text-amber-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-sm font-bold text-amber-900 mb-1",children:"Action Required: Request Returned"}),e.jsxs("p",{className:"text-xs text-amber-800 leading-relaxed mb-3",children:["This request has been returned to you by the department head.",a?"You can choose to resubmit, discuss with the dealer, request a revision, or cancel the request.":"The initiator needs to take action to proceed."]})]})]}):null,e.jsx("div",{className:"space-y-4",children:Ee.map((B,Ie)=>{var xt,ls,jt,da,ds;const ie=(((xt=B.status)==null?void 0:xt.toLowerCase())||"")==="in_progress",he=B.step===q,de=Q&&ie&&he,Se=B.status==="approved",Ne=j.find(le=>(le.step||le.levelNumber||le.level_number)===B.step),ve=Ne!=null&&Ne.levelId?(ls=t==null?void 0:t.approvals)==null?void 0:ls.find(le=>le.levelId===Ne.levelId||le.level_id===Ne.levelId):null,bt=(ve==null?void 0:ve.status)==="PAUSED"||((jt=t==null?void 0:t.pauseInfo)==null?void 0:jt.isPaused)&&(((da=t==null?void 0:t.pauseInfo)==null?void 0:da.levelId)===(ve==null?void 0:ve.levelId)||((ds=t==null?void 0:t.pauseInfo)==null?void 0:ds.level_id)===(ve==null?void 0:ve.levelId));return e.jsx("div",{className:`relative p-5 rounded-lg border-2 transition-all ${XA(B.status,de)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${ZA(B.status)}`,children:YA(B.status)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h4",{className:"font-semibold text-gray-900",children:B.title}),e.jsx(ne,{className:KA(B.status),children:B.status.toLowerCase()}),B.emailTemplateUrl&&B.status==="approved"&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",title:"View email template",onClick:()=>{k({stepNumber:B.step,stepName:B.title}),w(!0)},children:e.jsx(Ra,{className:"w-3.5 h-3.5 text-blue-600"})}),B.step===7&&B.einvoiceUrl&&Se&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",title:"Download E-Invoice",onClick:()=>window.open(B.einvoiceUrl,"_blank"),children:e.jsx(Ct,{className:"w-3.5 h-3.5 text-green-600"})}),(()=>{const le=(B.levelName||B.title||"").toLowerCase().includes("requestor claim")||(B.levelName||B.title||"").toLowerCase().includes("requestor - claim"),ct=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&B.status==="approved";return le&&ct&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-amber-100",title:"Preview Invoice",onClick:rs,children:e.jsx(Gt,{className:"w-3.5 h-3.5 text-amber-600"})})})()]}),e.jsx("p",{className:"text-sm text-gray-600",children:B.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:B.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",Ft(B.tatHours)]}),B.elapsedHours&&(de||Se)&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",Ft(B.elapsedHours)]})]})]}),B.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:B.comment})}),B.versionHistory&&B.versionHistory.all&&B.versionHistory.all.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsxs(E,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs text-amber-700 hover:text-amber-800 hover:bg-amber-50",onClick:()=>{const le=new Set(F);le.has(B.step)?le.delete(B.step):le.add(B.step),$(le)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lx,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"font-medium",children:"Version History"}),B.versionHistory.all&&B.versionHistory.all.length>0&&e.jsxs(ne,{className:"bg-amber-100 text-amber-800 text-[10px] px-1.5 py-0",children:[B.versionHistory.all.length," Versions"]})]}),F.has(B.step)?e.jsx(Xu,{className:"w-4 h-4"}):e.jsx(uo,{className:"w-4 h-4"})]}),F.has(B.step)&&B.versionHistory.all&&e.jsx("div",{className:"mt-2 space-y-3 p-3 bg-amber-50/50 rounded-lg border border-amber-200 text-left",children:B.versionHistory.all.map((le,ct)=>{var Ut,ms,Nt,Pe;return e.jsxs("div",{className:`space-y-2 ${ct>0?"pt-2 border-t border-amber-200":""}`,children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ne,{className:`${ct===0?"bg-amber-500":"bg-gray-400"} text-white text-[10px] px-2 py-0.5`,children:[ct===0?"Current":"Previous",": v",le.version]}),e.jsx("span",{className:"text-[10px] text-gray-600 font-medium",children:Cr(le.createdAt)})]})}),e.jsx("p",{className:"text-xs text-gray-700 font-medium",children:le.changeReason||"Version Update"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${ct===0?"bg-blue-100":"bg-gray-100"} flex items-center justify-center`,children:e.jsx("span",{className:`text-[8px] font-bold ${ct===0?"text-blue-600":"text-gray-600"}`,children:((ms=(Ut=le.changer)==null?void 0:Ut.displayName)==null?void 0:ms.charAt(0))||"U"})}),e.jsxs("span",{className:"text-[10px] text-gray-600",children:["By ",((Nt=le.changer)==null?void 0:Nt.displayName)||((Pe=le.changer)==null?void 0:Pe.email)||"Unknown User"]})]}),le.snapshotType==="PROPOSAL"&&le.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold text-gray-700",children:"Proposal Snapshot"}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Budget: ₹",Number(le.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("button",{className:"text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors",onClick:()=>T({data:le.snapshotData,type:"PROPOSAL",title:`Proposal (v${le.version})`}),children:[e.jsx(ht,{className:"w-3 h-3"}),"View Details"]})]}),le.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",le.snapshotData.comments]})]}),le.snapshotType==="INTERNAL_ORDER"&&le.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsx("p",{className:"text-[10px] font-semibold text-gray-700 mb-1",children:"IO Block Snapshot:"}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["IO Number: ",le.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Blocked Amount: ₹",Number(le.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),le.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-[10px] text-gray-600",children:["SAP Doc: ",le.snapshotData.sapDocumentNumber]})]}),le.snapshotType==="COMPLETION"&&le.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold text-gray-700",children:"Completion Snapshot"}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Total: ₹",Number(le.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("button",{className:"text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors",onClick:()=>T({data:le.snapshotData,type:"COMPLETION",title:`Completion (v${le.version})`}),children:[e.jsx(ht,{className:"w-3 h-3"}),"View Details"]})]}),le.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",le.snapshotData.comments]})]}),le.snapshotType==="APPROVE"&&le.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-gray-700 mb-1",children:[le.snapshotData.action==="APPROVE"?"Approval":"Rejection"," Snapshot:"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["By: ",le.snapshotData.approverName||le.snapshotData.approverEmail||"Unknown"]}),le.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1",children:["Comments: ",le.snapshotData.comments.substring(0,100),le.snapshotData.comments.length>100?"...":""]}),le.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-[10px] text-red-600 mt-1",children:["Rejection Reason: ",le.snapshotData.rejectionReason.substring(0,100),le.snapshotData.rejectionReason.length>100?"...":""]})]}),le.snapshotType==="WORKFLOW"&&le.snapshotData&&le.snapshotData.comments&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200",children:[e.jsx("p",{className:"text-[10px] font-semibold text-gray-700 mb-1",children:"Approval Comment:"}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:[le.snapshotData.comments.substring(0,100),le.snapshotData.comments.length>100?"...":""]})]})]},ct)})})]}),de&&(ve==null?void 0:ve.sla)&&e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Due by:"}),e.jsx("span",{className:"font-medium text-gray-900",children:ve.sla.deadline?xa(ve.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${bt?"bg-gray-100 border-gray-300":(ve.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(ve.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(ve.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(st,{className:"w-4 h-4"}),"Current Approver - Time Tracking ",bt&&"(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:ve.sla.elapsedText||"0 hours"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-600",children:"Time used:"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[ve.sla.elapsedText||"0 hours"," / ",Ft(B.tatHours)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const le=ve.sla.percentageUsed||0,ct=()=>bt?"bg-gray-500":le>=100?"bg-red-600":le>=75?"bg-orange-500":le>=50?"bg-amber-500":"bg-green-600",Ut=()=>bt?"text-gray-600":le>=100?"text-red-600":le>=75?"text-orange-600":le>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(na,{value:le,className:"h-3",indicatorClassName:ct()}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`text-xs font-semibold ${Ut()}`,children:["Progress: ",Math.min(100,le),"% of TAT used"]}),e.jsxs("span",{className:"text-xs font-medium text-gray-700",children:[ve.sla.remainingText||"0 hours"," remaining"]})]})]})})(),ve.sla.status==="breached"&&e.jsxs("p",{className:"text-xs font-semibold text-center text-red-600 flex items-center justify-center gap-1.5",children:[e.jsx(ni,{className:"w-4 h-4"}),"Deadline Breached"]}),ve.sla.status==="critical"&&e.jsxs("p",{className:"text-xs font-semibold text-center text-orange-600 flex items-center justify-center gap-1.5",children:[e.jsx(as,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),(()=>{const le=B.levelName||B.level_name;return(le&&le.toLowerCase().includes("department lead")||B.title&&B.title.toLowerCase().includes("department lead"))&&B.status==="approved"&&B.ioDetails&&B.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(Gt,{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:B.ioDetails.ioNumber})]}),B.ioDetails.blockedAmount!==void 0&&B.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:["₹",B.ioDetails.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),B.ioDetails.remainingBalance!==void 0&&B.ioDetails.remainingBalance!==null&&e.jsxs("div",{className:"flex items-center justify-between pt-1.5 border-t border-blue-100",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"Remaining Balance:"}),e.jsxs("span",{className:"text-sm font-semibold text-blue-700",children:["₹",B.ioDetails.remainingBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsxs("div",{className:"pt-1.5 border-t border-blue-100 text-xs text-gray-500",children:["Organised by ",B.ioDetails.organizedBy||B.approver||"N/A"," on"," ",B.ioDetails.organizedAt?Cr(B.ioDetails.organizedAt):B.approvedAt?Cr(B.approvedAt):"N/A"]})]})]})})(),B.step===6&&B.dmsDetails&&B.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(kt,{className:"w-4 h-4 text-purple-600"}),e.jsx("p",{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"E-Invoice & Settlement Details"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-gray-600",children:"Settlement ID:"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:B.dmsDetails.dmsNumber})]}),B.dmsDetails.dmsRemarks&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Settlement Remarks:"}),e.jsx("p",{className:"text-sm text-gray-900",children:B.dmsDetails.dmsRemarks})]}),B.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Initiated by ",B.dmsDetails.pushedBy," on"," ",Cr(B.dmsDetails.pushedAt)]})]})]}),(()=>{const le=j.find(Pe=>(Pe.step||Pe.levelNumber||Pe.level_number)===B.step),ct=((le==null?void 0:le.approverEmail)||"").toLowerCase(),Ut=ct&&ue===ct,ms=B.step===1||(le==null?void 0:le.levelName)&&le.levelName.toLowerCase().includes("dealer");return de&&(Ut||ms&&Ue)})()&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[(()=>{const le=((Ne==null?void 0:Ne.levelName)||B.title||"").toLowerCase();return(B.step===1||le.includes("proposal")||le.includes("submission"))&&(Ue||Xa)})()&&e.jsxs(E,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{o(!0)},children:[e.jsx(zs,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),(()=>{const le=((Ne==null?void 0:Ne.levelName)||B.title||"").toLowerCase();return(le.includes("requestor evaluation")||le.includes("confirmation")||B.step===rt)&&(a||Ps)})()&&e.jsxs(E,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{d(!0)},children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Review Request"]}),(()=>{const le=j.find(Pe=>(Pe.step||Pe.levelNumber||Pe.level_number)===B.step);if(!((le==null?void 0:le.levelName)||B.title||"").toLowerCase().includes("initiator action")||!(a||ue===pe))return null;const Nt=async Pe=>{var bs,_t;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const us=t.requestId||t.id;await Gx(us,Pe,{reason:""}),K.success(`Action "${Pe==="REVISE"?"Revision Requested":"Request Reopened"}" performed successfully`),W()}catch(us){console.error("Failed to perform initiator action:",us);const vg=((_t=(bs=us==null?void 0:us.response)==null?void 0:bs.data)==null?void 0:_t.message)||(us==null?void 0:us.message)||"Failed to perform action";K.error(vg)}};return e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(E,{variant:"outline",className:"border-orange-500 text-orange-600 hover:bg-orange-50",onClick:()=>Nt("REVISE"),children:[e.jsx($t,{className:"w-4 h-4 mr-2"}),"Request Re-quotation"]}),e.jsxs(E,{variant:"outline",className:"border-blue-500 text-blue-600 hover:bg-blue-50",onClick:()=>Nt("REOPEN"),children:[e.jsx(tx,{className:"w-4 h-4 mr-2"}),"Reopen"]})]})})(),(()=>{const le=j.find(_t=>(_t.levelName||"").toLowerCase().includes("department lead"));if(!(le&&B.step===(le.step||le.levelNumber||le.level_number)))return null;const Ut=((le==null?void 0:le.approverEmail)||"").toLowerCase();if(!(Ut&&ue===Ut||J||Xe))return null;const Nt=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order),Pe=(Nt==null?void 0:Nt.ioNumber)||(Nt==null?void 0:Nt.io_number)||(t==null?void 0:t.ioNumber)||"",bs=Pe&&Pe.trim()!=="";return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(E,{className:"bg-green-600 hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>{h(!0)},disabled:!bs,children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Review and Approve"]}),!bs&&e.jsx("p",{className:"text-xs text-amber-600",children:"Please add an IO number in the IO tab before approving this step."})]})})(),(()=>{const le=j.find(Pe=>(Pe.step||Pe.levelNumber||Pe.level_number)===B.step),ct=((le==null?void 0:le.approverEmail)||"").toLowerCase(),Ut=Ue&&ct===Ae,ms=((le==null?void 0:le.levelName)||B.title||"").toLowerCase(),Nt=ms.includes("dealer completion")||ms.includes("completion documents");return Ut&&Nt})()&&e.jsxs(E,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{u(!0)},children:[e.jsx(zs,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),(()=>{const le=j.find(Nt=>{const Pe=(Nt.levelName||"").toLowerCase();return Pe.includes("requestor claim")||Pe.includes("requestor - claim")});if(!(le&&B.step===(le.step||le.levelNumber||le.level_number)))return null;const Ut=((le==null?void 0:le.approverEmail)||"").toLowerCase();return a||Ut&&ue===Ut?e.jsxs(E,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:()=>{b(!0)},children:[e.jsx(kt,{className:"w-4 h-4 mr-2"}),"Generate E-Invoice & Sync"]}):null})(),(()=>{var bs;const le=((Ne==null?void 0:Ne.levelName)||B.title||"").toLowerCase(),ct=le.includes("credit note")||le.includes("sap")||B.step===8&&!le.includes("additional"),Ut=((Ne==null?void 0:Ne.approverEmail)||"").toLowerCase(),ms=Ut&&ue===Ut,Nt=((bs=s==null?void 0:s.role)==null?void 0:bs.toUpperCase())||"";return ct&&(ms||(Nt==="FINANCE"||Nt==="ADMIN"))})()&&e.jsxs(E,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{y(!0)},children:[e.jsx(Gt,{className:"w-4 h-4 mr-2"}),"View & Send Credit Note"]}),(()=>{const le=j.find(Nt=>(Nt.step||Nt.levelNumber||Nt.level_number)===B.step),ct=((le==null?void 0:le.levelName)||B.title||"").toLowerCase(),Ut=ct.includes("additional approver"),ms=B.step===1||ct.includes("proposal")||ct.includes("submission")||ct.includes("requestor evaluation")||ct.includes("confirmation")||ct.includes("department lead")||ct.includes("dealer completion")||ct.includes("completion documents")||ct.includes("requestor claim")||ct.includes("requestor - claim")||ct.includes("credit note")||ct.includes("sap");if(Ut||!ms){const Nt=(le==null?void 0:le.levelId)||(le==null?void 0:le.level_id);if(Nt){const Pe=(le==null?void 0:le.levelName)||(le==null?void 0:le.level_name)||B.title||"Approval Level",bs=(le==null?void 0:le.approverName)||(le==null?void 0:le.approver_name)||B.approver||"Approver";return e.jsxs(E,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{A({levelId:Nt,levelName:Pe,approverName:bs}),_(!0)},children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Review Request"]})}return e.jsxs(e.Fragment,{children:[e.jsxs(E,{className:"bg-green-600 hover:bg-green-700",onClick:async()=>{var Pe,bs;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const _t=t.id||t.requestId;if(!Nt){K.error("Approval level not found");return}await an(_t,Nt,""),K.success("Request approved successfully"),W()}catch(_t){console.error("Failed to approve:",_t);const us=((bs=(Pe=_t==null?void 0:_t.response)==null?void 0:Pe.data)==null?void 0:bs.message)||(_t==null?void 0:_t.message)||"Failed to approve request. Please try again.";K.error(us)}},children:[e.jsx(De,{className:"w-4 h-4 mr-2"}),"Approve"]}),e.jsxs(E,{variant:"destructive",onClick:async()=>{var Pe,bs;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const _t=t.id||t.requestId;if(!Nt){K.error("Approval level not found");return}const us=prompt("Please provide a reason for rejection:");if(us===null)return;await Sr(_t,Nt,"Request rejected",us),K.success("Request rejected successfully"),W()}catch(_t){console.error("Failed to reject:",_t);const us=((bs=(Pe=_t==null?void 0:_t.response)==null?void 0:Pe.data)==null?void 0:bs.message)||(_t==null?void 0:_t.message)||"Failed to reject request. Please try again.";K.error(us)}},children:[e.jsx(wt,{className:"w-4 h-4 mr-2"}),"Reject"]})]})}return null})()]}),B.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",Cr(B.approvedAt)]})]})]})},Ie)})})]})]}),e.jsx(EA,{isOpen:l,onClose:()=>o(!1),onSubmit:Le,dealerName:Pt,activityName:la,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),previousProposalData:(ns=N==null?void 0:N.find(B=>B.snapshotType==="PROPOSAL"))==null?void 0:ns.snapshotData,documentPolicy:i}),e.jsx(MA,{isOpen:c,onClose:()=>{d(!1)},onApprove:Fe,onReject:Ve,onRequestRevision:Me,proposalData:Ht,dealerName:Pt,activityName:la,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),request:t,previousProposalData:(()=>{const B=(N==null?void 0:N.filter(Ie=>Ie.snapshotType==="PROPOSAL"))||[];return B.length>1?B[1].snapshotData:null})()}),e.jsx(FA,{isOpen:m,onClose:()=>h(!1),onApprove:Ze,onReject:fs,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),preFilledIONumber:((Os=t==null?void 0:t.internalOrder)==null?void 0:Os.ioNumber)||((sr=t==null?void 0:t.internalOrder)==null?void 0:sr.io_number)||((ar=t==null?void 0:t.internal_order)==null?void 0:ar.ioNumber)||((oa=t==null?void 0:t.internal_order)==null?void 0:oa.io_number)||void 0,preFilledBlockedAmount:((vt=t==null?void 0:t.internalOrder)==null?void 0:vt.ioBlockedAmount)||((is=t==null?void 0:t.internalOrder)==null?void 0:is.io_blocked_amount)||((Is=t==null?void 0:t.internal_order)==null?void 0:Is.ioBlockedAmount)||((Zs=t==null?void 0:t.internal_order)==null?void 0:Zs.io_blocked_amount)||void 0,preFilledRemainingBalance:((Nr=t==null?void 0:t.internalOrder)==null?void 0:Nr.ioRemainingBalance)||((ca=t==null?void 0:t.internalOrder)==null?void 0:ca.io_remaining_balance)||((Ma=t==null?void 0:t.internal_order)==null?void 0:Ma.ioRemainingBalance)||((Kr=t==null?void 0:t.internal_order)==null?void 0:Kr.io_remaining_balance)||void 0}),e.jsx(IA,{isOpen:x,onClose:()=>u(!1),onSubmit:Be,dealerName:Pt,activityName:la,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),documentPolicy:i}),e.jsx(_A,{isOpen:g,onClose:()=>b(!1),onPush:qe,completionDetails:{activityCompletionDate:((Xr=t==null?void 0:t.completionDetails)==null?void 0:Xr.activityCompletionDate)||((Zr=t==null?void 0:t.completionDetails)==null?void 0:Zr.activity_completion_date),numberOfParticipants:((yc=t==null?void 0:t.completionDetails)==null?void 0:yc.numberOfParticipants)||((vc=t==null?void 0:t.completionDetails)==null?void 0:vc.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||((jc=t==null?void 0:t.completionDetails)==null?void 0:jc.closedExpenses)||((Nc=t==null?void 0:t.completionDetails)==null?void 0:Nc.closed_expenses),totalClosedExpenses:((wc=t==null?void 0:t.budgetTracking)==null?void 0:wc.closedExpenses)||((Cc=t==null?void 0:t.budgetTracking)==null?void 0:Cc.closed_expenses)||((Sc=t==null?void 0:t.completionDetails)==null?void 0:Sc.totalClosedExpenses)||((Ac=t==null?void 0:t.completionDetails)==null?void 0:Ac.total_closed_expenses),completionDescription:((Tc=t==null?void 0:t.completionDetails)==null?void 0:Tc.completionDescription)||((kc=t==null?void 0:t.completionDetails)==null?void 0:kc.completion_description)},ioDetails:{ioNumber:((Rc=t==null?void 0:t.internalOrder)==null?void 0:Rc.ioNumber)||((Dc=t==null?void 0:t.internalOrder)==null?void 0:Dc.io_number)||((Pc=t==null?void 0:t.internal_order)==null?void 0:Pc.ioNumber)||((Ic=t==null?void 0:t.internal_order)==null?void 0:Ic.io_number),blockedAmount:((Ec=t==null?void 0:t.internalOrder)==null?void 0:Ec.ioBlockedAmount)||((Fc=t==null?void 0:t.internalOrder)==null?void 0:Fc.io_blocked_amount)||((_c=t==null?void 0:t.internal_order)==null?void 0:_c.ioBlockedAmount)||((Lc=t==null?void 0:t.internal_order)==null?void 0:Lc.io_blocked_amount),availableBalance:((Mc=t==null?void 0:t.internalOrder)==null?void 0:Mc.ioAvailableBalance)||(($c=t==null?void 0:t.internalOrder)==null?void 0:$c.io_available_balance)||((Oc=t==null?void 0:t.internal_order)==null?void 0:Oc.ioAvailableBalance)||((Uc=t==null?void 0:t.internal_order)==null?void 0:Uc.io_available_balance),remainingBalance:((Bc=t==null?void 0:t.internalOrder)==null?void 0:Bc.ioRemainingBalance)||((Vc=t==null?void 0:t.internalOrder)==null?void 0:Vc.io_remaining_balance)||((zc=t==null?void 0:t.internal_order)==null?void 0:zc.ioRemainingBalance)||((Hc=t==null?void 0:t.internal_order)==null?void 0:Hc.io_remaining_balance)},completionDocuments:et,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(PA,{isOpen:f,onClose:()=>y(!1),onDownload:async()=>{K.info("Download functionality will be implemented")},onSendToDealer:async()=>{var B,Ie;try{const xe=(t==null?void 0:t.requestId)||(t==null?void 0:t.id);if(!xe){K.error("Request ID not found");return}await WA(xe),K.success("Credit note sent to dealer successfully. Step 8 has been approved."),n&&n()}catch(xe){console.error("Failed to send credit note to dealer:",xe);const ie=((Ie=(B=xe==null?void 0:xe.response)==null?void 0:B.data)==null?void 0:Ie.message)||(xe==null?void 0:xe.message)||"Failed to send credit note to dealer";K.error(ie)}},creditNoteData:{creditNoteNumber:((Wc=t==null?void 0:t.creditNote)==null?void 0:Wc.creditNoteNumber)||((Gc=t==null?void 0:t.creditNote)==null?void 0:Gc.credit_note_number)||((Kc=(Yc=t==null?void 0:t.claimDetails)==null?void 0:Yc.creditNote)==null?void 0:Kc.creditNoteNumber)||((Xc=t==null?void 0:t.claimDetails)==null?void 0:Xc.creditNoteNumber)||((Zc=t==null?void 0:t.claimDetails)==null?void 0:Zc.credit_note_number),creditNoteDate:((Jc=t==null?void 0:t.creditNote)==null?void 0:Jc.creditNoteDate)||((Qc=t==null?void 0:t.creditNote)==null?void 0:Qc.credit_note_date)||((ed=(qc=t==null?void 0:t.claimDetails)==null?void 0:qc.creditNote)==null?void 0:ed.creditNoteDate)||((td=t==null?void 0:t.claimDetails)==null?void 0:td.creditNoteDate)||((sd=t==null?void 0:t.claimDetails)==null?void 0:sd.credit_note_date),creditNoteAmount:(ad=t==null?void 0:t.creditNote)!=null&&ad.creditNoteAmount?Number((rd=t==null?void 0:t.creditNote)==null?void 0:rd.creditNoteAmount):(nd=t==null?void 0:t.creditNote)!=null&&nd.credit_note_amount?Number((id=t==null?void 0:t.creditNote)==null?void 0:id.credit_note_amount):(od=(ld=t==null?void 0:t.claimDetails)==null?void 0:ld.creditNote)!=null&&od.creditNoteAmount?Number((dd=(cd=t==null?void 0:t.claimDetails)==null?void 0:cd.creditNote)==null?void 0:dd.creditNoteAmount):(md=t==null?void 0:t.claimDetails)!=null&&md.creditNoteAmount?Number((ud=t==null?void 0:t.claimDetails)==null?void 0:ud.creditNoteAmount):(xd=t==null?void 0:t.claimDetails)!=null&&xd.credit_note_amount?Number((hd=t==null?void 0:t.claimDetails)==null?void 0:hd.credit_note_amount):void 0,status:((pd=t==null?void 0:t.creditNote)==null?void 0:pd.status)||((fd=(gd=t==null?void 0:t.claimDetails)==null?void 0:gd.creditNote)==null?void 0:fd.status)||((bd=t==null?void 0:t.creditNote)!=null&&bd.creditNoteNumber?"CONFIRMED":"PENDING")},dealerInfo:{dealerName:((yd=t==null?void 0:t.claimDetails)==null?void 0:yd.dealerName)||((vd=t==null?void 0:t.claimDetails)==null?void 0:vd.dealer_name),dealerCode:((jd=t==null?void 0:t.claimDetails)==null?void 0:jd.dealerCode)||((Nd=t==null?void 0:t.claimDetails)==null?void 0:Nd.dealer_code),dealerEmail:((wd=t==null?void 0:t.claimDetails)==null?void 0:wd.dealerEmail)||((Cd=t==null?void 0:t.claimDetails)==null?void 0:Cd.dealer_email)},activityName:((Sd=t==null?void 0:t.claimDetails)==null?void 0:Sd.activityName)||((Ad=t==null?void 0:t.claimDetails)==null?void 0:Ad.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(LA,{isOpen:v,onClose:()=>{w(!1),k(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@undefined"}),D&&e.jsx(DA,{isOpen:S,onClose:()=>{_(!1),A(null)},onApprove:async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId,he=D.levelId;if(!he){K.error("Approval level not found");return}await an(ie,he,B),K.success("Request approved successfully"),W(),_(!1),A(null)}catch(ie){console.error("Failed to approve:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to approve request. Please try again.";throw K.error(he),ie}},onReject:async B=>{var Ie,xe;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ie=t.id||t.requestId,he=D.levelId;if(!he){K.error("Approval level not found");return}await Sr(ie,he,"Request rejected",B),K.success("Request rejected successfully"),W(),_(!1),A(null)}catch(ie){console.error("Failed to reject:",ie);const he=((xe=(Ie=ie==null?void 0:ie.response)==null?void 0:Ie.data)==null?void 0:xe.message)||(ie==null?void 0:ie.message)||"Failed to reject request. Please try again.";throw K.error(he),ie}},requestTitle:(t==null?void 0:t.title)||"Request",requestDescription:(t==null?void 0:t.description)||"",requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),levelName:D.levelName,approverName:D.approverName}),N&&N.length>0&&e.jsxs(ee,{className:"mt-6 border-amber-100 bg-amber-50/30",children:[e.jsxs(ge,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(fe,{className:"text-sm font-bold flex items-center gap-2 text-amber-900",children:[e.jsx(kt,{className:"w-4 h-4"}),"Revision History & Audit Trail"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>O(!R),className:"text-amber-700 hover:text-amber-800 hover:bg-amber-100",children:R?"Hide History":"View History"})]}),e.jsx($e,{className:"text-xs text-amber-700",children:"Records of all revisions and actions taken on this request"})]}),R&&e.jsx(se,{children:e.jsx("div",{className:"space-y-4",children:N.map((B,Ie)=>{var xe,ie,he,de;return e.jsxs("div",{className:"relative pl-6 pb-4 border-l-2 border-amber-200 last:border-0 last:pb-0",children:[e.jsx("div",{className:"absolute left-[-9px] top-0 w-4 h-4 rounded-full bg-amber-500 border-2 border-white shadow-sm"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs font-bold text-amber-900",children:["Version ",B.version]}),B.snapshotType&&e.jsx(ne,{className:"bg-blue-100 text-blue-700 text-[9px] px-1.5 py-0",children:B.snapshotType}),B.levelNumber&&e.jsxs(ne,{className:"bg-gray-100 text-gray-600 text-[9px] px-1.5 py-0",children:["Step ",B.levelNumber]})]}),e.jsx("span",{className:"text-[10px] text-amber-600 font-medium bg-amber-100 px-2 py-0.5 rounded-full",children:Cr(B.createdAt)})]}),e.jsx("p",{className:"text-xs font-medium text-gray-800",children:B.changeReason||"Version Update"}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[e.jsx("div",{className:"w-4 h-4 rounded-full bg-blue-100 flex items-center justify-center",children:e.jsx("span",{className:"text-[8px] font-bold text-blue-600",children:((ie=(xe=B.changer)==null?void 0:xe.displayName)==null?void 0:ie.charAt(0))||"U"})}),e.jsxs("span",{className:"text-xs text-gray-500",children:["By ",((he=B.changer)==null?void 0:he.displayName)||((de=B.changer)==null?void 0:de.email)||"Unknown User"]})]}),B.snapshotType==="PROPOSAL"&&B.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]",children:[e.jsx("p",{className:"font-semibold text-gray-700 mb-1",children:"Proposal:"}),B.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(E,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-small flex items-center gap-1",onClick:()=>T({data:B.snapshotData,type:"PROPOSAL",title:`Historical Proposal (Version ${B.version})`}),children:["View Details",e.jsx(ht,{className:"w-2 h-2"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Budget: ₹",Number(B.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),B.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",B.snapshotData.comments.substring(0,80),B.snapshotData.comments.length>80?"...":""]})]}),B.snapshotType==="COMPLETION"&&B.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]",children:[e.jsx("p",{className:"font-semibold text-gray-700 mb-1",children:"Completion:"}),B.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(E,{variant:"link",size:"sm",className:"h-auto p-0 text-blue-600 hover:text-blue-700 font-medium flex items-center gap-1",onClick:()=>T({data:B.snapshotData,type:"COMPLETION",title:`Historical Completion (Version ${B.version})`}),children:["View Details",e.jsx(ht,{className:"w-3 h-3"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Total Expenses: ₹",Number(B.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),B.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",B.snapshotData.comments.substring(0,80),B.snapshotData.comments.length>80?"...":""]})]}),B.snapshotType==="INTERNAL_ORDER"&&B.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]",children:[e.jsx("p",{className:"font-semibold text-gray-700 mb-1",children:"IO Block:"}),e.jsxs("p",{className:"text-gray-600",children:["IO Number: ",B.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-gray-600",children:["Blocked: ₹",Number(B.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),B.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-gray-600",children:["SAP Doc: ",B.snapshotData.sapDocumentNumber]})]}),B.snapshotType==="APPROVE"&&B.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]",children:[e.jsxs("p",{className:"font-semibold text-gray-700 mb-1",children:[B.snapshotData.action==="APPROVE"?"Approval":"Rejection",":"]}),e.jsxs("p",{className:"text-gray-600",children:["By: ",B.snapshotData.approverName||B.snapshotData.approverEmail||"Unknown"]}),B.snapshotData.levelName&&e.jsxs("p",{className:"text-gray-600",children:["Level: ",B.snapshotData.levelName]}),B.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",B.snapshotData.comments.substring(0,80),B.snapshotData.comments.length>80?"...":""]}),B.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-red-600 mt-1",children:["Rejection Reason: ",B.snapshotData.rejectionReason.substring(0,80),B.snapshotData.rejectionReason.length>80?"...":""]})]}),B.snapshotType==="WORKFLOW"&&B.snapshotData&&e.jsxs("div",{className:"mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]",children:[e.jsx("p",{className:"font-semibold text-gray-700 mb-1",children:"Workflow:"}),e.jsxs("p",{className:"text-gray-600",children:["Status: ",B.snapshotData.status||"N/A"]}),B.snapshotData.currentLevel&&e.jsxs("p",{className:"text-gray-600",children:["Current Level: ",B.snapshotData.currentLevel]})]})]})]},B.historyId||Ie)})})})]}),e.jsx($A,{isOpen:!!V,onClose:()=>T(null),snapshot:V==null?void 0:V.data,type:(V==null?void 0:V.type)||"PROPOSAL",title:V==null?void 0:V.title})]})}function QA({request:t,apiRequest:s,onRefresh:a}){const{user:r}=Kt(),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,l=(i==null?void 0:i.ioNumber)||(i==null?void 0:i.io_number)||(t==null?void 0:t.ioNumber)||"",o=(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)||"",h=(i==null?void 0:i.organizer)||null,x=(s==null?void 0:s.proposalDetails)||{},u=Number((x==null?void 0:x.totalEstimatedBudget)||(x==null?void 0:x.total_estimated_budget)||0),[g,b]=p.useState(l),[f,y]=p.useState(!1),[v,w]=p.useState(null),[C,k]=p.useState(""),[S,_]=p.useState(null),[D,A]=p.useState(!1);p.useEffect(()=>{if(i&&l){const R=Number(c)||0,O=(h==null?void 0:h.displayName)||(h==null?void 0:h.display_name)||(h==null?void 0:h.name)||(h!=null&&h.firstName&&(h!=null&&h.lastName)?`${h.firstName} ${h.lastName}`.trim():null)||(h==null?void 0:h.email)||"Unknown User";if(b(l),o>0){const F=Number(o)||0,$=Number(d)||0,V=R-F;Math.abs($-V)>.01&&console.warn("[IOTab] âš ī¸ Remaining balance calculation issue detected!",{availableBalance:R,blockedAmount:F,expectedRemaining:V,backendRemaining:$,difference:$-V}),_({ioNumber:l,blockedAmount:F,availableBalance:R,remainingBalance:$,blockedDate:i.organizedAt||i.organized_at||new Date().toISOString(),blockedBy:O,sapDocumentNumber:m,status:i.status==="BLOCKED"?"blocked":i.status==="RELEASED"?"released":"blocked"}),R>0&&w(R)}}},[i,l,o,c,d,m,h]);const N=async()=>{var R,O;if(!g.trim()){K.error("Please enter an IO number");return}if(!n){K.error("Request ID not found");return}y(!0);try{const F=await zA(n,g.trim());F.isValid&&F.availableBalance>0?(w(F.availableBalance),u>0?k(String(u)):k(String(F.availableBalance)),K.success(`IO fetched from SAP. Available balance: ₹${F.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`)):(K.error("Invalid IO number or no available balance found"),w(null),k(""))}catch(F){console.error("Failed to fetch IO budget:",F);const $=((O=(R=F==null?void 0:F.response)==null?void 0:R.data)==null?void 0:O.message)||(F==null?void 0:F.message)||"Failed to validate IO number or fetch budget from SAP";K.error($),w(null)}finally{y(!1)}},P=async()=>{var F,$;if(!g.trim()||v===null){K.error("Please fetch IO amount first");return}if(!n){K.error("Request ID not found");return}const R=parseFloat(C);if(!C||isNaN(R)||R<=0){K.error("Please enter a valid amount to block");return}const O=parseFloat(R.toFixed(2));if(O>v){K.error("Amount to block exceeds available IO budget");return}if(u>0){const V=parseFloat(u.toFixed(2));if(Math.abs(O-V)>.01){K.error(`Amount to block must be exactly equal to the estimated budget (₹${V.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})})`);return}}A(!0);try{const V=parseFloat(v.toFixed(2)),T=parseFloat((V-O).toFixed(2)),j={ioNumber:g.trim(),ioAvailableBalance:V,ioBlockedAmount:O,ioRemainingBalance:T};await Zp(n,j);const U=await UA(n),I=(U==null?void 0:U.internalOrder)||(U==null?void 0:U.internal_order);if(I){const M=Number(I.ioBlockedAmount||I.io_blocked_amount||O),W=Number(I.ioRemainingBalance||I.io_remaining_balance||0),G=v-M;Math.abs(M-O)>.01&&console.warn("[IOTab] âš ī¸ Amount mismatch! Sent:",O,"Saved:",M),Math.abs(W-G)>.01&&console.warn("[IOTab] âš ī¸ Remaining balance calculation issue detected!",{availableBalance:v,blockedAmount:M,expectedRemaining:G,backendRemaining:W,difference:W-G});const ce=r,te=(ce==null?void 0:ce.displayName)||(ce==null?void 0:ce.display_name)||(ce==null?void 0:ce.name)||(ce!=null&&ce.firstName&&(ce!=null&&ce.lastName)?`${ce.firstName} ${ce.lastName}`.trim():null)||(ce==null?void 0:ce.email)||"Current User",L={ioNumber:I.ioNumber||I.io_number||g,blockedAmount:M,availableBalance:v,remainingBalance:W,blockedDate:I.organizedAt||I.organized_at||new Date().toISOString(),blockedBy:te,sapDocumentNumber:I.sapDocumentNumber||I.sap_document_number||"",status:"blocked"};_(L),k(""),K.success("IO budget blocked successfully in SAP"),a==null||a()}else K.error("IO blocked but failed to fetch updated details"),a==null||a()}catch(V){console.error("Failed to block IO budget:",V);const T=(($=(F=V==null?void 0:V.response)==null?void 0:F.data)==null?void 0:$.message)||(V==null?void 0:V.message)||"Failed to block IO budget in SAP";K.error(T)}finally{A(!1)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx($e,{children:"Enter IO number to fetch available budget from SAP"})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Oe,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:g,onChange:R=>b(R.target.value),disabled:f||!!S,className:"flex-1"}),e.jsxs(E,{onClick:N,disabled:!g.trim()||f||!!S,className:"bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),f?"Fetching...":"Fetch Amount"]})]})]}),!v&&!S&&g.trim()&&e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",children:e.jsxs("p",{className:"text-sm text-blue-800",children:[e.jsx("strong",{children:"Next Step:"}),' Click "Fetch Amount" to validate the IO number and get available balance from SAP.']})}),v!==null&&!S&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-green-50 border-2 border-green-200 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600 uppercase tracking-wide mb-1",children:"Available Amount"}),e.jsxs("p",{className:"text-2xl font-bold text-green-700",children:["₹",v.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsx(De,{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:"})," ",g]}),e.jsxs("p",{className:"text-xs text-gray-600 mt-1",children:[e.jsx("strong",{children:"Fetched from:"})," SAP System"]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{htmlFor:"blockAmount",children:"Amount to Block *"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",children:"₹"}),e.jsx(Oe,{type:"number",id:"blockAmount",placeholder:"Enter amount to block",min:"0",step:"0.01",value:C,onChange:R=>k(R.target.value),className:"pl-8"})]}),u>0&&e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-xs text-amber-800",children:[e.jsx("strong",{children:"Required:"})," Amount must be exactly equal to the estimated budget: ",e.jsxs("strong",{children:["₹",u.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs(E,{onClick:P,disabled:D||!C||parseFloat(C)<=0||parseFloat(C)>v||u>0&&Math.abs(parseFloat(C)-u)>.01,className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Ot,{className:"w-4 h-4 mr-2"}),D?"Blocking in SAP...":"Block IO in SAP"]})]})]})]}),e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(De,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx($e,{children:"Details of IO blocked in SAP system"})]}),e.jsx(se,{children:S?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(De,{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:S.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:S.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:["₹",S.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:["₹",S.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:["₹",S.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:S.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(S.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(ne,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Blocked"]})]})]})]}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Da,{className:"w-16 h-16 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-500 mb-2",children:"No IO blocked yet"}),e.jsx("p",{className:"text-xs text-gray-400",children:"Enter IO number and fetch amount to block budget"})]})})]})]})}async function qA(t,s=10){var a;try{const r={limit:s};t&&(r.q=t);const n=await je.get("/dealers",{params:r});return((a=n.data)==null?void 0:a.data)||n.data||[]}catch(r){throw console.error("[DealerAPI] Error fetching dealers:",r),r}}async function eT(t){var s,a,r;try{const n=await je.get(`/dealers/verify/${t}`);return((s=n.data)==null?void 0:s.data)||n.data}catch(n){const i=((r=(a=n.response)==null?void 0:a.data)==null?void 0:r.message)||n.message||"Dealer verification failed";throw console.error("[DealerAPI] Error verifying dealer login:",i),new Error(i)}}const Fs=[{level:1,name:"Dealer Proposal Submission",description:"Dealer submits proposal documents",defaultTat:72,isAuto:!1,approverType:"dealer"},{level:2,name:"Requestor Evaluation",description:"Initiator evaluates dealer proposal",defaultTat:48,isAuto:!1,approverType:"initiator"},{level:3,name:"Department Lead Approval",description:"Department lead approves and blocks IO budget",defaultTat:72,isAuto:!1,approverType:"manual"},{level:4,name:"Dealer Completion Documents",description:"Dealer submits completion documents",defaultTat:120,isAuto:!1,approverType:"dealer"},{level:5,name:"Requestor Claim Approval",description:"Initiator approves completion",defaultTat:48,isAuto:!1,approverType:"initiator"}];function tT({formData:t,updateFormData:s,onValidationError:a,currentUserEmail:r="",currentUserId:n="",currentUserName:i="",onValidate:l,maxApprovalLevels:o,onPolicyViolation:c}){const{userSearchResults:d,userSearchLoading:m,searchUsersForIndex:h,clearSearchForIndex:x}=Pp(),[u,g]=p.useState(!1),[b,f]=p.useState(""),[y,v]=p.useState(24),[w,C]=p.useState("hours"),[k,S]=p.useState(3),[_,D]=p.useState([]),[A,N]=p.useState(!1),[P,R]=p.useState(null),O=p.useRef(null),F=()=>{const L=t.approvers||[],z=[];return Fs.forEach(H=>{if(H.isAuto||H.approverType==="dealer"||H.approverType==="initiator")return;const ye=L.find(ae=>ae.level===H.level);(!ye||!ye.email||!ye.userId||!ye.tat)&&z.push(`${H.name}`)}),{isValid:z.length===0,missingSteps:z}};p.useEffect(()=>{if(l){const L=F();l(L.isValid)}},[t.approvers]),p.useEffect(()=>{const L=t.approvers||[];if(L.length>0){const z=[],H=L.filter(ae=>ae.isAdditional);Fs.forEach(ae=>{const me=L.find(Q=>Q.originalStepLevel===ae.level||!Q.originalStepLevel&&!Q.isAdditional&&Q.level===ae.level);if(me)z.push(me);else if(ae.isAuto){const Q=ae.level===8?"finance@royalenfield.com":"system@royalenfield.com",oe=ae.level===8?"System/Finance":"System";z.push({email:Q,name:oe,level:ae.level,tat:ae.defaultTat,tatType:"hours",originalStepLevel:ae.level})}else ae.approverType==="dealer"?z.push({email:t.dealerEmail||"",name:t.dealerName||"",level:ae.level,tat:ae.defaultTat,tatType:"hours",originalStepLevel:ae.level}):ae.approverType==="initiator"?z.push({email:r||"",name:i||r||"User",userId:n,level:ae.level,tat:ae.defaultTat,tatType:"hours",originalStepLevel:ae.level}):z.push({email:"",name:"",level:ae.level,tat:ae.defaultTat,tatType:"hours",originalStepLevel:ae.level})}),H.forEach(ae=>{z.push(ae)}),z.sort((ae,me)=>ae.level-me.level),JSON.stringify(L.map(ae=>({level:ae.level,originalStepLevel:ae.originalStepLevel})))!==JSON.stringify(z.map(ae=>({level:ae.level,originalStepLevel:ae.originalStepLevel})))&&s("approvers",z)}else{const z=[];Fs.forEach(H=>{H.isAuto||(H.approverType==="dealer"?z.push({email:t.dealerEmail||"",name:t.dealerName||"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}):H.approverType==="initiator"?z.push({email:r||"",name:i||r||"User",userId:n,level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}):z.push({email:"",name:"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level}))}),s("approvers",z)}},[t.dealerEmail,t.dealerName,r,n,i]);const $=(L,z)=>{const H=[...t.approvers||[]],ye=H.findIndex(ae=>ae.originalStepLevel===L||!ae.originalStepLevel&&ae.level===L&&!ae.isAdditional);if(ye===-1){const ae=Fs.find(me=>me.level===L);H.push({email:z,name:"",level:L,tat:(ae==null?void 0:ae.defaultTat)||48,tatType:"hours",originalStepLevel:L})}else{const ae=H[ye];if(ae){const me=ae.email;H[ye]={...ae,email:z,name:z!==me?"":ae.name,userId:z!==me?void 0:ae.userId}}}if(s("approvers",H),!z||!z.startsWith("@")||z.length<2){x(L-1);return}h(L-1,z,10)},V=async(L,z)=>{var H,ye;try{const ae=Fs.find(be=>be.level===L);if(ae&&!ae.isAuto&&ae.approverType!=="initiator"&&((H=z.email)==null?void 0:H.toLowerCase())===(r==null?void 0:r.toLowerCase())){K.error(`You cannot assign yourself as ${ae.name} approver.`),a&&a({type:"self-assign",email:z.email,message:`You cannot assign yourself as ${ae.name} approver.`});return}if((t.approvers||[]).some(be=>{var q,ue;return be.level!==L&&(be.userId===z.userId||((q=be.email)==null?void 0:q.toLowerCase())===((ue=z.email)==null?void 0:ue.toLowerCase()))})){K.error("This user is already assigned to another step."),a&&a({type:"error",email:z.email,message:"This user is already assigned to another step."});return}const oe=await ra({userId:z.userId,email:z.email,displayName:z.displayName,firstName:z.firstName,lastName:z.lastName,department:z.department,phone:z.phone,mobilePhone:z.mobilePhone,designation:z.designation,jobTitle:z.jobTitle,manager:z.manager,employeeId:z.employeeId,employeeNumber:z.employeeNumber,secondEmail:z.secondEmail,location:z.location}),Ce=[...t.approvers||[]],Ee=Ce.findIndex(be=>be.originalStepLevel===L||!be.originalStepLevel&&be.level===L&&!be.isAdditional);if(Ee===-1){const be=Fs.find(q=>q.level===L);Ce.push({email:z.email,name:z.displayName||[z.firstName,z.lastName].filter(Boolean).join(" "),userId:oe.userId,level:L,tat:(be==null?void 0:be.defaultTat)||48,tatType:"hours",originalStepLevel:L})}else{const be=Ce[Ee];be&&(Ce[Ee]={...be,email:z.email,name:z.displayName||[z.firstName,z.lastName].filter(Boolean).join(" "),userId:oe.userId,originalStepLevel:be.originalStepLevel||L})}s("approvers",Ce),x(L-1),K.success(`Approver for ${(ye=Fs.find(be=>be.level===L))==null?void 0:ye.name} selected successfully.`)}catch(ae){console.error("Failed to ensure user exists:",ae),K.error("Failed to validate user. Please try again."),a&&a({type:"error",email:z.email,message:"Failed to validate user. Please try again."})}},T=(L,z)=>{const H=[...t.approvers||[]],ye=H.findIndex(ae=>ae.originalStepLevel===L||!ae.originalStepLevel&&ae.level===L&&!ae.isAdditional);if(ye!==-1){const ae=H[ye];ae&&(H[ye]={...ae,tat:z},s("approvers",H))}},j=(L,z)=>{const H=[...t.approvers||[]],ye=H.findIndex(ae=>ae.originalStepLevel===L||!ae.originalStepLevel&&ae.level===L&&!ae.isAdditional);if(ye!==-1){const ae=H[ye];ae&&(H[ye]={...ae,tatType:z,tat:""},s("approvers",H))}},U=L=>{if(f(L),P&&P.email.toLowerCase()!==L.toLowerCase()&&R(null),O.current&&clearTimeout(O.current),!L||!L.startsWith("@")||L.length<2){D([]),N(!1);return}N(!0),O.current=setTimeout(async()=>{var z;try{const H=L.slice(1),ae=((z=(await ia(H,10)).data)==null?void 0:z.data)||[];D(ae)}catch(H){console.error("Search failed:",H),D([])}finally{N(!1)}},300)},I=async L=>{try{await ra({userId:L.userId,email:L.email,displayName:L.displayName,firstName:L.firstName,lastName:L.lastName,department:L.department,phone:L.phone,mobilePhone:L.mobilePhone,designation:L.designation,jobTitle:L.jobTitle,manager:L.manager,employeeId:L.employeeId,employeeNumber:L.employeeNumber,secondEmail:L.secondEmail,location:L.location}),f(L.email),R(L),D([]),N(!1)}catch(z){console.error("Failed to ensure user exists:",z),K.error("Failed to verify user. Please try again.")}},M=async()=>{var q,ue;const L=b.trim().toLowerCase();if(!L){K.error("Please enter an email address");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(L)){K.error("Please enter a valid email address");return}const H=typeof y=="string"?Number(y):y;if(!H||H<=0||isNaN(H)){K.error("Please enter valid TAT (minimum 1)");return}const ye=w==="days"?30:720;if((w==="days"?H*24:H)>720){K.error(`TAT cannot exceed ${ye} ${w==="days"?"days":"hours"}`);return}const me=Fs.find(Ae=>Ae.name==="Requestor Claim Approval");if(me&&k>=me.level){K.error('Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.');return}if(L===(r==null?void 0:r.toLowerCase())){K.error("You cannot add yourself as an additional approver.");return}const Q=t.approvers||[];if(Q.some(Ae=>{var Ue;return Ae.userId&&(P==null?void 0:P.userId)&&Ae.userId===P.userId||((Ue=Ae.email)==null?void 0:Ue.toLowerCase())===L})){K.error("This user is already assigned as an approver.");return}const Ce=Q.find(Ae=>Ae.originalStepLevel===k||!Ae.originalStepLevel&&!Ae.isAdditional&&Ae.level===k),be=(Ce?Ce.level:k)+1;if(o){const Ue=new Set(Q.map(Z=>Z.level)).size+1;if(Ue>o){const Z=[{type:"max_approval_levels",message:`Adding this approver would create ${Ue} approval levels, which exceeds the maximum allowed (${o}). Please remove some approvers before adding a new one.`,currentValue:Ue,maxValue:o}];c?c(Z):K.error(((q=Z[0])==null?void 0:q.message)||"Maximum approval levels exceeded");return}}if(!P||P.email.toLowerCase()!==L)try{const Ue=((ue=(await ia(L,1)).data)==null?void 0:ue.data)||[];if(Ue.length===0){K.error("User not found in organization directory. Please use @ to search for users.");return}const Z=Ue[0];await ra({userId:Z.userId,email:Z.email,displayName:Z.displayName,firstName:Z.firstName,lastName:Z.lastName,department:Z.department,phone:Z.phone,mobilePhone:Z.mobilePhone,designation:Z.designation,jobTitle:Z.jobTitle,manager:Z.manager,employeeId:Z.employeeId,employeeNumber:Z.employeeNumber,secondEmail:Z.secondEmail,location:Z.location});const Te={email:Z.email,name:Z.displayName||[Z.firstName,Z.lastName].filter(Boolean).join(" "),userId:Z.userId,level:be,tat:typeof y=="string"?Number(y):y,tatType:w,isAdditional:!0,insertAfterLevel:k,stepName:`Additional Approver - ${Z.displayName||Z.email}`},Xe=Q.map(pe=>pe.level>=be?{...pe,level:pe.level+1}:pe);Xe.push(Te),Xe.sort((pe,_e)=>pe.level-_e.level),s("approvers",Xe),K.success("Additional approver added and subsequent steps shifted")}catch(Ae){console.error("Failed to validate approver:",Ae),K.error("Failed to validate user. Please try again.");return}else{const Ae={email:P.email,name:P.displayName||[P.firstName,P.lastName].filter(Boolean).join(" "),userId:P.userId,level:be,tat:y,tatType:w,isAdditional:!0,insertAfterLevel:k,stepName:`Additional Approver - ${P.displayName||P.email}`},Ue=Q.map(Z=>Z.level>=be?{...Z,level:Z.level+1}:Z);Ue.push(Ae),Ue.sort((Z,Te)=>Z.level-Te.level),s("approvers",Ue),K.success("Additional approver added and subsequent steps shifted")}f(""),v(24),C("hours"),S(3),R(null),D([]),g(!1)},W=L=>{const z=[...t.approvers||[]];if(!z.find(me=>me.level===L))return;const ae=z.filter(me=>me.level!==L).map(me=>me.level>L&&!me.isAdditional?{...me,level:me.level-1}:me);ae.sort((me,Q)=>me.level-Q.level),s("approvers",ae),K.success("Additional approver removed and subsequent steps shifted back")},G=()=>[...t.approvers||[]].sort((z,H)=>z.level-H.level),ce=t.approvers||[],te=G();return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-purple-500 to-indigo-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(cs,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Approver Selection"}),e.jsx("p",{className:"text-gray-600",children:"Assign approvers for workflow steps with TAT (Turn Around Time)"})]}),e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(ee,{className:"border-2 border-blue-200 bg-blue-50",children:e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-blue-900",children:[e.jsx(Ur,{className:"w-5 h-5"}),"Workflow Steps Information"]}),e.jsxs($e,{className:"text-blue-700",children:['Some steps are pre-filled (Dealer, Initiator, System). You need to assign approvers for "Department Lead Approval" only. Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.',o&&e.jsxs("span",{className:"block mt-2 text-gray-600",children:["Max: ",o," level",o!==1?"s":"",(()=>{const L=t.approvers||[],H=new Set(L.map(ye=>ye.level)).size;return H>0?e.jsxs("span",{children:[" (",H,"/",o,")"]}):null})()]})]})]})}),e.jsxs(ee,{className:"border-2",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-5 h-5"}),"Approval Hierarchy"]}),e.jsx($e,{children:'Define approvers and TAT for each step. Some steps are pre-filled (Dealer, Initiator, System). Only "Department Lead Approval" requires manual assignment.'})]}),e.jsxs(se,{className:"space-y-2 pt-4",children:[e.jsxs("div",{className:"mb-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2",children:[o&&e.jsxs("p",{className:"text-sm text-gray-600",children:["Max: ",o," level",o!==1?"s":"",(()=>{const L=t.approvers||[],H=new Set(L.map(ye=>ye.level)).size;return H>0?e.jsxs("span",{children:[" (",H,"/",o,")"]}):null})()]}),e.jsxs(E,{type:"button",variant:"outline",onClick:()=>g(!0),className:"flex items-center gap-2",children:[e.jsx(gs,{className:"w-4 h-4"}),"Add Additional Approver"]})]}),e.jsx("div",{className:"p-3 rounded-lg border-2 border-blue-200 bg-blue-50",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center flex-shrink-0",children:e.jsx(Vt,{className:"w-4 h-4 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-blue-900 text-sm",children:"Request Initiator"}),e.jsx(ne,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-xs text-blue-700",children:"Creates and submits the request"})]})]})}),(()=>{const L=te.filter(H=>H.isAdditional&&H.insertAfterLevel===0);let z=L.length;return Fs.filter(H=>!H.isAuto).map((H,ye,ae)=>{const me=ce.find(q=>q.originalStepLevel===H.level||!q.originalStepLevel&&q.level===H.level&&!q.isAdditional)||{email:"",name:"",level:H.level,tat:H.defaultTat,tatType:"hours",originalStepLevel:H.level},Q=ye===ae.length-1,oe=H.isAuto||H.approverType==="dealer"||H.approverType==="initiator",Ce=!H.isAuto,Ee=te.filter(q=>q.isAdditional&&q.insertAfterLevel===H.level).sort((q,ue)=>q.level-ue.level),be=z+1;return z++,z+=Ee.length,e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-3 bg-gray-300"})}),ye===0&&L.map((q,ue)=>{const Ae=ue+1;return e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-3 bg-gray-300"})}),e.jsx("div",{className:"p-3 rounded-lg border-2 border-purple-200 bg-purple-50",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 bg-purple-600",children:e.jsx("span",{className:"text-white font-semibold text-sm",children:Ae})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-sm",children:"Additional Approver"}),e.jsx(ne,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>W(q.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(ft,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:q.name||q.email}),e.jsxs("div",{className:"text-xs text-gray-500",children:[e.jsxs("div",{children:["Email: ",q.email]}),e.jsxs("div",{children:["TAT: ",q.tat," ",q.tatType]})]})]})]})})]},`additional-${q.level}`)}),e.jsx("div",{className:`p-3 rounded-lg border-2 transition-all ${me.email&&me.userId?"border-green-200 bg-green-50":oe?"border-blue-200 bg-blue-50":"border-gray-200 bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${me.email&&me.userId?"bg-green-600":oe?"bg-blue-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold text-sm",children:be})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-sm",children:H.name}),Q&&e.jsx(ne,{variant:"destructive",className:"text-xs",children:"FINAL"}),oe&&e.jsx(ne,{variant:"outline",className:"text-xs",children:"PRE-FILLED"})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:H.description}),Ce&&(()=>{var Ae,Ue;const q=!!(me.email&&me.userId),ue=!me.email&&!oe;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs(re,{htmlFor:`approver-${H.level}`,className:`text-xs font-bold ${ue?"text-blue-900":q?"text-green-900":"text-gray-900"}`,children:["Approver Email ",!oe&&"*",ue&&e.jsx("span",{className:"ml-2 text-[10px] font-semibold italic text-blue-600",children:"(Required)"})]}),q&&e.jsxs(ne,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Oe,{id:`approver-${H.level}`,type:"text",placeholder:oe?me.email:"@username or email...",value:me.email||"",onChange:Z=>{const Te=Z.target.value;oe||$(H.level,Te)},disabled:oe||H.isAuto,className:`h-9 border-2 transition-all mt-1 w-full text-sm ${oe?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":q?"bg-green-50/50 border-green-600 focus:border-green-700 ring-offset-green-50 focus:ring-1 focus:ring-green-100 font-semibold text-gray-900":"bg-white border-blue-300 shadow-sm shadow-blue-100/50 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900"}`}),!oe&&!H.isAuto&&(m[H.level-1]||(((Ae=d[H.level-1])==null?void 0:Ae.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:m[H.level-1]?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:(Ue=d[H.level-1])==null?void 0:Ue.map(Z=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>V(H.level,Z),children:[e.jsx("div",{className:"font-medium text-gray-900",children:Z.displayName||Z.email}),e.jsx("div",{className:"text-xs text-gray-600",children:Z.email}),Z.department&&e.jsx("div",{className:"text-xs text-gray-500",children:Z.department})]},Z.userId))})})]}),me.name&&e.jsxs("p",{className:"text-xs text-green-600 mt-1",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:me.name})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:`tat-${H.level}`,className:`text-xs font-bold ${ue?"text-blue-900":q?"text-green-900":"text-gray-900"}`,children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Oe,{id:`tat-${H.level}`,type:"number",placeholder:me.tatType==="days"?"7":"24",min:"1",max:me.tatType==="days"?"30":"720",value:me.tat||"",onChange:Z=>T(H.level,parseInt(Z.target.value)||""),disabled:H.isAuto,className:`h-9 border-2 transition-all flex-1 text-sm ${oe?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":q?"bg-green-50/50 border-green-600 focus:border-green-700 focus:ring-1 focus:ring-green-100 font-semibold text-gray-900":"bg-white border-blue-300 shadow-sm shadow-blue-100/50 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900"}`}),e.jsxs(We,{value:me.tatType||"hours",onValueChange:Z=>j(H.level,Z),disabled:H.isAuto,children:[e.jsx(Ye,{className:`w-20 h-9 border-2 transition-all text-sm ${oe?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed":q?"bg-green-50/50 border-green-600 focus:border-green-700 focus:ring-1 focus:ring-green-100 text-gray-900 font-medium":"bg-white border-blue-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900"}`,children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]})]})]})})()]})]})}),Ee.map((q,ue)=>{const Ae=be+ue+1;return e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-3 bg-gray-300"})}),e.jsx("div",{className:"p-3 rounded-lg border-2 border-purple-200 bg-purple-50",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 bg-purple-600",children:e.jsx("span",{className:"text-white font-semibold text-sm",children:Ae})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-sm",children:q.stepName||"Additional Approver"}),e.jsx(ne,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),q.email&&q.userId&&e.jsxs(ne,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Verified"]}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>W(q.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(ft,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:q.name||q.email||"No approver assigned"}),q.email&&e.jsxs("div",{className:"text-xs text-gray-500 space-y-1",children:[e.jsxs("div",{children:["Email: ",q.email]}),q.tat&&e.jsxs("div",{children:["TAT: ",q.tat," ",q.tatType]})]})]})]})})]},`additional-${q.level}`)})]},H.level)})})()]})]}),e.jsxs(ee,{className:"border-2",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(st,{className:"w-5 h-5"}),"TAT Summary"]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3",children:te.map(L=>{const z=L.originalStepLevel?Fs.find(me=>me.level===L.originalStepLevel):Fs.find(me=>me.level===L.level&&!L.isAdditional);if(z!=null&&z.isAuto)return null;const H=Number(L.tat||0),ae=(L.tatType||"hours")==="days"?H*24:H;if(!H)return null;if(L.isAdditional){const me=Fs.find(Q=>Q.level===L.insertAfterLevel);return e.jsxs("div",{className:"flex items-center justify-between p-2 bg-purple-50 rounded border border-purple-200",children:[e.jsx("span",{className:"text-sm font-medium",children:L.stepName||`Additional Approver (after "${(me==null?void 0:me.name)||"Unknown"}")`}),e.jsxs("span",{className:"text-sm text-gray-600",children:[ae," hours"]})]},L.level)}return e.jsxs("div",{className:"flex items-center justify-between p-2 bg-gray-50 rounded",children:[e.jsx("span",{className:"text-sm font-medium",children:(z==null?void 0:z.name)||"Unknown"}),e.jsxs("span",{className:"text-sm text-gray-600",children:[ae," hours"]})]},L.level)})})})]})]}),e.jsx(pt,{open:u,onOpenChange:g,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(gs,{className:"w-5 h-5 text-blue-600"}),"Add Additional Approver"]}),e.jsx(Dt,{children:'Add an additional approver between workflow steps. The approver will be inserted after the selected step. Additional approvers cannot be added after "Requestor Claim Approval".'})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Insert After Step *"}),e.jsxs(We,{value:k.toString(),onValueChange:L=>S(Number(L)),children:[e.jsx(Ye,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select step"})}),e.jsx(Ke,{children:Fs.filter(L=>{if(L.isAuto)return!1;const z=Fs.find(H=>H.name==="Requestor Claim Approval");return!(z&&L.level>=z.level)}).map(L=>e.jsx(Y,{value:L.level.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:L.name})]})},L.level))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"The new approver will be inserted after the selected step."}),e.jsx("p",{className:"text-xs text-amber-600 font-medium",children:'âš ī¸ Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.'}),o&&e.jsxs("p",{className:"text-xs text-gray-600 mt-2",children:["Max: ",o," level",o!==1?"s":"",(()=>{const L=t.approvers||[],H=new Set(L.map(ye=>ye.level)).size;return H>0?e.jsxs("span",{children:[" (",H,"/",o,")"]}):null})()]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{type:"number",min:"1",max:w==="days"?"30":"720",value:y,onChange:L=>{const z=L.target.value;if(z==="")v("");else{const H=Number(z);!isNaN(H)&&H>=0&&v(H)}},onBlur:L=>{const z=L.target.value;(!z||z===""||Number(z)<=0)&&v(24)},className:"h-11 border-gray-300 flex-1",placeholder:"24"}),e.jsxs(We,{value:w,onValueChange:L=>C(L),children:[e.jsx(Ye,{className:"w-24 h-11 border-gray-300",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Maximum time for this approver to respond (1-",w==="days"?"30 days":"720 hours",")"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ci,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Oe,{type:"text",placeholder:"@username or user@example.com",value:b,onChange:L=>U(L.target.value),className:"pl-10 h-11 border-gray-300",autoFocus:!0}),(A||_.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:A?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):_.length>0?e.jsx("ul",{className:"divide-y",children:_.map(L=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>I(L),children:e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:L.displayName||[L.firstName,L.lastName].filter(Boolean).join(" ")||L.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:L.email}),L.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:L.designation})]})})},L.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(Tt,{children:[e.jsx(E,{type:"button",variant:"outline",onClick:()=>{g(!1),f(""),v(24),C("hours"),S(3),R(null),D([])},className:"flex-1",children:"Cancel"}),e.jsxs(E,{type:"button",onClick:M,className:"flex-1 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:!b.trim()||!y,children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Add Approver"]})]})]})})]})}const Nl=[{level:1,name:"Dealer Proposal Submission",description:"Dealer submits proposal documents",defaultTat:72,isAuto:!1,approverType:"dealer"},{level:2,name:"Requestor Evaluation",description:"Initiator evaluates dealer proposal",defaultTat:48,isAuto:!1,approverType:"initiator"},{level:3,name:"Department Lead Approval",description:"Department lead approves and blocks IO budget",defaultTat:72,isAuto:!1,approverType:"manual"},{level:4,name:"Activity Creation",description:"System auto-processes activity creation",defaultTat:1,isAuto:!0,approverType:"system"},{level:5,name:"Dealer Completion Documents",description:"Dealer submits completion documents",defaultTat:120,isAuto:!1,approverType:"dealer"},{level:6,name:"Requestor Claim Approval",description:"Initiator approves completion",defaultTat:48,isAuto:!1,approverType:"initiator"},{level:7,name:"E-Invoice Generation",description:"System generates e-invoice via DMS",defaultTat:1,isAuto:!0,approverType:"system"},{level:8,name:"Credit Note Confirmation",description:"System/Finance processes credit note confirmation",defaultTat:48,isAuto:!0,approverType:"system"}],wl=["Claim Details","Approver Selection","Review & Submit"];function sT({onBack:t,onSubmit:s}){const{user:a}=Kt(),[r,n]=p.useState(1),[i,l]=p.useState(!1),[o,c]=p.useState([]),[d,m]=p.useState(!1),[h,x]=p.useState(""),u=p.useRef(null),[g,b]=p.useState(!1),f=p.useRef(null),[y,v]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[w,C]=p.useState({open:!1,violations:[]}),[k,S]=p.useState([]),[_,D]=p.useState(!0);p.useEffect(()=>{(async()=>{try{D(!0);const M=await sS();S(M)}catch(M){console.error("Failed to load activity types:",M),K.error("Failed to load activity types. Please refresh the page.")}finally{D(!1)}})()},[]),p.useEffect(()=>{(async()=>{var M;try{const W=await Ys("SYSTEM_SETTINGS"),G=await Ys("WORKFLOW_SHARING"),ce=[...W,...G],te={};ce.forEach(L=>{te[L.configKey]=L.configValue}),v({maxApprovalLevels:parseInt(te.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(te.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((M=te.ALLOW_ADD_SPECTATOR)==null?void 0:M.toLowerCase())==="true",maxSpectators:parseInt(te.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(W){console.error("Failed to load system policy:",W)}})()},[]),p.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const[A,N]=p.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:"",approvers:[]}),P=wl.length,R=I=>{if(x(I),u.current&&clearTimeout(u.current),!I||I.trim().length<2){c([]),m(!1);return}m(!0),u.current=setTimeout(async()=>{try{const M=await qA(I,10);c(M)}catch(M){console.error("Error searching dealers:",M),c([])}finally{m(!1)}},300)},O=(I,M)=>{N(W=>{const G={...W,[I]:M};if(I==="periodStartDate")M&&G.periodEndDate&&M>G.periodEndDate&&(G.periodEndDate=void 0,K.error("End date must be on or after the start date. End date has been cleared."));else if(I==="periodEndDate"&&M&&G.periodStartDate&&M{switch(r){case 1:return A.activityName&&A.activityType&&A.dealerCode&&A.dealerName&&A.activityDate&&A.location&&A.requestDescription;case 2:const M=(A.approvers||[]).find(W=>W.originalStepLevel===3||!W.originalStepLevel&&W.level===3&&!W.isAdditional);return(M==null?void 0:M.email)&&(M==null?void 0:M.userId)&&(M==null?void 0:M.tat);case 3:return!0;default:return!1}},$=()=>{if(rG.originalStepLevel===3||!G.originalStepLevel&&G.level===3&&!G.isAdditional),W=[];(!(M!=null&&M.email)||!(M!=null&&M.userId)||!(M!=null&&M.tat))&&W.push("Department Lead Approval"),W.length>0?K.error(`Please add missing approvers: ${W.join(", ")}`):K.error("Please complete all required approver selections (email, user verification, and TAT) before proceeding.")}else K.error("Please complete all required fields before proceeding.");return}n(r+1)}},V=()=>{r>1&&n(r-1)},T=async I=>{l(!0);try{const M=await eT(I.dealerCode);if(!M.isLoggedIn){K.error(`Dealer "${M.dealerName||M.displayName}" (${M.dealerCode}) is not mapped to the system.`,{duration:5e3}),x(""),c([]),O("dealerCode",""),O("dealerName",""),O("dealerEmail",""),O("dealerPhone",""),O("dealerAddress",""),l(!1);return}O("dealerCode",M.dealerCode),O("dealerName",M.dealerName||M.displayName),O("dealerEmail",M.email||""),O("dealerPhone",M.phone||""),O("dealerAddress",""),x(M.dealerName||M.displayName),c([]),K.success(`Dealer "${M.dealerName||M.displayName}" verified and mapped to the System`)}catch{K.error("Dealer is not mapped to the system",{duration:5e3}),x(""),c([]),O("dealerCode",""),O("dealerName",""),O("dealerEmail",""),O("dealerPhone",""),O("dealerAddress","")}finally{l(!1)}},j=()=>{if(g)return;const M=[...A.approvers||[]].sort((L,z)=>L.level-z.level),W=new Map,G=[];if(M.forEach(L=>{W.has(L.level)?G.push(L.level):W.set(L.level,L)}),G.length>0){K.error(`Duplicate approver levels detected: ${G.join(", ")}. Please refresh and try again.`),console.error("Duplicate levels found:",G,M);return}const ce=M.map(L=>{const z={email:L.email,name:L.name,userId:L.userId,level:L.level,tat:L.tat,tatType:L.tatType};return L.isAdditional&&L.stepName&&(z.stepName=L.stepName,z.isAdditional=!0),L.originalStepLevel&&(z.originalStepLevel=L.originalStepLevel),z}),te={...A,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",approvers:ce};if(b(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{b(!1),f.current=null},3e4),s)try{s(te)}catch(L){f.current&&(clearTimeout(f.current),f.current=null),b(!1),console.error("Error submitting claim:",L)}else f.current&&(clearTimeout(f.current),f.current=null),b(!1)},U=()=>{switch(r){case 1:return e.jsxs(ts.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(Gt,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Claim Details"}),e.jsx("p",{className:"text-gray-600",children:"Provide comprehensive information about your claim request"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(Oe,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:A.activityName,onChange:I=>O("activityName",I.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(We,{value:A.activityType,onValueChange:I=>O("activityType",I),disabled:_,children:[e.jsx(Ye,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(Ge,{placeholder:_?"Loading activity types...":"Select activity type"})}),e.jsx(Ke,{children:k.length>0?k.map(I=>e.jsx(Y,{value:I.title,children:I.title},I.activityTypeId)):e.jsx("div",{className:"px-2 py-1.5 text-sm text-gray-500 text-center",children:"No activity types available"})})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Dealer Code / Dealer Name *"}),e.jsx("div",{className:"mt-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Oe,{placeholder:"Type dealer code, name, or email to search...",value:A.dealerCode?`${A.dealerName} (${A.dealerCode})`:h,onChange:I=>{A.dealerCode?(O("dealerCode",""),O("dealerName",""),O("dealerEmail",""),O("dealerPhone",""),O("dealerAddress",""),x(I.target.value)):R(I.target.value)},onFocus:()=>{h&&h.length>=2&&R(h)},className:"h-12 border-2 border-gray-300 focus:border-blue-500",disabled:i}),A.dealerCode&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsxs(ne,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Verified"]})}),(d||o.length>0)&&!A.dealerCode&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:d?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:o.map(I=>e.jsx("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>T(I),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-gray-900",children:I.dealerName||I.displayName}),e.jsxs("div",{className:"text-xs text-gray-600",children:[e.jsx("span",{className:"font-mono",children:I.dealerCode}),I.email&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1",children:"â€ĸ"}),e.jsx("span",{children:I.email})]})]}),I.city&&I.state&&e.jsxs("div",{className:"text-xs text-gray-500",children:[I.city,", ",I.state]})]}),e.jsx("div",{className:"ml-2 flex-shrink-0",children:I.isLoggedIn?e.jsx(De,{className:"w-4 h-4 text-green-600"}):e.jsx(wt,{className:"w-4 h-4 text-red-500"})})]})},I.dealerId))})})]})}),A.dealerCode&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:A.dealerName})," (",A.dealerCode,")"]}),A.dealerEmail&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Email: ",A.dealerEmail]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(Hs,{children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(ot,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:A.activityDate?He(A.activityDate,"d MMM yyyy"):"Select date"})]})}),e.jsx(Gs,{className:"w-auto p-0",align:"start",children:e.jsx(Yn,{mode:"single",selected:A.activityDate,onSelect:I=>O("activityDate",I),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(Oe,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:A.location,onChange:I=>O("location",I.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"requestDescription",className:"text-base font-semibold",children:"Request in Detail - Brief Requirement *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(Rn,{value:A.requestDescription||"",onChange:I=>O("requestDescription",I),placeholder:"Provide comprehensive details about your claim requirement including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(re,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(ne,{variant:"secondary",className:"text-xs",children:"Optional"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(Hs,{children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(ot,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:A.periodStartDate?He(A.periodStartDate,"d MMM yyyy"):"Start date"})]})}),e.jsx(Gs,{className:"w-auto p-0",align:"start",children:e.jsx(Yn,{mode:"single",selected:A.periodStartDate,onSelect:I=>O("periodStartDate",I),initialFocus:!0,toDate:A.periodEndDate||void 0})})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(Hs,{children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",disabled:!A.periodStartDate,children:[e.jsx(ot,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:A.periodEndDate?He(A.periodEndDate,"d MMM yyyy"):"End date"})]})}),e.jsx(Gs,{className:"w-auto p-0",align:"start",children:e.jsx(Yn,{mode:"single",selected:A.periodEndDate,onSelect:I=>O("periodEndDate",I),initialFocus:!0,fromDate:A.periodStartDate||void 0})})]}),!A.periodStartDate&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Please select start date first"})]})]}),(A.periodStartDate||A.periodEndDate)&&e.jsx("div",{className:"mt-2",children:A.periodStartDate&&A.periodEndDate?e.jsxs("p",{className:"text-xs text-gray-600",children:["Period: ",He(A.periodStartDate,"d MMM yyyy")," - ",He(A.periodEndDate,"d MMM yyyy")]}):e.jsx("p",{className:"text-xs text-gray-500",children:A.periodStartDate?"Please select end date for the period":"Please select start date first"})})]})]})]});case 2:return e.jsx(tT,{formData:A,updateFormData:O,currentUserEmail:(a==null?void 0:a.email)||"",currentUserId:(a==null?void 0:a.userId)||"",currentUserName:(a==null?void 0:a.displayName)||(a==null?void 0:a.name)||(a!=null&&a.firstName&&(a!=null&&a.lastName)?`${a.firstName} ${a.lastName}`.trim():(a==null?void 0:a.email)||"User"),maxApprovalLevels:y.maxApprovalLevels,onPolicyViolation:I=>C({open:!0,violations:I})});case 3:return e.jsxs(ts.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(De,{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(ee,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Gt,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:A.activityName})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(ne,{variant:"secondary",className:"mt-1",children:A.activityType})]})]})})]}),e.jsxs(ee,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Si,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1 font-mono",children:A.dealerCode})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:A.dealerName})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:A.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:A.dealerPhone})]}),A.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:A.dealerAddress})]})]})})]}),e.jsxs(ee,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-purple-50 to-indigo-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-5 h-5 text-purple-600"}),"Selected Approvers"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsx("div",{className:"space-y-3",children:[...A.approvers||[]].filter(M=>{var W,G;return!((W=M.email)!=null&&W.includes("system@"))&&!((G=M.email)!=null&&G.includes("finance@"))}).sort((M,W)=>M.level-W.level).map(M=>{const W=Number(M.tat||0),ce=(M.tatType||"hours")==="days"?W*24:W;let te="Unknown",L="";if(M.isAdditional){te=M.stepName||"Additional Approver";const z=Nl.find(H=>H.level===M.insertAfterLevel);L=M.stepName||`Additional Approver (after "${(z==null?void 0:z.name)||"Unknown"}")`}else{const z=M.originalStepLevel?Nl.find(H=>H.level===M.originalStepLevel):Nl.find(H=>H.level===M.level&&!H.isAuto);te=(z==null?void 0:z.name)||"Unknown",L=te}return e.jsx("div",{className:`p-3 rounded-lg border ${M.isAdditional?"bg-purple-50 border-purple-200":"bg-gray-50 border-gray-200"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:L}),M.isAdditional&&e.jsx(ne,{variant:"outline",className:"text-xs bg-purple-100 text-purple-700 border-purple-300",children:"ADDITIONAL"})]}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:M.name||M.email||"Not selected"}),M.email&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:M.email})]}),e.jsxs("div",{className:"text-right ml-4",children:[e.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:[ce," hours"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"TAT"})]})]})},`${M.level}-${M.email}`)})})})]}),e.jsxs(ee,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(ot,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:A.activityDate?He(A.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Location"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(po,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:A.location})]})]}),A.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Estimated Budget"}),e.jsx("p",{className:"text-xl font-bold text-blue-900 mt-1",children:A.estimatedBudget})]})]})})]}),e.jsxs(ee,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Brief Requirement"}),e.jsx("div",{className:"mt-2 p-4 bg-gray-50 rounded-lg border",children:e.jsx(sa,{content:A.requestDescription||"",className:"text-sm"})})]})})]}),(A.periodStartDate||A.periodEndDate)&&e.jsxs(ee,{className:"border-2",children:[e.jsx(ge,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(st,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(se,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:A.periodStartDate?He(A.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:A.periodEndDate?He(A.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(Ur,{className:"w-6 h-6 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-blue-900 mb-1",children:"Ready to Submit"}),e.jsx("p",{className:"text-sm text-blue-800",children:"Please review all the information above. Once submitted, your claim request will enter the approval workflow."})]})]})})]})]});default:return null}};return e.jsxs("div",{className:"w-full bg-gradient-to-br from-gray-50 to-gray-100 py-4 sm:py-6 lg:py-8 px-3 sm:px-4 lg:px-6 overflow-y-auto",children:[e.jsxs("div",{className:"max-w-6xl mx-auto pb-8",children:[e.jsxs("div",{className:"mb-6 sm:mb-8",children:[e.jsxs(E,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(Ns,{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(ne,{variant:"secondary",className:"mb-2 text-xs",children:"Claim Management Template"}),e.jsx("h1",{className:"text-xl sm:text-2xl lg:text-3xl font-bold text-gray-900",children:"New Claim Request"}),e.jsxs("p",{className:"text-sm sm:text-base text-gray-600 mt-1",children:["Step ",r," of ",P,": ",e.jsx("span",{className:"hidden sm:inline",children:wl[r-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(na,{value:r/P*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:wl.map((I,M)=>e.jsx("span",{className:`text-xs sm:text-sm ${M+1<=r?"text-blue-600 font-medium":"text-gray-400"}`,children:M+1},M))})]})]}),e.jsx(ee,{className:"mb-6 sm:mb-8",children:e.jsx(se,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(Ei,{mode:"wait",children:U()})})}),e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between gap-3 sm:gap-0 pb-4 sm:pb-0",children:[e.jsxs(E,{variant:"outline",onClick:V,disabled:r===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(Ns,{className:"w-4 h-4"}),"Previous"]}),rC({open:!1,violations:[]}),violations:w.violations,policyDetails:{maxApprovalLevels:y.maxApprovalLevels,maxParticipants:y.maxParticipants,allowSpectators:y.allowSpectators,maxSpectators:y.maxSpectators}})]})}const{DocumentsTab:aT,ActivityTab:rT,WorkNotesTab:nT,SummaryTab:iT,RequestDetailHeader:lT,QuickActionsSidebar:oT,RequestDetailModals:cT}=Wp;let dT=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("Dealer Claim RequestDetail Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(as,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(E,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(E,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function mT({requestId:t,onBack:s,dynamicRequests:a=[]}){var It,ns,Os,sr,ar,oa;const n=Ea().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=p.useState(l),[d,m]=p.useState(!1),[h,x]=p.useState(null),[u,g]=p.useState(null),[b,f]=p.useState(!1),[y,v]=p.useState(0),[w,C]=p.useState(!1),[k,S]=p.useState(!1),[_,D]=p.useState(!1),[A,N]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[P,R]=p.useState({open:!1,violations:[]}),{user:O}=Kt(),{request:F,apiRequest:$,loading:V,refreshing:T,refreshDetails:j,currentApprovalLevel:U,isSpectator:I,isInitiator:M,existingParticipants:W,accessDenied:G}=hc(n,a,O),ce=(O==null?void 0:O.userId)||"",te=M,{mergedMessages:L,unreadWorkNotes:z,workNoteAttachments:H,setWorkNoteAttachments:ye}=Ip(n,$,o,O),{uploadingDocument:ae,triggerFileInput:me,previewDocument:Q,setPreviewDocument:oe,documentPolicy:Ce,documentError:Ee,setDocumentError:be}=Ep($,j),[q,ue]=p.useState(null),Ae=q||U,{showApproveModal:Ue,setShowApproveModal:Z,showRejectModal:Te,setShowRejectModal:Xe,showAddApproverModal:pe,setShowAddApproverModal:_e,showAddSpectatorModal:rt,setShowAddSpectatorModal:ut,showSkipApproverModal:nt,setShowSkipApproverModal:Ps,showActionStatusModal:Xs,setShowActionStatusModal:Na,skipApproverData:Xa,setSkipApproverData:X,actionStatus:we,setActionStatus:J,handleApproveConfirm:Le,handleRejectConfirm:Fe,handleAddApprover:Ve,handleSkipApprover:Me,handleAddSpectator:Ze}=_p(n,Ae,j),Be=async vt=>{await Le(vt),ue(null)},qe=async vt=>{await Fe(vt),ue(null)},fs=((F==null?void 0:F.status)||($==null?void 0:$.status)||"").toLowerCase(),Ht=(fs==="approved"||fs==="rejected")&&M,{conclusionRemark:at,setConclusionRemark:et,conclusionLoading:yt,conclusionSubmitting:rs,aiGenerated:Pt,handleGenerateConclusion:la,handleFinalizeConclusion:pa,generationAttempts:Fa,generationFailed:wa,maxAttemptsReached:St}=Fp(F,n,M,j,s,J,Na);p.useEffect(()=>{(async()=>{var is;try{const Is=await Ys("SYSTEM_SETTINGS"),Zs=await Ys("WORKFLOW_SHARING"),Nr=[...Is,...Zs],ca={};Nr.forEach(Ma=>{ca[Ma.configKey]=Ma.configValue}),N({maxApprovalLevels:parseInt(ca.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(ca.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((is=ca.ALLOW_ADD_SPECTATOR)==null?void 0:is.toLowerCase())==="true",maxSpectators:parseInt(ca.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(Is){console.error("Failed to load system policy:",Is)}})()},[]),p.useEffect(()=>{const is=new URLSearchParams(window.location.search).get("tab");is&&c(is)},[n]);const Ca=()=>{j()},Za=()=>{C(!0)},Ja=()=>{S(!0)},Qa=async()=>{await j()},qa=()=>{D(!0)},er=async()=>{await j()},tr=async()=>{await j()},_a=async()=>{if(!($!=null&&$.requestId)){K.error("Request ID not found");return}if(!h){K.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},ga=(F==null?void 0:F.status)==="closed";p.useEffect(()=>{(async()=>{if(!ga||!($!=null&&$.requestId)){g(null),x(null);return}try{f(!0);const is=await Bp($.requestId);if(is!=null&&is.summaryId){x(is.summaryId);try{const Is=await pc(is.summaryId);g(Is)}catch(Is){console.error("Failed to fetch summary details:",Is),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{f(!1)}})()},[ga,$==null?void 0:$.requestId]),p.useEffect(()=>{if(!ce||!($!=null&&$.requestId))return;const vt=Lr();if(!vt)return;Tx(vt,ce);const is=Is=>{var Ma,Kr,Xr,Zr;const Zs=Is==null?void 0:Is.notification;if(!Zs)return;const Nr=Zs.requestId||Zs.request_id,ca=((Ma=Zs.metadata)==null?void 0:Ma.requestNumber)||((Kr=Zs.metadata)==null?void 0:Kr.request_number);Nr!==$.requestId&&ca!==n&&ca!==$.requestNumber||((Xr=Zs.metadata)!=null&&Xr.creditNoteNumber||(Zr=Zs.metadata)!=null&&Zr.credit_note_number)&&j()};return vt.on("notification:new",is),()=>{vt.off("notification:new",is)}},[ce,$==null?void 0:$.requestId,n,j]);const La=((F==null?void 0:F.approvalFlow)||[]).filter(vt=>vt&&typeof vt.step=="number").map(vt=>({levelNumber:vt.step||0,approverName:vt.approver||"Unknown",status:vt.status||"pending",tatHours:vt.tatHours||24}));return V&&!F&&!$?e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx($t,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading dealer claim request details..."})]})}):G!=null&&G.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(rx,{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:G.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})}):F?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(lT,{request:F,refreshing:T,onBack:s||(()=>window.history.back()),onRefresh:Ca,onShareSummary:_a,isInitiator:M,slaData:((It=F==null?void 0:F.summary)==null?void 0:It.sla)||(F==null?void 0:F.sla)||null,isPaused:((ns=F==null?void 0:F.pauseInfo)==null?void 0:ns.isPaused)||!1}),e.jsxs($i,{value:o,onValueChange:c,className:"w-full","data-testid":"dealer-claim-request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(Oi,{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(qt,{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(nx,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),ga&&u&&e.jsxs(qt,{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(ix,{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(qt,{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(ta,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),te&&e.jsxs(qt,{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(Da,{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(qt,{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(Re,{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(qt,{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(kt,{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(qt,{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(As,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),z>0&&e.jsx(ne,{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:z>9?"9+":z})]})]})}),e.jsxs("div",{className:o==="worknotes"?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:o==="worknotes"?"":"lg:col-span-2",children:[e.jsx(es,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(RA,{request:F,apiRequest:$,currentUserId:ce,isInitiator:M,needsClosure:Ht,conclusionRemark:at,setConclusionRemark:et,conclusionLoading:yt,conclusionSubmitting:rs,aiGenerated:Pt,handleGenerateConclusion:la,handleFinalizeConclusion:pa,generationAttempts:Fa,generationFailed:wa,maxAttemptsReached:St})}),ga&&e.jsx(es,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(iT,{summary:u,loading:b,onShare:_a,isInitiator:M})}),e.jsx(es,{value:"workflow",className:"mt-0",children:e.jsx(JA,{request:F,user:O,isInitiator:M,onSkipApprover:vt=>{if(!vt.levelId){alert("Level ID not available");return}X(vt),Ps(!0)},onRefresh:j,documentPolicy:Ce})}),te&&e.jsx(es,{value:"io",className:"mt-0",children:e.jsx(QA,{request:F,apiRequest:$,onRefresh:j})}),e.jsx(es,{value:"documents",className:"mt-0",children:e.jsx(aT,{request:F,workNoteAttachments:H,uploadingDocument:ae,documentPolicy:Ce,triggerFileInput:me,setPreviewDocument:oe,downloadDocument:ps})}),e.jsx(es,{value:"activity",className:"mt-0",children:e.jsx(rT,{request:F})}),e.jsx(es,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(nT,{requestId:n,requestTitle:F.title,mergedMessages:L,setWorkNoteAttachments:ye,isInitiator:M,isSpectator:I,currentLevels:La,onAddApprover:Ve,maxApprovalLevels:A.maxApprovalLevels,onPolicyViolation:vt=>R({open:!0,violations:vt})})})]}),o!=="worknotes"&&e.jsx(oT,{request:F,isInitiator:M,isSpectator:I,currentApprovalLevel:U,onAddApprover:()=>_e(!0),onAddSpectator:()=>ut(!0),onApprove:()=>Z(!0),onReject:()=>Xe(!0),onPause:Za,onResume:Ja,onRetrigger:qa,summaryId:h,refreshTrigger:y,pausedByUserId:(sr=(Os=F==null?void 0:F.pauseInfo)==null?void 0:Os.pausedBy)==null?void 0:sr.userId,currentUserId:ce,apiRequest:$})]})]})]})}),d&&h&&e.jsx(Gp,{isOpen:d,onClose:()=>m(!1),summaryId:h,requestTitle:(F==null?void 0:F.title)||"N/A",onSuccess:()=>{j(),v(vt=>vt+1)}}),w&&($==null?void 0:$.requestId)&&e.jsx(Yp,{isOpen:w,onClose:()=>C(!1),requestId:$.requestId,levelId:(U==null?void 0:U.levelId)||null,onSuccess:er}),k&&($==null?void 0:$.requestId)&&e.jsx(Kp,{isOpen:k,onClose:()=>S(!1),requestId:$.requestId,onSuccess:Qa}),_&&($==null?void 0:$.requestId)&&e.jsx(Xp,{isOpen:_,onClose:()=>D(!1),requestId:$.requestId,approverName:(oa=(ar=F==null?void 0:F.pauseInfo)==null?void 0:ar.pausedBy)==null?void 0:oa.name,onSuccess:tr}),e.jsx(cT,{showApproveModal:Ue,showRejectModal:Te,showAddApproverModal:pe,showAddSpectatorModal:rt,showSkipApproverModal:nt,showActionStatusModal:Xs,previewDocument:Q,documentError:Ee,request:F,skipApproverData:Xa,actionStatus:we,existingParticipants:W,currentLevels:La,maxApprovalLevels:A.maxApprovalLevels,onPolicyViolation:vt=>R({open:!0,violations:vt}),setShowApproveModal:Z,setShowRejectModal:Xe,setShowAddApproverModal:_e,setShowAddSpectatorModal:ut,setShowSkipApproverModal:Ps,setShowActionStatusModal:Na,setPreviewDocument:oe,setDocumentError:be,setSkipApproverData:X,setActionStatus:J,handleApproveConfirm:Be,handleRejectConfirm:qe,handleAddApprover:Ve,handleAddSpectator:Ze,handleSkipApprover:Me,downloadDocument:ps,documentPolicy:Ce}),e.jsx(Fn,{open:P.open,onClose:()=>R({open:!1,violations:[]}),violations:P.violations,policyDetails:{maxApprovalLevels:A.maxApprovalLevels,maxParticipants:A.maxParticipants,allowSpectators:A.allowSpectators,maxSpectators:A.maxSpectators}})]}):e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6","data-testid":"not-found-state",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(Re,{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(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function uT(t){return e.jsx(dT,{children:e.jsx(mT,{...t})})}function xT({onNavigate:t,onNewRequest:s}){const[a,r]=p.useState(!0),[n,i]=p.useState(!1),[l,o]=p.useState({totalClaims:0,totalValue:0,approved:0,rejected:0,pending:0,credited:0,pendingCredit:0,approvedValue:0,rejectedValue:0,pendingValue:0,creditedValue:0,pendingCreditValue:0}),[c,d]=p.useState([]),[m,h]=p.useState("all"),[x,u]=p.useState(),[g,b]=p.useState(),f=async(R=!1)=>{try{R?i(!0):r(!0);const O=await GA(m||"all",x,g);o(O.kpis||{totalClaims:0,totalValue:0,approved:0,rejected:0,pending:0,credited:0,pendingCredit:0,approvedValue:0,rejectedValue:0,pendingValue:0,creditedValue:0,pendingCreditValue:0}),d(O.categoryData||[])}catch(O){console.error("[DealerDashboard] Error fetching data:",O),K.error("Failed to load dashboard data. Please try again later."),o({totalClaims:0,totalValue:0,approved:0,rejected:0,pending:0,credited:0,pendingCredit:0,approvedValue:0,rejectedValue:0,pendingValue:0,creditedValue:0,pendingCreditValue:0}),d([])}finally{r(!1),i(!1)}};p.useEffect(()=>{f()},[]);const y=(R,O=!1)=>{if(R==null||isNaN(R))return"₹0";const F=typeof R=="string"?parseFloat(R):Number(R);return F<=0?"₹0":O||F<1e4?`₹${Math.round(F).toLocaleString("en-IN")}`:F>=1e5?`₹${(F/1e5).toFixed(1)}L`:F>=1e3?`₹${(F/1e3).toFixed(1)}K`:`₹${Math.round(F).toLocaleString("en-IN")}`},v=R=>R.toLocaleString("en-IN"),w=()=>l.totalClaims===0?0:(l.approved/l.totalClaims*100).toFixed(1),C=()=>l.approved===0?0:(l.credited/l.approved*100).toFixed(1),k=p.useMemo(()=>{const R=c.reduce((O,F)=>O+F.raised,0);return R===0?[]:c.map(O=>({name:O.activityType.length>20?O.activityType.substring(0,20)+"...":O.activityType,value:O.raised,fullName:O.activityType,percentage:(O.raised/R*100).toFixed(0)}))},[c]),S=p.useMemo(()=>c.map(R=>({name:R.activityType.length>15?R.activityType.substring(0,15)+"...":R.activityType,fullName:R.activityType,Raised:R.raised,Approved:R.approved,Rejected:R.rejected,Pending:R.pending})),[c]),_=p.useMemo(()=>c.map(R=>({name:R.activityType.length>15?R.activityType.substring(0,15)+"...":R.activityType,fullName:R.activityType,Raised:R.raisedValue,Approved:R.approvedValue,Credited:R.creditedValue})),[c]),D=["#166534","#15803d","#16a34a","#22c55e","#4ade80","#86efac","#bbf7d0"],A=p.useMemo(()=>c.length===0?null:c.reduce((R,O)=>O.approvalRate>((R==null?void 0:R.approvalRate)||0)?O:R),[c]),N=p.useMemo(()=>c.length===0?null:c.reduce((R,O)=>O.raisedValue>((R==null?void 0:R.raisedValue)||0)?O:R),[c]);return a?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx($t,{className:"w-8 h-8 animate-spin text-blue-600"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading dashboard..."})]})}):l.totalClaims===0&&c.length===0?e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(ee,{className:"border-0 shadow-xl relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(se,{className:"relative z-10 p-8 lg:p-12",children:e.jsx("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6",children:e.jsxs("div",{className:"text-white",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx("div",{className:"w-16 h-16 bg-yellow-400 rounded-xl flex items-center justify-center shadow-lg",children:e.jsx(hs,{className:"w-8 h-8 text-slate-900"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-4xl text-white font-bold",children:"Claims Analytics Dashboard"}),e.jsx("p",{className:"text-xl text-gray-200 mt-1",children:"Comprehensive insights into approval workflows"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 mt-8",children:[e.jsxs(E,{onClick:()=>t==null?void 0:t("/new-request"),className:"bg-blue-600 hover:bg-blue-700 text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200",children:[e.jsx(Re,{className:"w-5 h-5 mr-2"}),"Create New Claim"]}),e.jsxs(E,{onClick:()=>{i(!0),f(!0)},disabled:n,variant:"outline",className:"bg-white/10 hover:bg-white/20 text-white border-white/20",children:[e.jsx($t,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh"]})]})]})})})]}),e.jsx(ee,{className:"shadow-lg",children:e.jsxs(se,{className:"flex flex-col items-center justify-center py-16 px-4",children:[e.jsx("div",{className:"w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mb-6",children:e.jsx(Pl,{className:"w-12 h-12 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-2",children:"No Claims Data Available"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md mb-6",children:"You don't have any claims data yet. Once you create and submit claim requests, your analytics will appear here."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs(E,{onClick:()=>t==null?void 0:t("/new-request"),className:"bg-blue-600 hover:bg-blue-700 text-white",children:[e.jsx(Re,{className:"w-5 h-5 mr-2"}),"Create Your First Claim"]}),e.jsxs(E,{onClick:()=>{i(!0),f(!0)},disabled:n,variant:"outline",children:[e.jsx($t,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh Data"]})]})]})})]}):e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(ee,{className:"border-0 shadow-xl relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(se,{className:"relative z-10 p-8 lg:p-12",children:e.jsxs("div",{className:"flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6",children:[e.jsxs("div",{className:"text-white",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx("div",{className:"w-16 h-16 bg-yellow-400 rounded-xl flex items-center justify-center shadow-lg",children:e.jsx(hs,{className:"w-8 h-8 text-slate-900"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-4xl text-white font-bold",children:"Claims Analytics Dashboard"}),e.jsx("p",{className:"text-xl text-gray-200 mt-1",children:"Comprehensive insights into approval workflows"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 mt-8",children:[e.jsxs(E,{onClick:()=>t==null?void 0:t("/requests?status=pending"),className:"bg-blue-600 hover:bg-blue-700 text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200",children:[e.jsx(st,{className:"w-5 h-5 mr-2"}),"View Pending Claims"]}),e.jsxs(E,{onClick:()=>t==null?void 0:t("/requests"),className:"bg-emerald-600 hover:bg-emerald-700 text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200",children:[e.jsx(Re,{className:"w-5 h-5 mr-2"}),"My Claims"]})]})]}),e.jsx("div",{className:"hidden lg:flex items-center gap-4",children:e.jsx("div",{className:"w-24 h-24 bg-yellow-400/20 rounded-full flex items-center justify-center",children:e.jsx("div",{className:"w-16 h-16 bg-yellow-400/30 rounded-full flex items-center justify-center",children:e.jsx(Il,{className:"w-8 h-8 text-yellow-400"})})})})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6 gap-4",children:[e.jsxs(ee,{className:"border-l-4 border-l-blue-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Raised Claims"}),e.jsx("div",{className:"p-2 rounded-lg bg-blue-50",children:e.jsx(Re,{className:"h-4 w-4 text-blue-600"})})]})}),e.jsxs(se,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.totalClaims)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y(l.totalValue,!0)})]})]}),e.jsxs(ee,{className:"border-l-4 border-l-green-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Approved"}),e.jsx("div",{className:"p-2 rounded-lg bg-green-50",children:e.jsx(De,{className:"h-4 w-4 text-green-600"})})]})}),e.jsxs(se,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.approved)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(ta,{className:"h-3 w-3 text-green-600"}),e.jsxs("p",{className:"text-xs text-green-600",children:[w(),"% approval rate"]})]})]})]}),e.jsxs(ee,{className:"border-l-4 border-l-red-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Rejected"}),e.jsx("div",{className:"p-2 rounded-lg bg-red-50",children:e.jsx(wt,{className:"h-4 w-4 text-red-600"})})]})}),e.jsxs(se,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.rejected)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(u0,{className:"h-3 w-3 text-red-600"}),e.jsxs("p",{className:"text-xs text-red-600",children:[l.totalClaims>0?(l.rejected/l.totalClaims*100).toFixed(1):0,"% rejection rate"]})]})]})]}),e.jsxs(ee,{className:"border-l-4 border-l-orange-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Pending"}),e.jsx("div",{className:"p-2 rounded-lg bg-orange-50",children:e.jsx(st,{className:"h-4 w-4 text-orange-600"})})]})}),e.jsxs(se,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.pending)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y(l.pendingValue)})]})]}),e.jsxs(ee,{className:"border-l-4 border-l-emerald-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Credited"}),e.jsx("div",{className:"p-2 rounded-lg bg-emerald-50",children:e.jsx(x0,{className:"h-4 w-4 text-emerald-600"})})]})}),e.jsxs(se,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.credited)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(ta,{className:"h-3 w-3 text-emerald-600"}),e.jsxs("p",{className:"text-xs text-emerald-600",children:[C(),"% credit rate"]})]})]})]}),e.jsxs(ee,{className:"border-l-4 border-l-amber-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(ge,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-sm text-muted-foreground",children:"Pending Credit"}),e.jsx("div",{className:"p-2 rounded-lg bg-amber-50",children:e.jsx(as,{className:"h-4 w-4 text-amber-600"})})]})}),e.jsxs(se,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:v(l.pendingCredit)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y(l.pendingCreditValue)})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(ee,{className:"shadow-lg",children:[e.jsx(ge,{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(Pl,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(fe,{children:"Claims Distribution by Activity Type"}),e.jsx($e,{children:"Total claims raised across activity types"})]})]})}),e.jsxs(se,{children:[e.jsx(Pr,{width:"100%",height:300,children:e.jsxs(Uu,{children:[e.jsx(Bu,{data:k,cx:"50%",cy:"50%",labelLine:!1,label:({name:R,percentage:O})=>`${R}: ${O}%`,outerRadius:80,fill:"#8884d8",dataKey:"value",children:k.map((R,O)=>e.jsx(Vu,{fill:D[O%D.length]},`cell-${O}`))}),e.jsx(Ir,{})]})}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mt-4",children:k.slice(0,3).map((R,O)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-gray-50",children:[e.jsx("div",{className:"w-3 h-3 rounded",style:{backgroundColor:D[O%D.length]}}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600",children:R.name}),e.jsx("p",{className:"text-sm text-gray-900",children:v(R.value)})]})]},O))})]})]}),e.jsxs(ee,{className:"shadow-lg",children:[e.jsx(ge,{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(Il,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{children:"Claims Status by Activity Type"}),e.jsx($e,{children:"Count comparison across workflow stages"})]})]})}),e.jsx(se,{children:e.jsx(Pr,{width:"100%",height:300,children:e.jsxs(kl,{data:S,children:[e.jsx(ei,{strokeDasharray:"3 3"}),e.jsx(ti,{dataKey:"name"}),e.jsx(si,{}),e.jsx(Ir,{}),e.jsx(ai,{}),e.jsx(fa,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(fa,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(fa,{dataKey:"Rejected",fill:"#ef4444"}),e.jsx(fa,{dataKey:"Pending",fill:"#f59e0b"})]})})})]})]}),e.jsxs(ee,{className:"shadow-lg",children:[e.jsx(ge,{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(kt,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(fe,{children:"Detailed Activity Type Breakdown"}),e.jsx($e,{children:"In-depth analysis of claims by type and status"})]})]})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg mb-4 text-gray-900",children:"Activity Type Value Comparison"}),e.jsx(Pr,{width:"100%",height:350,children:e.jsxs(kl,{data:_,children:[e.jsx(ei,{strokeDasharray:"3 3"}),e.jsx(ti,{dataKey:"name"}),e.jsx(si,{tickFormatter:R=>y(R)}),e.jsx(Ir,{formatter:R=>y(R),labelFormatter:R=>R}),e.jsx(ai,{}),e.jsx(fa,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(fa,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(fa,{dataKey:"Credited",fill:"#10b981"})]})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mt-6",children:c.slice(0,3).map((R,O)=>e.jsxs(ee,{className:"shadow-md hover:shadow-lg transition-shadow",children:[e.jsx(ge,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-base",children:R.activityType}),e.jsxs(ne,{className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:[R.approvalRate.toFixed(1),"% approved"]})]})}),e.jsxs(se,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Raised:"}),e.jsxs("span",{className:"text-gray-900",children:[v(R.raised)," (",y(R.raisedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Approved:"}),e.jsxs("span",{className:"text-green-600",children:[v(R.approved)," (",y(R.approvedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Rejected:"}),e.jsxs("span",{className:"text-red-600",children:[v(R.rejected)," (",y(R.rejectedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Pending:"}),e.jsxs("span",{className:"text-orange-600",children:[v(R.pending)," (",y(R.pendingValue),")"]})]}),e.jsx("div",{className:"h-px bg-gray-200 my-2"}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Credited:"}),e.jsxs("span",{className:"text-emerald-600",children:[v(R.credited)," (",y(R.creditedValue),")"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-600",children:"Pending Credit:"}),e.jsxs("span",{className:"text-amber-600",children:[v(R.pendingCredit)," (",y(R.pendingCreditValue),")"]})]})]}),e.jsxs("div",{className:"pt-2",children:[e.jsxs("div",{className:"flex justify-between text-xs text-gray-600 mb-1",children:[e.jsx("span",{children:"Credit Rate"}),e.jsxs("span",{children:[R.creditRate.toFixed(1),"%"]})]}),e.jsx(na,{value:R.creditRate,className:"h-2"})]})]})]},O))})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(ee,{className:"border-t-4 border-t-green-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(se,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"p-3 bg-green-100 rounded-lg",children:e.jsx(Ot,{className:"h-6 w-6 text-green-600"})}),e.jsx(ta,{className:"h-5 w-5 text-green-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Best Performing"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:(A==null?void 0:A.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-green-600",children:[(A==null?void 0:A.approvalRate.toFixed(2))||0,"% approval rate"]})]})}),e.jsx(ee,{className:"border-t-4 border-t-blue-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(se,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(Da,{className:"h-6 w-6 text-blue-600"})}),e.jsx(kt,{className:"h-5 w-5 text-blue-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Top Activity Type"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:(N==null?void 0:N.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-blue-600",children:[N?y(N.raisedValue,!0):"₹0"," raised"]})]})}),e.jsx(ee,{className:"border-t-4 border-t-emerald-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(se,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"p-3 bg-emerald-100 rounded-lg",children:e.jsx(xo,{className:"h-6 w-6 text-emerald-600"})}),e.jsx(De,{className:"h-5 w-5 text-emerald-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Overall Credit Rate"}),e.jsxs("p",{className:"text-xl text-gray-900 mb-1",children:[C(),"%"]}),e.jsxs("p",{className:"text-sm text-emerald-600",children:[v(l.credited)," claims credited"]})]})}),e.jsx(ee,{className:"border-t-4 border-t-amber-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(se,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"p-3 bg-amber-100 rounded-lg",children:e.jsx(ex,{className:"h-6 w-6 text-amber-600"})}),e.jsx(as,{className:"h-5 w-5 text-amber-600"})]}),e.jsx("h3",{className:"text-sm text-gray-600 mb-1",children:"Pending Action"}),e.jsx("p",{className:"text-xl text-gray-900 mb-1",children:v(l.pendingCredit)}),e.jsxs("p",{className:"text-sm text-amber-600",children:[y(l.pendingCreditValue)," awaiting credit"]})]})})]})]})}function hT({searchTerm:t,sortBy:s,sortOrder:a,onSearchChange:r,onSortByChange:n,onSortOrderChange:i,onClearFilters:l,activeFiltersCount:o,...c}){return e.jsxs(ee,{className:"shadow-lg border-0",children:[e.jsx(ge,{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(Ya,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx($e,{className:"text-xs sm:text-sm",children:o>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[o," filter",o>1?"s":""," active"]})})]})]}),o>0&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:l,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(ft,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(se,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{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(Oe,{placeholder:"Search requests, IDs...",value:t,onChange:d=>r(d.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(We,{value:s,onValueChange:d=>n(d),children:[e.jsx(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Sort by"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"due",children:"Due Date"}),e.jsx(Y,{value:"created",children:"Date Created"}),e.jsx(Y,{value:"priority",children:"Priority"}),e.jsx(Y,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>i(a==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:a==="asc"?e.jsx(Ai,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Ti,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function pT({searchTerm:t,statusFilter:s="all",sortBy:a,sortOrder:r,onSearchChange:n,onStatusChange:i,onSortByChange:l,onSortOrderChange:o,onClearFilters:c,activeFiltersCount:d,...m}){return e.jsxs(ee,{className:"shadow-lg border-0","data-testid":"dealer-closed-requests-filters",children:[e.jsx(ge,{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(Ya,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx($e,{className:"text-xs sm:text-sm",children:d>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[d," filter",d>1?"s":""," active"]})})]})]}),d>0&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:c,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3","data-testid":"dealer-closed-requests-clear-filters",children:[e.jsx(ft,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(se,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{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(Oe,{placeholder:"Search requests, IDs...",value:t,onChange:h=>n(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 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors","data-testid":"dealer-closed-requests-search"})]}),i&&e.jsxs(We,{value:s,onValueChange:i,children:[e.jsx(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200","data-testid":"dealer-closed-requests-status-filter",children:e.jsx(Ge,{placeholder:"Closure Type"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Closures"}),e.jsx(Y,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(Y,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wt,{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(We,{value:a,onValueChange:h=>l(h),children:[e.jsx(Ye,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200","data-testid":"dealer-closed-requests-sort-by",children:e.jsx(Ge,{placeholder:"Sort by"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"due",children:"Due Date"}),e.jsx(Y,{value:"created",children:"Date Created"}),e.jsx(Y,{value:"priority",children:"Priority"})]})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:o,className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11","data-testid":"dealer-closed-requests-sort-order",children:r==="asc"?e.jsx(Ai,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(Ti,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function gT({searchTerm:t,statusFilter:s,initiatorFilter:a,approverFilter:r,approverFilterType:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,initiatorSearch:d,approverSearch:m,onSearchChange:h,onStatusChange:x,onInitiatorChange:u,onApproverChange:g,onApproverTypeChange:b,onDateRangeChange:f,onCustomStartDateChange:y,onCustomEndDateChange:v,onShowCustomDatePickerChange:w,onApplyCustomDate:C,onClearFilters:k,hasActiveFilters:S,..._}){return e.jsx(ee,{className:"border-gray-200 shadow-md","data-testid":"dealer-user-all-requests-filters",children:e.jsx(se,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ya,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),S&&e.jsx(ne,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),S&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:k,className:"gap-2",children:[e.jsx($t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Ts,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Oe,{placeholder:"Search requests...",value:t,onChange:D=>h(D.target.value),className:"pl-10 h-10","data-testid":"dealer-search-input"})]}),e.jsxs(We,{value:s,onValueChange:x,children:[e.jsx(Ye,{className:"h-10","data-testid":"dealer-status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"paused",children:"Paused"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:d.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:d.selectedUser.displayName||d.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:d.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Oe,{placeholder:"Search initiator...",value:d.searchQuery,onChange:D=>d.handleSearch(D.target.value),onFocus:()=>{d.searchResults.length>0&&d.setShowResults(!0)},onBlur:()=>setTimeout(()=>d.setShowResults(!1),200),className:"h-10","data-testid":"dealer-initiator-search-input"}),d.showResults&&d.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:d.searchResults.map(D=>e.jsx("button",{type:"button",onClick:()=>d.handleSelect(D),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:D.displayName||D.email}),D.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:D.email})]})},D.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approver"}),r!=="all"&&b&&e.jsxs(We,{value:n,onValueChange:D=>b(D),children:[e.jsx(Ye,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"current",children:"Current Only"}),e.jsx(Y,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:m.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:m.selectedUser.displayName||m.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:m.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Oe,{placeholder:"Search approver...",value:m.searchQuery,onChange:D=>m.handleSearch(D.target.value),onFocus:()=>{m.searchResults.length>0&&m.setShowResults(!0)},onBlur:()=>setTimeout(()=>m.setShowResults(!1),200),className:"h-10","data-testid":"dealer-approver-search-input"}),m.showResults&&m.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:m.searchResults.map(D=>e.jsx("button",{type:"button",onClick:()=>m.handleSelect(D),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:D.displayName||D.email}),D.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:D.email})]})},D.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(ot,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(We,{value:i,onValueChange:D=>f(D),children:[e.jsx(Ye,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),i==="custom"&&e.jsxs(Hs,{open:c,onOpenChange:w,children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ot,{className:"w-4 h-4"}),l&&o?`${He(l,"MMM d, yyyy")} - ${He(o,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Gs,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Ms,{value:l||null,onChange:D=>{const A=D?new Date(D):void 0;A?(y==null||y(A),o&&A>o&&(v==null||v(A))):y==null||y(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",children:"End Date"}),e.jsx(Ms,{value:o||null,onChange:D=>{const A=D?new Date(D):void 0;A?(v==null||v(A),l&&A{w==null||w(!1),y==null||y(void 0),v==null||v(void 0),f("month")},children:"Cancel"})]})]})})]})]})]})})})}function fT(t){switch(t){case"DEALER_CLAIM":return uT;case"CUSTOM":default:return SA}}function bT(t){switch(t){case"DEALER":return hT;case"STANDARD":default:return AA}}function yT(t){switch(t){case"DEALER":return pT;case"STANDARD":default:return TA}}function vT(t){switch(t){case"DEALER":return gT;case"STANDARD":default:return kA}}const jT=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ha,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ot,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ot,iconColor:"text-gray-600"}}},NT=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,iconColor:"text-yellow-600",label:"Pending"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:ze,iconColor:"text-green-600",label:"Needs Closure"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:wt,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:De,iconColor:"text-gray-600",label:"Closed"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ze,iconColor:"text-gray-600",label:t}}};function wT({onViewRequest:t}){const[s,a]=p.useState([]),[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState(1),[d,m]=p.useState(0),[h]=p.useState(10),x=p.useRef(null),u=Vj(),g=p.useMemo(()=>{try{const A=tt.getUserData();return Eo(A)}catch(A){return console.error("[OpenRequests] Error getting user filter type:",A),"STANDARD"}},[]),b=p.useMemo(()=>bT(g),[g]),f=g==="DEALER",y=A=>({search:u.searchTerm||void 0,status:A&&!f&&u.statusFilter!=="all"?u.statusFilter:void 0,priority:!f&&u.priorityFilter!=="all"?u.priorityFilter:void 0,templateType:!f&&u.templateTypeFilter!=="all"?u.templateTypeFilter:void 0,sortBy:u.sortBy,sortOrder:u.sortOrder}),v=p.useCallback(async(A=1,N)=>{try{A===1&&(n(!0),a([]));const P=await ks.listOpenForMe({page:A,limit:h,search:N==null?void 0:N.search,status:N==null?void 0:N.status,priority:N==null?void 0:N.priority,templateType:N==null?void 0:N.templateType,sortBy:N==null?void 0:N.sortBy,sortOrder:N==null?void 0:N.sortOrder}),R=Array.isArray(P==null?void 0:P.data)?P.data:[],O=P==null?void 0:P.pagination;O&&(u.setCurrentPage(O.page||1),c(O.totalPages||1),m(O.total||0));const F=R.map($=>{var T,j,U,I;const V=$.submittedAt||$.submitted_at||$.createdAt||$.created_at;return{id:$.requestNumber||$.request_number||$.requestId,requestId:$.requestId,displayId:$.requestNumber||$.request_number||$.requestId,title:$.title,description:$.description,status:($.status||"").toString().toLowerCase().replace("_","-"),priority:($.priority||"").toString().toLowerCase(),initiator:{name:((T=$.initiator)==null?void 0:T.displayName)||((j=$.initiator)==null?void 0:j.email)||"—",avatar:(((U=$.initiator)==null?void 0:U.displayName)||((I=$.initiator)==null?void 0:I.email)||"NA").split(" ").map(M=>M[0]).join("").slice(0,2).toUpperCase()},currentApprover:$.currentApprover?{name:$.currentApprover.name||$.currentApprover.email||"—",avatar:($.currentApprover.name||$.currentApprover.email||"CA").split(" ").map(M=>M[0]).join("").slice(0,2).toUpperCase(),sla:$.currentApprover.sla}:void 0,createdAt:V||"—",approvalStep:$.currentLevel?`Step ${$.currentLevel} of ${$.totalLevels||"?"}`:void 0,department:$.department,currentLevelSLA:$.currentLevelSLA,templateType:$.templateType||$.template_type}});a(F)}finally{n(!1),l(!1)}},[h,u]);x.current=v;const w=p.useCallback(()=>{l(!0),v(u.currentPage,y(!0))},[u.currentPage,v]),C=p.useCallback(A=>{A>=1&&A<=o&&(u.setCurrentPage(A),v(A,y(!0)))},[o,u,v]),k=()=>{const A=[];let P=Math.max(1,u.currentPage-Math.floor(2.5)),R=Math.min(o,P+5-1);R-P<4&&(P=Math.max(1,R-5+1));for(let O=P;O<=R;O++)A.push(O);return A},S=p.useRef(!1);p.useEffect(()=>{if(!S.current){S.current=!0;const A=u.currentPage||1;v(A,y(!0))}},[]);const _=p.useRef({searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,isDealer:f});p.useEffect(()=>{if(!S.current)return;const A=_.current;if(!(A.searchTerm!==u.searchTerm||A.statusFilter!==u.statusFilter||A.priorityFilter!==u.priorityFilter||A.templateTypeFilter!==u.templateTypeFilter||A.sortBy!==u.sortBy||A.sortOrder!==u.sortOrder||A.isDealer!==f))return;const P=setTimeout(()=>{u.setCurrentPage(1),v(1,y(!0)),_.current={searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,isDealer:f}},u.searchTerm?500:0);return()=>clearTimeout(P)},[u.searchTerm,u.statusFilter,u.priorityFilter,u.templateTypeFilter,u.sortBy,u.sortOrder,f]);const D=s;return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto",children:[e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-3 sm:gap-4 md:gap-6",children:[e.jsx("div",{className:"space-y-1 sm:space-y-2",children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-slate-800 to-slate-900 rounded-xl flex items-center justify-center shadow-lg",children:e.jsx(Re,{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(ne,{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(E,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:w,disabled:i,children:[e.jsx($t,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:i?"Refreshing...":"Refresh"})]})]})]}),e.jsx(b,{searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,onSearchChange:u.setSearchTerm,onStatusFilterChange:u.setStatusFilter,onPriorityFilterChange:u.setPriorityFilter,onTemplateTypeFilterChange:u.setTemplateTypeFilter,onSortByChange:u.setSortBy,onSortOrderChange:u.setSortOrder,onClearFilters:u.clearFilters,activeFiltersCount:u.activeFiltersCount}),e.jsx("div",{className:"space-y-3",children:D.map(A=>{const N=jT(A.priority),P=NT(A.status);return e.jsx(ee,{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(A.id,A.title),children:e.jsx(se,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${N.color} border shadow-sm`,children:e.jsx(N.icon,{className:`w-5 h-5 ${N.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:A.displayId||A.id}),e.jsxs(ne,{variant:"outline",className:`${P.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx(P.icon,{className:"w-3.5 h-3.5 mr-1"}),P.label||A.status]}),A.department&&e.jsx(ne,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:A.department}),e.jsx(ne,{variant:"outline",className:`${N.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:A.priority}),(()=>{const R=(A==null?void 0:A.templateType)||(A==null?void 0:A.template_type)||"",O=(R==null?void 0:R.toUpperCase())||"";let F="Non-Templatized",$="bg-purple-100 !text-purple-600 border-purple-200";return O==="DEALER CLAIM"?(F="Dealer Claim",$="bg-blue-100 !text-blue-700 border-blue-200"):O==="TEMPLATE"&&(F="Template"),e.jsx(ne,{variant:"outline",className:`${$} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:F})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:A.title}),A.currentLevelSLA&&(()=>{var V;const R=!!(A.isPaused||(V=A.pauseInfo)!=null&&V.isPaused||A.status==="paused"),O=A.currentLevelSLA.percentageUsed||0,$=R?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:O>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:O>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:O>=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 ${$.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:[R?e.jsx(pn,{className:`w-3.5 h-3.5 ${$.icon}`}):e.jsx(st,{className:`w-3.5 h-3.5 ${$.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",O,"% ",R&&"(paused)"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:A.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${$.text}`,children:[A.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(na,{value:O,className:"h-1.5",indicatorClassName:$.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(Zt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:A.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:A.initiator.name})]}),A.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Zt,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(Jt,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:A.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:A.currentApprover.name})]}),A.approvalStep&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ze,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"font-medium",children:A.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ot,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",A.createdAt!=="—"?xa(A.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(ss,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},A.id)})}),D.length===0&&e.jsx(ee,{className:"shadow-lg border-0",children:e.jsxs(se,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Re,{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:u.searchTerm||u.activeFiltersCount>0?"Try adjusting your filters or search terms to see more results.":"No open requests available at the moment."}),u.activeFiltersCount>0&&e.jsx(E,{variant:"outline",className:"mt-4",onClick:u.clearFilters,children:"Clear all filters"})]})}),o>1&&!r&&e.jsx(ee,{className:"shadow-md",children:e.jsx(se,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(u.currentPage-1)*h+1," to ",Math.min(u.currentPage*h,d)," of ",d," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>C(u.currentPage-1),disabled:u.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(ss,{className:"h-4 w-4 rotate-180"})}),u.currentPage>3&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>C(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),k().map(A=>e.jsx(E,{variant:A===u.currentPage?"default":"outline",size:"sm",onClick:()=>C(A),className:`h-8 w-8 p-0 ${A===u.currentPage?"bg-re-green text-white hover:bg-re-green/90":""}`,children:A},A)),u.currentPage5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>C(o),className:"h-8 w-8 p-0",children:o})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>C(u.currentPage+1),disabled:u.currentPage===o,className:"h-8 w-8 p-0",children:e.jsx(ss,{className:"h-4 w-4"})})]})]})})})]})}function CT({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(Re,{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(ne,{variant:"secondary",className:"text-xs sm:text-sm md:text-base px-2 sm:px-3 md:px-4 py-1 sm:py-1.5 md:py-2 bg-slate-100 text-slate-800 font-semibold","data-testid":"closed-requests-count",children:[s?"Loadingâ€Ļ":`${t} closed`,e.jsx("span",{className:"hidden sm:inline ml-1",children:"requests"})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:r,disabled:a,"data-testid":"closed-requests-refresh",children:[e.jsx($t,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${a?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:a?"Refreshing...":"Refresh"})]})]})]})}function ST(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ha,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ot,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ot,iconColor:"text-gray-600"}}}function AT(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:De,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:wt,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ze,iconColor:"text-gray-600",label:t,description:""}}}function TT({request:t,onViewRequest:s}){const a=ST(t.priority),r=AT(t.status),n=a.icon,i=r.icon;return e.jsx(ee,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>s==null?void 0:s(t.id,t.title),"data-testid":`closed-request-card-${t.id}`,children:e.jsx(se,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-5",children:[e.jsx("div",{className:"flex-shrink-0 pt-1",children:e.jsx("div",{className:`p-2.5 rounded-lg ${a.color} border shadow-sm`,children:e.jsx(n,{className:`w-5 h-5 ${a.iconColor}`})})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap",children:[e.jsx("h3",{className:"text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors",children:t.displayId||t.id}),e.jsxs(ne,{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(ne,{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(ne,{variant:"outline",className:`${a.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:t.priority}),(()=>{const l=t.templateType||"",o=(l==null?void 0:l.toUpperCase())||"";let c="Non-Templatized",d="bg-purple-100 !text-purple-600 border-purple-200";return o==="DEALER CLAIM"?(c="Dealer Claim",d="bg-blue-100 !text-blue-700 border-blue-200"):o==="TEMPLATE"&&(c="Template"),e.jsx(ne,{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(Zt,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(Jt,{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(De,{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(ot,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?xa(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(De,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",xa(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(ss,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function kT({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(TT,{request:r,onViewRequest:a},r.id))})}function RT({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(ee,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(se,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Re,{className:"h-8 w-8 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md",children:t||s>0?"Try adjusting your filters or search terms to see more results.":"No closed requests available at the moment."}),s>0&&e.jsx(E,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function DT(t,s){const a=[];let n=Math.max(1,t-Math.floor(2.5)),i=Math.min(s,n+5-1);i-n<4&&(n=Math.max(1,i-5+1));for(let l=n;l<=i;l++)a.push(l);return a}function PT({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const l=DT(a,r);return e.jsx(ee,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(se,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-muted-foreground",children:["Showing ",(a-1)*i+1," to ",Math.min(a*i,n)," of ",n," closed requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>s(a-1),disabled:a===1,className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-prev",children:e.jsx(ss,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>s(1),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-first",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),l.map(o=>e.jsx(E,{variant:o===a?"default":"outline",size:"sm",onClick:()=>s(o),className:`h-8 w-8 p-0 ${o===a?"bg-re-green text-white hover:bg-re-green/90":""}`,"data-testid":`closed-requests-pagination-page-${o}`,children:o},o)),a5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>s(a+1),disabled:a===r,className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-next",children:e.jsx(ss,{className:"h-4 w-4"})})]})]})})})}function IT(t){var s,a,r,n;return{id:t.requestNumber||t.request_number||t.requestId,requestId:t.requestId,displayId:t.requestNumber||t.request_number||t.requestId,title:t.title,description:t.description,status:(t.status||"").toString().toLowerCase(),priority:(t.priority||"").toString().toLowerCase(),initiator:{name:((s=t.initiator)==null?void 0:s.displayName)||((a=t.initiator)==null?void 0:a.email)||"—",avatar:(((r=t.initiator)==null?void 0:r.displayName)||"NA").split(" ").map(i=>i[0]).join("").slice(0,2).toUpperCase()},createdAt:t.submittedAt||t.createdAt||t.created_at||"—",dueDate:t.closureDate||t.closure_date||t.closedAt||void 0,reason:t.conclusionRemark||t.conclusion_remark,department:t.department,totalLevels:t.totalLevels||0,completedLevels:((n=t.summary)==null?void 0:n.approvedLevels)||0,templateType:t.templateType||t.template_type}}function ET(t){return t.map(IT)}function FT({itemsPerPage:t=10}={}){const[s,a]=p.useState([]),[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=p.useCallback(async(h=1,x)=>{try{h===1&&(n(!0),a([]));const u=await ks.listClosedByMe({page:h,limit:t,search:x==null?void 0:x.search,status:x!=null&&x.status&&x.status!=="all"?x.status:void 0,priority:x==null?void 0:x.priority,templateType:x==null?void 0:x.templateType,sortBy:x==null?void 0:x.sortBy,sortOrder:x==null?void 0:x.sortOrder}),g=Array.isArray(u==null?void 0:u.data)?u.data:[],b=ET(g);a(b);const f=u==null?void 0:u.pagination;f&&c({currentPage:f.page||1,totalPages:f.totalPages||1,totalRecords:f.total||0,itemsPerPage:t})}catch(u){console.error("[ClosedRequests] Error fetching requests:",u),a([])}finally{n(!1),l(!1)}},[t]),m=p.useCallback(h=>{l(!0),d(o.currentPage,h)},[d,o.currentPage]);return{requests:s,loading:r,refreshing:i,pagination:o,fetchRequests:d,handleRefresh:m}}const _T={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",sortBy:"created",sortOrder:"desc",currentPage:1},Jp=Br({name:"closedRequests",initialState:_T,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setTemplateTypeFilter:(t,s)=>{t.templateTypeFilter=s.payload},setSortBy:(t,s)=>{t.sortBy=s.payload},setSortOrder:(t,s)=>{t.sortOrder=s.payload},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.templateTypeFilter="all",t.currentPage=1}}}),{setSearchTerm:LT,setStatusFilter:MT,setPriorityFilter:$T,setTemplateTypeFilter:OT,setSortBy:UT,setSortOrder:BT,setCurrentPage:VT,clearFilters:zT}=Jp.actions;function HT({onFiltersChange:t,debounceMs:s=500}={}){const a=Sn(),r=p.useRef(null),n=p.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,sortBy:d,sortOrder:m,currentPage:h}=zr(S=>S.closedRequests),x=p.useCallback(S=>a(LT(S)),[a]),u=p.useCallback(S=>a(MT(S)),[a]),g=p.useCallback(S=>a($T(S)),[a]),b=p.useCallback(S=>a(OT(S)),[a]),f=p.useCallback(S=>a(UT(S)),[a]),y=p.useCallback(S=>a(BT(S)),[a]),v=p.useCallback(S=>a(VT(S)),[a]),w=p.useCallback(()=>({search:i,status:l,priority:o,templateType:c!=="all"?c:void 0,sortBy:d,sortOrder:m}),[i,l,o,c,d,m]);p.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const S=setTimeout(()=>{t&&t(w())},i?s:0);return r.current=S,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,d,m,t,w,s]);const C=p.useCallback(()=>{a(zT())},[a]),k=[i,o!=="all"?o:null,l!=="all"?l:null,c!=="all"?c:null].filter(Boolean).length;return{searchTerm:i,priorityFilter:o,statusFilter:l,templateTypeFilter:c,sortBy:d,sortOrder:m,currentPage:h,setSearchTerm:x,setPriorityFilter:g,setStatusFilter:u,setTemplateTypeFilter:b,setSortBy:f,setSortOrder:y,setCurrentPage:v,clearFilters:C,activeFiltersCount:k,getFilters:w}}function WT({onViewRequest:t}){const s=FT({itemsPerPage:10}),a=p.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=HT(),n=p.useMemo(()=>{try{const h=tt.getUserData();return Eo(h)}catch(h){return console.error("[ClosedRequests] Error getting user filter type:",h),"STANDARD"}},[]),i=p.useMemo(()=>yT(n),[n]),l=n==="DEALER",o=p.useRef({searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,sortBy:r.sortBy,sortOrder:r.sortOrder}),c=p.useRef(!1);p.useEffect(()=>{const h=r.currentPage||1;a.current(h,{search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:!l&&r.priorityFilter!=="all"?r.priorityFilter:void 0,templateType:!l&&r.templateTypeFilter!=="all"?r.templateTypeFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder}),c.current=!0},[l]),p.useEffect(()=>{if(!c.current)return;const h=o.current;if(!(h.searchTerm!==r.searchTerm||h.statusFilter!==r.statusFilter||h.priorityFilter!==r.priorityFilter||h.templateTypeFilter!==r.templateTypeFilter||h.sortBy!==r.sortBy||h.sortOrder!==r.sortOrder))return;const u=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,templateType:r.templateTypeFilter!=="all"?r.templateTypeFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder}),o.current={searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,sortBy:r.sortBy,sortOrder:r.sortOrder}},r.searchTerm!==h.searchTerm?500:0);return()=>clearTimeout(u)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.templateTypeFilter,r.sortBy,r.sortOrder,l]);const d=p.useCallback(h=>{h>=1&&h<=s.pagination.totalPages&&(r.setCurrentPage(h),s.fetchRequests(h,{search:r.searchTerm||void 0,status:r.statusFilter!=="all"?r.statusFilter:void 0,priority:r.priorityFilter!=="all"?r.priorityFilter:void 0,templateType:r.templateTypeFilter!=="all"?r.templateTypeFilter:void 0,sortBy:r.sortBy,sortOrder:r.sortOrder}))},[s,r]),m=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,templateType:r.templateTypeFilter!=="all"?r.templateTypeFilter: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(CT,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:m}),e.jsx(i,{searchTerm:r.searchTerm,priorityFilter:r.priorityFilter,statusFilter:r.statusFilter,templateTypeFilter:r.templateTypeFilter,sortBy:r.sortBy,sortOrder:r.sortOrder,activeFiltersCount:l?[r.searchTerm,r.statusFilter!=="all"?r.statusFilter:null].filter(Boolean).length:r.activeFiltersCount,onSearchChange:r.setSearchTerm,onPriorityChange:r.setPriorityFilter,onStatusChange:r.setStatusFilter,onTemplateTypeChange:r.setTemplateTypeFilter,onSortByChange:r.setSortBy,onSortOrderChange:()=>r.setSortOrder(r.sortOrder==="asc"?"desc":"asc"),onClearFilters:r.clearFilters}),e.jsx(kT,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(RT,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(PT,{pagination:s.pagination,onPageChange:d})]})}function GT(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 YT(t){return GT(t)?"DEALER_CLAIM":"CUSTOM"}function KT(t,s){return`/request/${t}`}class XT 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(E,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(E,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function ZT({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=Ea().requestId||t||"",{user:i}=Kt(),{apiRequest:l,loading:o}=hc(n,a,i);if(o&&!l)return e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx($t,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading request details..."})]})});const c=YT(l),d=fT(c);return e.jsx(d,{requestId:t,onBack:s,dynamicRequests:a})}function JT(t){return e.jsx(XT,{children:e.jsx(ZT,{...t})})}function QT({onViewSummary:t}){const s=Ks(),[a,r]=p.useState([]),[n,i]=p.useState(!0),[l,o]=p.useState(""),[c,d]=p.useState(1),[m,h]=p.useState(1),[x,u]=p.useState(0),g=10,b=p.useCallback(async(w=1)=>{try{i(!0);const C=await aA({page:w,limit:g});r(C.data||[]),h(C.pagination.totalPages||1),u(C.pagination.total||0),d(C.pagination.page||1)}catch(C){console.error("Failed to fetch shared summaries:",C),K.error("Failed to load shared summaries")}finally{i(!1)}},[]);p.useEffect(()=>{b(1)},[b]);const f=async w=>{try{await Up(w),r(C=>C.map(k=>k.sharedSummaryId===w?{...k,isRead:!0,viewedAt:new Date().toISOString()}:k)),t?t(w):s(`/shared-summaries/${w}`)}catch(C){console.error("Failed to mark as viewed:",C),t?t(w):s(`/shared-summaries/${w}`)}},y=w=>{w>=1&&w<=m&&b(w)},v=a.filter(w=>{var k,S,_,D;if(!l)return!0;const C=l.toLowerCase();return((k=w.title)==null?void 0:k.toLowerCase().includes(C))||((S=w.requestNumber)==null?void 0:S.toLowerCase().includes(C))||((_=w.initiatorName)==null?void 0:_.toLowerCase().includes(C))||((D=w.sharedByName)==null?void 0:D.toLowerCase().includes(C))});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(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Oe,{placeholder:"Search by title, request number, or user...",value:l,onChange:w=>o(w.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(lt,{className:"h-8 w-8 animate-spin text-blue-600"})}),!n&&v.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(Re,{className:"h-8 w-8 sm:h-12 sm:w-12 text-gray-400 mx-auto mb-3 sm:mb-4"}),e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-1 sm:mb-2",children:"No shared summaries"}),e.jsx("p",{className:"text-sm sm:text-base text-gray-600",children:l?"No summaries match your search.":"You haven't received any shared summaries yet."})]}),!n&&v.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-3 sm:gap-4 mb-4 sm:mb-6",children:v.map(w=>e.jsx("div",{className:`bg-white rounded-lg shadow-sm border-2 transition-all cursor-pointer hover:shadow-md ${w.isRead?"border-gray-200":"border-blue-300 bg-blue-50"}`,onClick:()=>f(w.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:[w.isRead?e.jsx(h0,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}):e.jsx(ht,{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:w.title}),!w.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:w.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(Vt,{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:w.initiatorName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(Vt,{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:w.sharedByName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(ot,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",He(new Date(w.sharedAt),"MMM dd, yyyy HH:mm")]})]}),w.viewedAt&&e.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[e.jsx(ht,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",He(new Date(w.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(E,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:C=>{C.stopPropagation(),f(w.sharedSummaryId)},children:"View"})]})})},w.sharedSummaryId))}),m>1&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 sm:gap-4 bg-white rounded-lg shadow-sm border border-gray-200 p-3 sm:p-4",children:[e.jsxs("div",{className:"text-xs sm:text-sm text-gray-600 text-center sm:text-left",children:["Showing ",(c-1)*g+1," to ",Math.min(c*g,x)," of ",x," summaries"]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>y(c-1),disabled:c===1,className:"text-xs sm:text-sm",children:"Previous"}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 whitespace-nowrap",children:["Page ",c," of ",m]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>y(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function qT(){const{sharedSummaryId:t}=Ea(),s=Ks(),[a,r]=p.useState(null),[n,i]=p.useState(!0);p.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var m,h;try{i(!0);try{await Up(t)}catch(u){console.warn("Failed to mark as viewed:",u)}const x=await pc(t);r(x)}catch(x){console.error("Failed to fetch summary details:",x),K.error(((h=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:h.message)||"Failed to load summary"),s("/shared-summaries")}finally{i(!1)}})()},[t,s]);const l=d=>{const m=d.toLowerCase();return m==="approved"?e.jsx(De,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(wt,{className:"h-4 w-4 text-red-600"}):m==="pending"||m==="in progress"?e.jsx(st,{className:"h-4 w-4 text-orange-600"}):e.jsx(Re,{className:"h-4 w-4 text-gray-600"})},o=d=>{const m=d.toLowerCase();return m==="approved"?"bg-green-100 text-green-700 border-green-300":m==="rejected"?"bg-red-100 text-red-700 border-red-300":m==="pending"||m==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},c=(d,m)=>d&&d.trim()&&d.trim().toUpperCase()!=="N/A"?d:m&&m.trim()&&m.trim().toUpperCase()!=="N/A"?m:"N/A";return n?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(lt,{className:"h-12 w-12 animate-spin text-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading summary..."})]})}):a?e.jsx("div",{className:"min-h-screen bg-gray-50 p-4 sm:p-6",children:e.jsxs("div",{className:"max-w-5xl mx-auto",children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs(E,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(Ns,{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(ne,{className:o(a.workflow.status),children:[l(a.workflow.status),e.jsx("span",{className:"ml-1 capitalize",children:a.workflow.status})]})]}),a.description&&e.jsx("div",{className:"mb-4",children:e.jsx(sa,{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:He(new Date(a.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),a.approvers&&a.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),a.approvers.map((d,m)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsxs("h4",{className:"text-md font-semibold text-gray-800 mb-3",children:["Approver ",d.levelNumber]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:d.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:c(d.designation,d.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1",children:[l(d.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:d.status})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:He(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(ne,{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(sa,{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(Re,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Summary Not Found"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"The summary you're looking for doesn't exist."}),e.jsx(E,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function e5(){const{requestId:t}=Ea(),s=Ks(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(ys,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(Op,{requestId:t||""})})})}function Qp({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(ne,{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 Bs({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:l,testId:o="stats-card",onClick:c}){return e.jsx(ee,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":o,onClick:c,children:e.jsx(se,{className:"p-3 sm:p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:`text-xs sm:text-sm font-medium ${i}`,"data-testid":`${o}-label`,children:t}),e.jsx("p",{className:`text-xl sm:text-2xl font-bold ${l}`,"data-testid":`${o}-value`,children:s})]}),e.jsx(a,{className:`w-6 h-6 sm:w-8 sm:h-8 ${r}`,"data-testid":`${o}-icon`})]})})})}function t5({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(Bs,{label:"Total",value:t.total,icon:Re,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(Bs,{label:"Pending",value:t.pending,icon:st,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(Bs,{label:"Paused",value:t.paused,icon:za,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(Bs,{label:"Approved",value:t.approved,icon:De,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(Bs,{label:"Rejected",value:t.rejected,icon:wt,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(Bs,{label:"Draft",value:t.draft,icon:go,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(Bs,{label:"Closed",value:t.closed,icon:fo,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 s5({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,onSearchChange:n,onStatusChange:i,onPriorityChange:l,onTemplateTypeChange:o}){return e.jsx(ee,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(se,{className:"p-3 sm:p-4 md:p-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-3 sm:gap-4 items-start md:items-center",children:[e.jsxs("div",{className:"flex-1 relative w-full",children:[e.jsx(Rs,{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(Oe,{placeholder:"Search requests by title, description, or ID...",value:t,onChange:c=>n(c.target.value),className:"pl-9 text-sm sm:text-base bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"search-input"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 w-full md:w-auto",children:[e.jsxs(We,{value:s,onValueChange:i,children:[e.jsx(Ye,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"draft",children:"Draft"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"paused",children:"Paused"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]}),e.jsxs(We,{value:a,onValueChange:l,children:[e.jsx(Ye,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"Priority"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Priority"}),e.jsx(Y,{value:"express",children:"Express"}),e.jsx(Y,{value:"standard",children:"Standard"})]})]}),e.jsxs(We,{value:r,onValueChange:o,children:[e.jsx(Ye,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"Template Type"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]})]})]})})})}function a5(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ha,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ot,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ot,iconColor:"text-gray-600"}}}function r5(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:De,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:wt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:De,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:go,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ze,iconColor:"text-gray-600"}}}const n5=t=>{if(!t)return"";let s=t.replace(/<(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hr|li|main|nav|noscript|ol|p|pre|section|table|tfoot|ul|video)[^>]*>/gi," ");return s=s.replace(//gi," "),s=s.replace(/<[^>]*>/g,""),s=s.replace(/\s+/g," ").trim(),s=s.replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'"),s};function i5({request:t,index:s,onViewRequest:a}){var o;const r=r5(t.status),n=a5(t.priority),i=r.icon,l=n.icon;return e.jsx(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(ee,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(se,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(ne,{variant:"outline",className:`${r.color} border font-medium text-xs shrink-0`,"data-testid":"status-badge",children:[e.jsx(i,{className:"w-3 h-3 mr-1"}),e.jsx("span",{className:"capitalize",children:t.status})]}),(((o=t.pauseInfo)==null?void 0:o.isPaused)||t.isPaused)&&e.jsxs(ne,{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(za,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ne,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(l,{className:"w-3 h-3 mr-1"}),t.priority]}),(()=>{const c=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",d=(c==null?void 0:c.toUpperCase())||"";let m="Non-Templatized",h="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Dealer Claim",h="bg-blue-100 !text-blue-700 border-blue-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(ne,{variant:"outline",className:`${h} 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:n5(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:"})," ",xa(t.submittedDate)]})]})]}),e.jsx(ss,{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(Vt,{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(ta,{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(st,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",xa(t.submittedDate)]})]})]})]})})})})}function l5({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(ee,{"data-testid":"loading-state",children:e.jsx(se,{className:"p-6 text-sm text-gray-600",children:"Loading your requestsâ€Ļ"})});if(t.length===0){const l=a||r!=="all"||n!=="all";return e.jsx(ee,{"data-testid":"empty-state",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(Re,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No requests found"}),e.jsx("p",{className:"text-gray-600",children:l?"Try adjusting your search or filters":"You haven't created any requests yet"})]})})}return e.jsx("div",{className:"space-y-4","data-testid":"my-requests-list",children:t.map((l,o)=>e.jsx(i5,{request:l,index:o,onViewRequest:i},l.id))})}function o5(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 qp(t){return Array.isArray(t)?t.map(o5):[]}function c5({itemsPerPage:t=10}={}){const[s,a]=p.useState([]),[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=p.useCallback(async(m=1,h)=>{try{m===1&&(n(!0),a([]));const x=await ks.listMyInitiatedWorkflows({page:m,limit:t,search:h==null?void 0:h.search,status:h==null?void 0:h.status,priority:h==null?void 0:h.priority,templateType:h==null?void 0:h.templateType}),u=Array.isArray(x==null?void 0:x.data)?x.data:[],g=qp(u);a(g),l(!0);const b=x==null?void 0:x.pagination;b&&c({currentPage:b.page||1,totalPages:b.totalPages||1,totalRecords:b.total||0,itemsPerPage:t})}catch(x){console.error("[MyRequests] Error fetching requests:",x),a([]),l(!0)}finally{n(!1)}},[t]);return{requests:s,loading:r,hasFetchedFromApi:i,pagination:o,fetchMyRequests:d}}const d5={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",currentPage:1},eg=Br({name:"myRequests",initialState:d5,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload,t.currentPage=1},setTemplateTypeFilter:(t,s)=>{t.templateTypeFilter=s.payload,t.currentPage=1},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.templateTypeFilter="all",t.currentPage=1}}}),{setSearchTerm:m5,setStatusFilter:u5,setPriorityFilter:x5,setTemplateTypeFilter:h5,setCurrentPage:p5,clearFilters:g5}=eg.actions;function f5({onFiltersChange:t,debounceMs:s=500}={}){const a=Sn(),r=p.useRef(null),n=p.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d}=zr(y=>y.myRequests),m=p.useCallback(y=>a(m5(y)),[a]),h=p.useCallback(y=>a(u5(y)),[a]),x=p.useCallback(y=>a(x5(y)),[a]),u=p.useCallback(y=>a(h5(y)),[a]),g=p.useCallback(y=>a(p5(y)),[a]),b=p.useCallback(()=>({search:i,status:l,priority:o,templateType:c}),[i,l,o,c]);p.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const y=setTimeout(()=>{t&&t(b())},i?s:0);return r.current=y,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,t,b,s]);const f=p.useCallback(()=>{a(g5())},[a]);return{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d,setSearchTerm:m,setStatusFilter:h,setPriorityFilter:x,setTemplateTypeFilter:u,setCurrentPage:g,getFilters:b,resetFilters:f}}function b5({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=Kt(),r=c5({itemsPerPage:10}),n=p.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=f5(),l=p.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}),o=p.useRef(!1);p.useEffect(()=>{const y=i.currentPage||1;n.current(y,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}),o.current=!0},[]),p.useEffect(()=>{if(!o.current)return;const y=l.current;if(!(y.searchTerm!==i.searchTerm||y.statusFilter!==i.statusFilter||y.priorityFilter!==i.priorityFilter||y.templateTypeFilter!==i.templateTypeFilter))return;const w=setTimeout(()=>{i.setCurrentPage(1),n.current(1,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}),l.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}},i.searchTerm!==y.searchTerm?500:0);return()=>clearTimeout(w)},[i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter]);const[c,d]=p.useState(null),[m,h]=p.useState(!1),x=p.useCallback(async()=>{if(a!=null&&a.userId)try{h(!0);const y=await At.getRequestStats("all",void 0,void 0,void 0,i.priorityFilter!=="all"?i.priorityFilter:void 0,i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0,void 0,a.userId,void 0,void 0,i.searchTerm||void 0,void 0,!0);d({total:y.totalRequests||0,pending:y.openRequests||0,paused:y.pausedRequests||0,approved:y.approvedRequests||0,rejected:y.rejectedRequests||0,draft:y.draftRequests||0,closed:y.closedRequests||0})}catch(y){console.error("Failed to fetch backend stats:",y),d(null)}finally{h(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter,i.templateTypeFilter]);p.useEffect(()=>{const y=setTimeout(()=>{x()},i.searchTerm?500:0);return()=>clearTimeout(y)},[i.searchTerm,i.priorityFilter,i.templateTypeFilter,x]);const u=qp(s),g=r.hasFetchedFromApi?r.requests:u,b=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]),f=p.useCallback(y=>{y>=1&&y<=r.pagination.totalPages&&(i.setCurrentPage(y),r.fetchMyRequests(y,{search:i.searchTerm||void 0,status:i.statusFilter!=="all"?i.statusFilter:void 0,priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0}))},[r,i]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"my-requests-page",children:[e.jsx(Qp,{icon:Re,title:"My Requests",description:"Track and manage all your submitted requests",badge:{value:`${b.total} total`,label:"requests",loading:r.loading||m},testId:"my-requests-header"}),e.jsx(t5,{stats:b,onStatusFilter:y=>{i.setStatusFilter(y)}}),e.jsx(s5,{searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,onSearchChange:i.setSearchTerm,onStatusChange:i.setStatusFilter,onPriorityChange:i.setPriorityFilter,onTemplateTypeChange:i.setTemplateTypeFilter}),e.jsx(l5,{requests:g,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(vr,{currentPage:i.currentPage||r.pagination.currentPage,totalPages:r.pagination.totalPages,totalRecords:r.pagination.totalRecords,itemsPerPage:r.pagination.itemsPerPage,onPageChange:f,loading:r.loading,itemLabel:"requests",testIdPrefix:"my-requests-pagination"})]})}function tg({isOrgLevel:t,isAdmin:s,loading:a,exporting:r,onExport:n}){const i=()=>"All Requests",l=()=>t?"View and filter all organization-wide workflow requests":s?"Viewing requests where you are initiator, approver, or participant":"View and filter your workflow requests";return e.jsxs("div",{className:"flex items-start justify-between gap-4","data-testid":"requests-header-container",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Qp,{icon:Re,title:i(),description:l(),testId:"requests-header"}),e.jsx(ne,{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(E,{onClick:n,disabled:r||a,className:"bg-re-green hover:bg-re-green/90 text-white shrink-0",size:"sm","data-testid":"export-button",children:r?e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function sg({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(Bs,{label:"Total",value:t.total,icon:Re,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(Bs,{label:"Pending",value:t.pending,icon:st,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(Bs,{label:"Paused",value:t.paused,icon:za,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(Bs,{label:"Approved",value:t.approved,icon:De,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(Bs,{label:"Rejected",value:t.rejected,icon:wt,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(Bs,{label:"Closed",value:t.closed,icon:fo,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 y5=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ha,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ot,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ot,iconColor:"text-gray-600"}}},v5=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:De,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:wt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:De,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:go,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:ze,iconColor:"text-gray-600"}}},j5=t=>{if(!t)return"";let s=t.replace(/<(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hr|li|main|nav|noscript|ol|p|pre|section|table|tfoot|ul|video)[^>]*>/gi," ");return s=s.replace(//gi," "),s=s.replace(/<[^>]*>/g,""),s=s.replace(/\s+/g," ").trim(),s=s.replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'"),s};function N5({request:t,index:s,onViewRequest:a}){var o;const r=v5(t.status),n=y5(t.priority),i=r.icon,l=n.icon;return e.jsx(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(ee,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(se,{className:"p-3 sm:p-6",children:e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-base sm:text-lg font-semibold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors line-clamp-2","data-testid":"request-title",children:t.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mb-2",children:[e.jsxs(ne,{variant:"outline",className:`${r.color} border font-medium text-xs shrink-0`,"data-testid":"status-badge",children:[e.jsx(i,{className:"w-3 h-3 mr-1"}),e.jsx("span",{className:"capitalize",children:t.status})]}),(((o=t.pauseInfo)==null?void 0:o.isPaused)||t.isPaused)&&e.jsxs(ne,{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(za,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ne,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(l,{className:"w-3 h-3 mr-1"}),t.priority]}),(()=>{const c=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",d=(c==null?void 0:c.toUpperCase())||"";let m="Non-Templatized",h="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Dealer Claim",h="bg-blue-100 !text-blue-700 border-blue-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(ne,{variant:"outline",className:`${h} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:m})})(),t.department&&e.jsx(ne,{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:j5(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:"})," ",xa(t.submittedDate)]})]})]}),e.jsx(ss,{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(Vt,{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(ta,{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(st,{className:"w-3.5 h-3.5 flex-shrink-0"}),e.jsxs("span",{"data-testid":"submitted-timestamp",children:["Submitted: ",xa(t.submittedDate)]})]})]})]})})})})}function ag({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(ee,{"data-testid":"loading-state",children:e.jsx(se,{className:"p-6 text-sm text-gray-600",children:"Loading requestsâ€Ļ"})}):t.length===0?e.jsx(ee,{"data-testid":"empty-state",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx(Re,{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(N5,{request:n,index:i,onViewRequest:r},n.id))})}const w5={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",slaComplianceFilter:"all",departmentFilter:"all",initiatorFilter:"all",approverFilter:"all",approverFilterType:"current",dateRange:"all",customStartDate:void 0,customEndDate:void 0,showCustomDatePicker:!1,currentPage:1},rg=Br({name:"requests",initialState:w5,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setTemplateTypeFilter:(t,s)=>{t.templateTypeFilter=s.payload},setSlaComplianceFilter:(t,s)=>{t.slaComplianceFilter=s.payload},setDepartmentFilter:(t,s)=>{t.departmentFilter=s.payload},setInitiatorFilter:(t,s)=>{t.initiatorFilter=s.payload},setApproverFilter:(t,s)=>{t.approverFilter=s.payload},setApproverFilterType:(t,s)=>{t.approverFilterType=s.payload},setDateRange:(t,s)=>{t.dateRange=s.payload},setCustomStartDate:(t,s)=>{t.customStartDate=s.payload},setCustomEndDate:(t,s)=>{t.customEndDate=s.payload},setShowCustomDatePicker:(t,s)=>{t.showCustomDatePicker=s.payload},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.templateTypeFilter="all",t.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:C5,setStatusFilter:S5,setPriorityFilter:A5,setTemplateTypeFilter:T5,setSlaComplianceFilter:k5,setDepartmentFilter:R5,setInitiatorFilter:D5,setApproverFilter:P5,setApproverFilterType:I5,setDateRange:Cu,setCustomStartDate:Cl,setCustomEndDate:Sl,setShowCustomDatePicker:Vn,setCurrentPage:E5,clearFilters:F5}=rg.actions;function ng(){const t=Sn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,slaComplianceFilter:i,departmentFilter:l,initiatorFilter:o,approverFilter:c,approverFilterType:d,dateRange:m,customStartDate:h,customEndDate:x,showCustomDatePicker:u,currentPage:g}=zr(j=>j.requests),b=p.useCallback(j=>t(C5(j)),[t]),f=p.useCallback(j=>t(S5(j)),[t]),y=p.useCallback(j=>t(A5(j)),[t]),v=p.useCallback(j=>t(T5(j)),[t]),w=p.useCallback(j=>t(k5(j)),[t]),C=p.useCallback(j=>t(R5(j)),[t]),k=p.useCallback(j=>t(D5(j)),[t]),S=p.useCallback(j=>t(P5(j)),[t]),_=p.useCallback(j=>t(I5(j)),[t]),D=p.useCallback(j=>t(Cu(j)),[t]),A=p.useCallback(j=>t(Cl(j)),[t]),N=p.useCallback(j=>t(Sl(j)),[t]),P=p.useCallback(j=>t(Vn(j)),[t]),R=p.useCallback(j=>t(E5(j)),[t]),O=p.useCallback(()=>({search:s||void 0,status:a!=="all"?a:void 0,priority:r!=="all"?r:void 0,templateType:n!=="all"?n:void 0,slaCompliance:i!=="all"?i:void 0,department:l!=="all"?l:void 0,initiator:o!=="all"?o:void 0,approver:c!=="all"?c:void 0,approverType:c!=="all"?d:void 0,dateRange:m,startDate:h,endDate:x}),[s,a,r,n,i,l,o,c,d,m,h,x]),F=p.useCallback(()=>{t(F5())},[t]),$=p.useCallback(j=>{const U=j;t(Cu(U)),U!=="custom"?(t(Cl(void 0)),t(Sl(void 0)),t(Vn(!1))):t(Vn(!0))},[t]),V=p.useCallback(()=>{h&&x&&(h>x&&(t(Cl(x)),t(Sl(h))),t(Vn(!1)))},[h,x,t]);return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,slaComplianceFilter:i,departmentFilter:l,initiatorFilter:o,approverFilter:c,approverFilterType:d,dateRange:m,customStartDate:h,customEndDate:x,showCustomDatePicker:u,currentPage:g,hasActiveFilters:!!(s||a!=="all"||r!=="all"||n!=="all"||i!=="all"||l!=="all"||o!=="all"||c!=="all"||m!=="all"||h||x),setSearchTerm:b,setStatusFilter:f,setPriorityFilter:y,setTemplateTypeFilter:v,setSlaComplianceFilter:w,setDepartmentFilter:C,setInitiatorFilter:k,setApproverFilter:S,setApproverFilterType:_,setDateRange:D,setCustomStartDate:A,setCustomEndDate:N,setShowCustomDatePicker:P,setCurrentPage:R,getFilters:O,clearFilters:F,handleDateRangeChange:$,handleApplyCustomDate:V}}function hi({filterValue:t,onFilterChange:s,source:a="default"}){const[r,n]=p.useState(""),[i,l]=p.useState([]),[o,c]=p.useState(!1),[d,m]=p.useState(null),[h,x]=p.useState(!1),u=p.useRef(null);p.useEffect(()=>{async function y(){if(t!=="all"&&!d)try{const v=await dr.getUserById(t);v&&(m(v),n(v.displayName||v.email))}catch(v){console.error("Failed to fetch user detail for search:",v)}else t==="all"&&(m(null),n(""))}y()},[t]),p.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const g=p.useCallback(y=>{if(n(y),u.current&&clearTimeout(u.current),!y||y.trim().length<2){l([]),c(!1);return}u.current=setTimeout(async()=>{var v;x(!0);try{const C=((v=(await dr.searchUsers(y.trim(),10,a)).data)==null?void 0:v.data)||[];l(C),c(C.length>0)}catch(w){console.error("Search API failed:",w),l([]),c(!1)}finally{x(!1)}},400)},[a]),b=p.useCallback(y=>{m(y),s(y.userId),n(y.displayName||y.email),c(!1),l([])},[s]),f=p.useCallback(()=>{m(null),s("all"),n(""),c(!1),l([])},[s]);return{searchQuery:r,searchResults:i,showResults:o,selectedUser:d,searching:h,handleSearch:g,handleSelect:b,handleClear:f,setShowResults:c}}function _5(t){var d,m,h,x,u,g,b;const s=t.submittedAt||t.submitted_at||t.createdAt||t.created_at,a=(t.priority||"").toString().toLowerCase(),r=(t.status||"").toString().toUpperCase();let n="—",i="—";const l=t.currentApprover||t.current_approver||t.currentApproverData;if(l)n=l.name||l.approverName||l.displayName||l.email||l.approverEmail||"—";else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const f=t.approvals.find(y=>{const v=(y.status||"").toString().toUpperCase();return v==="PENDING"||v==="IN_PROGRESS"});if(f)n=f.approverName||((d=f.approver)==null?void 0:d.name)||((m=f.approver)==null?void 0:m.displayName)||f.approverEmail||((h=f.approver)==null?void 0:h.email)||"—";else{const v=[...t.approvals].sort((w,C)=>{const k=w.levelNumber||w.level_number||0;return(C.levelNumber||C.level_number||0)-k})[0];v&&(n=v.approverName||((x=v.approver)==null?void 0:x.name)||((u=v.approver)==null?void 0:u.displayName)||v.approverEmail||((g=v.approver)==null?void 0:g.email)||"—")}}const o=t.currentLevel||t.current_level||t.currentLevelNumber||t.current_level_number,c=t.totalLevels||t.total_levels||t.totalLevelsCount||t.total_levels_count;if(o&&c)i=`${o} of ${c}`;else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const f=t.approvals.find(y=>{const v=(y.status||"").toString().toUpperCase();return v==="PENDING"||v==="IN_PROGRESS"});if(f){const y=f.levelNumber||f.level_number||0,v=c||t.approvals.length;i=`${y} of ${v}`}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||((b=t.initiator)==null?void 0:b.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 ig(t){return Array.isArray(t)?t.map(_5):[]}function L5(t,s,a,r,n,i){if(t.length>0){const l=t.length,o=t.filter(u=>{const g=(u.status||"").toString().toUpperCase();return g==="PENDING"||g==="IN_PROGRESS"}).length,c=t.filter(u=>(u.status||"").toString().toUpperCase()==="APPROVED").length,d=t.filter(u=>(u.status||"").toString().toUpperCase()==="REJECTED").length,m=t.filter(u=>(u.status||"").toString().toUpperCase()==="DRAFT").length,h=t.filter(u=>(u.status||"").toString().toUpperCase()==="CLOSED").length,x=t.filter(u=>(u.status||"").toString().toUpperCase()==="PAUSED").length;return{total:l,pending:o,paused:x,approved:c,rejected:d,draft:m,closed:h}}else return s&&a?{total:a.total,pending:a.pending,paused:a.paused||0,approved:a.approved,rejected:a.rejected,draft:a.draft,closed:a.closed}:{total:n||i.length,pending:i.filter(o=>o.status==="pending"||o.status==="in-progress").length,paused:i.filter(o=>o.status==="paused").length,approved:i.filter(o=>o.status==="approved").length,rejected:i.filter(o=>o.status==="rejected").length,draft:i.filter(o=>o.status==="draft").length,closed:i.filter(o=>o.status==="closed").length}}var lg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(fi,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(lg);var M5=lg.exports;const og=bi(M5);var cg={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(fi,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(cg);var $5=cg.exports;const dg=bi($5);Bt.extend(dg);Bt.extend(og);function O5(t,s){let a=[...t];if(s.search){const r=s.search.toLowerCase();a=a.filter(n=>{var i,l,o,c;return((i=n.title)==null?void 0:i.toLowerCase().includes(r))||((l=n.description)==null?void 0:l.toLowerCase().includes(r))||((o=n.requestNumber)==null?void 0:o.toLowerCase().includes(r))||((c=n.request_number)==null?void 0:c.toLowerCase().includes(r))})}if(s.status&&s.status!=="all")if(s.status.toLowerCase()==="pending")a=a.filter(r=>{var l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return(n==="PENDING"||n==="IN_PROGRESS")&&!i});else if(s.status.toLowerCase()==="paused")a=a.filter(r=>{var l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return n==="PAUSED"||i});else{const r=s.status.toUpperCase().replace("-","_");a=a.filter(n=>{var o;const i=(n.status||"").toString().toUpperCase(),l=((o=n.pauseInfo)==null?void 0:o.isPaused)||n.isPaused||!1;return r==="IN_PROGRESS"||r==="IN-PROGRESS"?i==="IN_PROGRESS"&&!l:i===r&&!l})}if(s.priority&&s.priority!=="all"&&(a=a.filter(r=>{var n;return(r.priority||"").toString().toLowerCase()===((n=s.priority)==null?void 0:n.toLowerCase())})),s.department&&s.department!=="all"&&(a=a.filter(r=>{var i;return(r.department||((i=r.initiator)==null?void 0:i.department)||"")===s.department})),s.initiator&&s.initiator!=="all"&&(a=a.filter(r=>{var i,l;return(r.initiatorId||r.initiator_id||((i=r.initiator)==null?void 0:i.userId)||((l=r.initiator)==null?void 0:l.user_id)||(r.initiator&&typeof r.initiator=="object"&&"userId"in r.initiator?r.initiator.userId:null))===s.initiator})),s.approver&&s.approver!=="all"&&((s.approverType||"current")==="current"?a=a.filter(n=>{var l,o,c,d,m,h;return(((l=n.currentApprover)==null?void 0:l.userId)||((o=n.currentApprover)==null?void 0:o.user_id)||((d=(c=n.approvals)==null?void 0:c.find(x=>{const u=(x.status||"").toString().toUpperCase();return u==="IN_PROGRESS"||u==="PENDING"}))==null?void 0:d.approverId)||((h=(m=n.approvals)==null?void 0:m.find(x=>{const u=(x.status||"").toString().toUpperCase();return u==="IN_PROGRESS"||u==="PENDING"}))==null?void 0:h.approver_id)||n.currentApproverId||n.current_approver_id)===s.approver}):a=a.filter(n=>{var l,o;const i=[];return(l=n.currentApprover)!=null&&l.userId&&i.push(n.currentApprover.userId),(o=n.currentApprover)!=null&&o.user_id&&i.push(n.currentApprover.user_id),Array.isArray(n.approvals)&&n.approvals.forEach(c=>{c.approverId&&i.push(c.approverId),c.approver_id&&i.push(c.approver_id)}),i.includes(s.approver||"")})),s.slaCompliance&&s.slaCompliance!=="all"&&(a=a.filter(r=>{var c,d,m,h,x,u,g,b,f,y,v,w;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const C=(r.status||"").toString().toUpperCase();if(!(C==="APPROVED"||C==="REJECTED"||C==="CLOSED"))return!1;const S=((c=r.currentLevelSLA)==null?void 0:c.status)||((m=(d=r.currentApprover)==null?void 0:d.sla)==null?void 0:m.status)||((h=r.sla)==null?void 0:h.status)||((u=(x=r.summary)==null?void 0:x.sla)==null?void 0:u.status);return S?S!=="breached"&&S.toLowerCase()!=="breached":!0}const i=((g=r.currentLevelSLA)==null?void 0:g.status)||((f=(b=r.currentApprover)==null?void 0:b.sla)==null?void 0:f.status)||((y=r.sla)==null?void 0:y.status)||((w=(v=r.summary)==null?void 0:v.sla)==null?void 0:w.status);if(!i)return n==="on-track"||n==="on_track";const o={"on-track":"on_track",on_track:"on_track",approaching:"approaching",critical:"critical",breached:"breached"}[n.toLowerCase()]||n.toLowerCase();return i===o||i.toLowerCase()===o})),s.dateRange){let r=null,n=null;if(s.dateRange==="custom"&&s.startDate&&s.endDate)r=Bt(s.startDate).startOf("day").toDate(),n=Bt(s.endDate).endOf("day").toDate();else{const i=Bt();switch(s.dateRange){case"today":r=i.startOf("day").toDate(),n=i.endOf("day").toDate();break;case"week":r=i.startOf("week").toDate(),n=i.endOf("week").toDate();break;case"month":r=i.startOf("month").toDate(),n=i.endOf("month").toDate();break}}r&&n&&(a=a.filter(i=>{const l=i.submittedAt||i.submission_date||i.submitted_at;if(!l){const m=i.createdAt||i.created_at||i.created_date;if(!m)return!1;const h=Bt(m).startOf("day").toDate(),x=Bt(r).startOf("day").toDate(),u=Bt(n).endOf("day").toDate();return h>=x&&h<=u}const o=Bt(l).startOf("day").toDate(),c=Bt(r).startOf("day").toDate(),d=Bt(n).endOf("day").toDate();return o>=c&&o<=d}))}return a}Bt.extend(og);Bt.extend(dg);function U5(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return He(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function mg(t,s){const a=O5(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var v,w,C,k,S;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),h=((v=c.initiator)==null?void 0:v.displayName)||((w=c.initiator)==null?void 0:w.email)||c.initiatorName||"N/A",x=c.department||((C=c.initiator)==null?void 0:C.department)||"N/A",u=((k=c.currentApprover)==null?void 0:k.displayName)||((S=c.currentApprover)==null?void 0:S.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",b=U5(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),f=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),y=[c.requestNumber||c.request_number||"",`"${(c.title||"").replace(/"/g,'""')}"`,d,m,`"${h.replace(/"/g,'""')}"`,`"${x.replace(/"/g,'""')}"`,`"${u.replace(/"/g,'""')}"`,g,b,`"${f}"`];r.push(y.join(","))});const n=r.join(` -`),i=new Blob([n],{type:"text/csv;charset=utf-8;"}),l=document.createElement("a"),o=URL.createObjectURL(i);l.setAttribute("href",o),l.setAttribute("download",`requests-export-${new Date().toISOString().split("T")[0]}.csv`),l.style.visibility="hidden",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o)}async function B5({page:t,itemsPerPage:s,filters:a,isOrgLevel:r}){var n,i,l,o;if(r){const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(c.templateType=a.templateType),a!=null&&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 ks.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 h=m.filter(g=>(g.status||"").toString().toUpperCase()!=="DRAFT"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:h.length,totalPages:1};return{data:h,allData:[],filteredData:h,pagination:{page:x.page,limit:x.limit||s,total:x.total||h.length,totalPages:x.totalPages||1}}}else{const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(c.templateType=a.templateType),a!=null&&a.department&&a.department!=="all"&&(c.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(c.initiator=a.initiator),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(c.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(c.dateRange=a.dateRange),a!=null&&a.startDate&&(c.startDate=(l=a.startDate)==null?void 0:l.toISOString()),a!=null&&a.endDate&&(c.endDate=(o=a.endDate)==null?void 0:o.toISOString());const d=await ks.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 h=m.filter(u=>(u.status||"").toString().toUpperCase()!=="DRAFT"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:h.length,totalPages:1};return{data:h,allData:[],filteredData:h,pagination:x}}}async function V5(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const l=t?await ks.listWorkflows({page:r,limit:100}):await ks.listParticipantRequests({page:r,limit:100});let o=[];if(Array.isArray(l==null?void 0:l.data)?o=l.data:Array.isArray(l)&&(o=l),o.length>0){const c=o.filter(d=>(d.status||"").toString().toUpperCase()!=="DRAFT");a.push(...c),r++,l!=null&&l.pagination?n=r<=l.pagination.totalPages:n=o.length===100}else n=!1}return a}function z5({onViewRequest:t}){const{user:s}=Kt(),a=zr(I=>I.dashboard.viewAsUser),r=p.useMemo(()=>ki(s),[s]),n=p.useMemo(()=>r&&!a,[r,a]),i=ng(),[l,o]=p.useState([]),[c,d]=p.useState(!1),[m,h]=p.useState(!1),[x,u]=p.useState(null),[g,b]=p.useState([]),[f,y]=p.useState(!1),[v,w]=p.useState(1),[C,k]=p.useState(0),[S]=p.useState(10),_=hi({filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter,source:"local"}),D=hi({filterValue:i.approverFilter,onFilterChange:i.setApproverFilter,source:"local"}),A=p.useCallback(async(I,M,W,G)=>{try{const ce=G==null?void 0:G.slaCompliance;if(ce&&ce!=="all"&&ce!=="breached"&&ce!=="compliant"){const L={};G!=null&&G.search&&(L.search=G.search),G!=null&&G.priority&&G.priority!=="all"&&(L.priority=G.priority),G!=null&&G.department&&G.department!=="all"&&(L.department=G.department),G!=null&&G.initiator&&G.initiator!=="all"&&(L.initiator=G.initiator),G!=null&&G.approver&&G.approver!=="all"&&(L.approver=G.approver,L.approverType=G.approverType||"current"),L.slaCompliance=ce,I&&(L.dateRange=I),M&&(L.startDate=M.toISOString()),W&&(L.endDate=W.toISOString());const z=n?await ks.listWorkflows({page:1,limit:1e3,...L}):await ks.listParticipantRequests({page:1,limit:1e3,...L}),H=Array.isArray(z==null?void 0:z.data)?z.data:[],ye=H.length,ae=H.filter(Ce=>{const Ee=(Ce.status||"").toString().toUpperCase();return Ee==="PENDING"||Ee==="IN_PROGRESS"}).length,me=H.filter(Ce=>(Ce.status||"").toString().toUpperCase()==="APPROVED").length,Q=H.filter(Ce=>(Ce.status||"").toString().toUpperCase()==="REJECTED").length,oe=H.filter(Ce=>(Ce.status||"").toString().toUpperCase()==="CLOSED").length;u({total:ye,pending:ae,paused:0,approved:me,rejected:Q,draft:0,closed:oe})}else{const L=await At.getRequestStats(I,M?M.toISOString():void 0,W?W.toISOString():void 0,void 0,G==null?void 0:G.priority,void 0,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,!n);u({total:L.totalRequests||0,pending:L.openRequests||0,paused:L.pausedRequests||0,approved:L.approvedRequests||0,rejected:L.rejectedRequests||0,draft:L.draftRequests||0,closed:L.closedRequests||0})}}catch(ce){console.error("Failed to fetch backend stats:",ce)}finally{}},[n]),N=p.useCallback(async()=>{try{y(!0);const I=await At.getDepartments();b(I)}catch{}finally{y(!1)}},[]),P=p.useRef(i),R=p.useRef(A);p.useEffect(()=>{P.current=i,R.current=A},[i,A]),p.useEffect(()=>{const I=new URLSearchParams(window.location.search),M=I.get("approver"),W=I.get("approverType"),G=I.get("slaCompliance"),ce=I.get("dateRange"),te=I.get("startDate"),L=I.get("endDate");M&&i.setApproverFilter(M),(W==="current"||W==="any")&&i.setApproverFilterType(W),G&&i.setSlaComplianceFilter(G),ce&&i.setDateRange(ce),te&&i.setCustomStartDate(new Date(te)),L&&i.setCustomEndDate(new Date(L))},[]);const O=p.useCallback(async(I=1)=>{try{I===1&&(d(!0),o([]));const M=P.current.getFilters(),W=await B5({page:I,itemsPerPage:S,filters:M,isOrgLevel:n});o(W.data),i.setCurrentPage(W.pagination.page),w(W.pagination.totalPages),k(W.pagination.total)}catch{o([])}finally{d(!1)}},[S,n]),F=p.useCallback(async()=>{try{h(!0);const I=await V5(n);await mg(I,i.getFilters())}catch(I){console.error("Failed to export requests:",I),alert("Failed to export requests. Please try again.")}finally{h(!1)}},[n,i]);p.useEffect(()=>{N()},[N]),p.useEffect(()=>{const I=setTimeout(()=>{const M={priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0,department:i.departmentFilter!=="all"?i.departmentFilter:void 0,initiator:i.initiatorFilter!=="all"?i.initiatorFilter:void 0,approver:i.approverFilter!=="all"?i.approverFilter:void 0,approverType:i.approverFilter!=="all"?i.approverFilterType:void 0,search:i.searchTerm||void 0,slaCompliance:i.slaComplianceFilter!=="all"?i.slaComplianceFilter:void 0},W=i.dateRange||"all";R.current(W,i.customStartDate,i.customEndDate,M)},i.searchTerm?500:0);return()=>clearTimeout(I)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.templateTypeFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const $=p.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,slaComplianceFilter:i.slaComplianceFilter,departmentFilter:i.departmentFilter,initiatorFilter:i.initiatorFilter,approverFilter:i.approverFilter,approverFilterType:i.approverFilterType,dateRange:i.dateRange,customStartDate:i.customStartDate,customEndDate:i.customEndDate,isOrgLevel:n}),V=p.useRef(!1);p.useEffect(()=>{const I=i.currentPage||1;O(I),V.current=!0},[]),p.useEffect(()=>{if(!V.current)return;const I=$.current;if(!(I.searchTerm!==i.searchTerm||I.statusFilter!==i.statusFilter||I.priorityFilter!==i.priorityFilter||I.templateTypeFilter!==i.templateTypeFilter||I.slaComplianceFilter!==i.slaComplianceFilter||I.departmentFilter!==i.departmentFilter||I.initiatorFilter!==i.initiatorFilter||I.approverFilter!==i.approverFilter||I.approverFilterType!==i.approverFilterType||I.dateRange!==i.dateRange||I.customStartDate!==i.customStartDate||I.customEndDate!==i.customEndDate||I.isOrgLevel!==n))return;const W=setTimeout(()=>{i.setCurrentPage(1),O(1),$.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,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!==I.searchTerm?500:0);return()=>clearTimeout(W)},[n,i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter,i.slaComplianceFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.dateRange,i.customStartDate,i.customEndDate]);const T=p.useCallback(I=>{I>=1&&I<=v&&(i.setCurrentPage(I),O(I))},[v,O,i]),j=p.useMemo(()=>ig(l),[l]),U=p.useMemo(()=>x?{total:x.total||0,pending:x.pending||0,paused:x.paused||0,approved:x.approved||0,rejected:x.rejected||0,draft:x.draft||0,closed:x.closed||0}:L5([],n,x,!1,C,j),[n,x,C,j]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(tg,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:F}),e.jsx(sg,{stats:U,onStatusFilter:I=>{i.setStatusFilter(I)}}),e.jsx(ee,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(se,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ya,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(ne,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),i.hasActiveFilters&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:i.clearFilters,className:"gap-2",children:[e.jsx($t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Ts,{}),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(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Oe,{placeholder:"Search requests...",value:i.searchTerm,onChange:I=>i.setSearchTerm(I.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(We,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"paused",children:"Paused"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]}),e.jsxs(We,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"All Priority"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Priority"}),e.jsx(Y,{value:"express",children:"Express"}),e.jsx(Y,{value:"standard",children:"Standard"})]})]}),e.jsxs(We,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"All Templates"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs(We,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:f||g.length===0,children:[e.jsx(Ye,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ge,{placeholder:f?"Loading...":"All Departments"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Departments"}),g.map(I=>e.jsx(Y,{value:I,children:I},I))]})]}),e.jsxs(We,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"All SLA Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All SLA Status"}),e.jsx(Y,{value:"compliant",children:"Compliant"}),e.jsx(Y,{value:"on-track",children:"On Track"}),e.jsx(Y,{value:"approaching",children:"Approaching"}),e.jsx(Y,{value:"critical",children:"Critical"}),e.jsx(Y,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:_.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:_.selectedUser.displayName||_.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:_.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Oe,{placeholder:"Search initiator...",value:_.searchQuery,onChange:I=>_.handleSearch(I.target.value),onFocus:()=>{_.searchResults.length>0&&_.setShowResults(!0)},onBlur:()=>setTimeout(()=>_.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),_.showResults&&_.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:_.searchResults.map(I=>e.jsx("button",{type:"button",onClick:()=>_.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(re,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(We,{value:i.approverFilterType,onValueChange:I=>i.setApproverFilterType(I),children:[e.jsx(Ye,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"current",children:"Current Only"}),e.jsx(Y,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:D.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:D.selectedUser.displayName||D.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:D.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Oe,{placeholder:"Search approver...",value:D.searchQuery,onChange:I=>D.handleSearch(I.target.value),onFocus:()=>{D.searchResults.length>0&&D.setShowResults(!0)},onBlur:()=>setTimeout(()=>D.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),D.showResults&&D.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:D.searchResults.map(I=>e.jsx("button",{type:"button",onClick:()=>D.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(ot,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(We,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(Ye,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs(Hs,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ot,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${He(i.customStartDate,"MMM d, yyyy")} - ${He(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Gs,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Ms,{value:i.customStartDate||null,onChange:I=>{const M=I?new Date(I):void 0;M?(i.setCustomStartDate(M),i.customEndDate&&M>i.customEndDate&&i.setCustomEndDate(M)):i.setCustomStartDate(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",children:"End Date"}),e.jsx(Ms,{value:i.customEndDate||null,onChange:I=>{const M=I?new Date(I):void 0;M?(i.setCustomEndDate(M),i.customStartDate&&M{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})})]})})]})]})]})})}),e.jsx(ag,{requests:j,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(vr,{currentPage:i.currentPage||1,totalPages:v,totalRecords:C,itemsPerPage:S,onPageChange:T,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function H5({page:t,itemsPerPage:s,filters:a}){const r={};a!=null&&a.search&&(r.search=a.search),a!=null&&a.status&&a.status!=="all"&&(r.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(r.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(r.templateType=a.templateType),a!=null&&a.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 ks.listParticipantRequests({page:t,limit:s,...r});let i=[];Array.isArray(n==null?void 0:n.data)?i=n.data:Array.isArray(n)&&(i=n);const l=i.filter(c=>(c.status||"").toString().toUpperCase()!=="DRAFT"),o=(n==null?void 0:n.pagination)||{page:t,limit:s,total:l.length,totalPages:1};return{data:l,allData:[],filteredData:l,pagination:{page:o.page,limit:o.limit||s,total:o.total||l.length,totalPages:o.totalPages||1}}}const Su=100;async function W5(t){const s=[];let a=!0,r=1;const n=100,i={};for(t!=null&&t.search&&(i.search=t.search),t!=null&&t.status&&t.status!=="all"&&(i.status=t.status),t!=null&&t.priority&&t.priority!=="all"&&(i.priority=t.priority),t!=null&&t.templateType&&t.templateType!=="all"&&(i.templateType=t.templateType),t!=null&&t.department&&t.department!=="all"&&(i.department=t.department),t!=null&&t.initiator&&t.initiator!=="all"&&(i.initiator=t.initiator),t!=null&&t.approver&&t.approver!=="all"&&(i.approver=t.approver,i.approverType=t.approverType||"current"),t!=null&&t.slaCompliance&&t.slaCompliance!=="all"&&(i.slaCompliance=t.slaCompliance),t!=null&&t.dateRange&&(i.dateRange=t.dateRange),t!=null&&t.startDate&&(i.startDate=t.startDate instanceof Date?t.startDate.toISOString():t.startDate),t!=null&&t.endDate&&(i.endDate=t.endDate instanceof Date?t.endDate.toISOString():t.endDate);a&&r<=n;){const l=await ks.listParticipantRequests({page:r,limit:Su,...i});let o=[];if(Array.isArray(l==null?void 0:l.data)?o=l.data:Array.isArray(l)&&(o=l),o.length===0)a=!1;else{const c=o.filter(d=>(d.status||"").toString().toUpperCase()!=="DRAFT");s.push(...c),r++,l!=null&&l.pagination?a=r<=l.pagination.totalPages:a=o.length===Su}}return s}function G5({onViewRequest:t}){const s=ng(),a=p.useMemo(()=>{try{const W=tt.getUserData();return Eo(W)}catch(W){return console.error("[UserAllRequests] Error getting user filter type:",W),"STANDARD"}},[]),r=p.useMemo(()=>vT(a),[a]),n=a==="DEALER",i=p.useCallback(()=>{const W=s.getFilters();if(n){const{priority:G,templateType:ce,department:te,slaCompliance:L,...z}=W;return z}return W},[s,n]),l=p.useCallback(()=>n?!!(s.searchTerm||s.statusFilter!=="all"||s.initiatorFilter!=="all"||s.approverFilter!=="all"||s.dateRange!=="all"||s.customStartDate||s.customEndDate):s.hasActiveFilters,[n,s]),[o,c]=p.useState([]),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(null),[b,f]=p.useState([]),[y,v]=p.useState(!1),[w,C]=p.useState(1),[k,S]=p.useState(0),[_]=p.useState(10),D=hi({filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter,source:"local"}),A=hi({filterValue:s.approverFilter,onFilterChange:s.setApproverFilter,source:"local"}),N=p.useCallback(async(W,G,ce,te)=>{try{const L=await At.getRequestStats(W,G?G.toISOString():void 0,ce?ce.toISOString():void 0,void 0,te==null?void 0:te.priority,te==null?void 0:te.templateType,te==null?void 0:te.department,te==null?void 0:te.initiator,te==null?void 0:te.approver,te==null?void 0:te.approverType,te==null?void 0:te.search,te==null?void 0:te.slaCompliance,!0);g({total:L.totalRequests||0,pending:L.openRequests||0,paused:L.pausedRequests||0,approved:L.approvedRequests||0,rejected:L.rejectedRequests||0,draft:L.draftRequests||0,closed:L.closedRequests||0})}catch(L){console.error("Failed to fetch backend stats:",L)}},[]),P=p.useCallback(async()=>{try{v(!0);const W=await At.getDepartments();f(W)}catch{}finally{v(!1)}},[]),R=p.useRef(s),O=p.useRef(N),F=p.useRef(i);p.useEffect(()=>{R.current=s,O.current=N,F.current=i},[s,N,i]);const $=p.useCallback(async(W=1)=>{try{W===1&&(m(!0),c([]));const G=F.current(),ce=await H5({page:W,itemsPerPage:_,filters:G});c(ce.data),s.setCurrentPage(ce.pagination.page),C(ce.pagination.totalPages),S(ce.pagination.total)}catch{c([])}finally{m(!1)}},[_,s]),V=p.useCallback(async()=>{try{x(!0);const W=i(),G=await W5(W);await mg(G,W)}catch(W){console.error("Failed to export requests:",W),alert("Failed to export requests. Please try again.")}finally{x(!1)}},[i]);p.useEffect(()=>{P()},[P]),p.useEffect(()=>{const W=setTimeout(()=>{const G={initiator:s.initiatorFilter!=="all"?s.initiatorFilter:void 0,approver:s.approverFilter!=="all"?s.approverFilter:void 0,approverType:s.approverFilter!=="all"?s.approverFilterType:void 0,search:s.searchTerm||void 0};n||(s.priorityFilter!=="all"&&(G.priority=s.priorityFilter),s.templateTypeFilter!=="all"&&(G.templateType=s.templateTypeFilter),s.departmentFilter!=="all"&&(G.department=s.departmentFilter),s.slaComplianceFilter!=="all"&&(G.slaCompliance=s.slaComplianceFilter));const ce=s.dateRange==="all"?"all":s.dateRange||"month";O.current(ce,s.customStartDate,s.customEndDate,G)},s.searchTerm?500:0);return()=>clearTimeout(W)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate,s.templateTypeFilter,n]);const T=p.useRef({searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}),j=p.useRef(!1);p.useEffect(()=>{const W=s.currentPage||1;$(W),j.current=!0},[]),p.useEffect(()=>{if(!j.current)return;const W=T.current;if(!(W.searchTerm!==s.searchTerm||W.statusFilter!==s.statusFilter||W.priorityFilter!==s.priorityFilter||W.templateTypeFilter!==s.templateTypeFilter||W.slaComplianceFilter!==s.slaComplianceFilter||W.departmentFilter!==s.departmentFilter||W.initiatorFilter!==s.initiatorFilter||W.approverFilter!==s.approverFilter||W.approverFilterType!==s.approverFilterType||W.dateRange!==s.dateRange||W.customStartDate!==s.customStartDate||W.customEndDate!==s.customEndDate))return;const ce=setTimeout(()=>{s.setCurrentPage(1),$(1),T.current={searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}},s.searchTerm!==W.searchTerm?500:0);return()=>clearTimeout(ce)},[s.searchTerm,s.statusFilter,s.priorityFilter,s.templateTypeFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const U=p.useCallback(W=>{W>=1&&W<=w&&(s.setCurrentPage(W),$(W))},[w,$,s]),I=p.useMemo(()=>ig(o),[o]),M=p.useMemo(()=>{if(u)return{total:u.total||0,pending:u.pending||0,paused:u.paused||0,approved:u.approved||0,rejected:u.rejected||0,draft:u.draft||0,closed:u.closed||0};const W=I.filter(z=>{const H=(z.status||"").toString().toLowerCase();return H==="pending"||H==="in-progress"}).length,G=I.filter(z=>(z.status||"").toString().toLowerCase()==="paused").length,ce=I.filter(z=>(z.status||"").toString().toLowerCase()==="approved").length,te=I.filter(z=>(z.status||"").toString().toLowerCase()==="rejected").length,L=I.filter(z=>(z.status||"").toString().toLowerCase()==="closed").length;return{total:k>0?k:I.length,pending:W,paused:G,approved:ce,rejected:te,draft:0,closed:L}},[u,k,I]);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(tg,{isOrgLevel:!1,isAdmin:!1,loading:d,exporting:h,onExport:V}),e.jsx(sg,{stats:M,onStatusFilter:W=>{s.setStatusFilter(W)}}),e.jsx(r,{searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,departmentFilter:s.departmentFilter,slaComplianceFilter:s.slaComplianceFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate,showCustomDatePicker:s.showCustomDatePicker,departments:b,loadingDepartments:y,initiatorSearch:D,approverSearch:A,onSearchChange:s.setSearchTerm,onStatusChange:s.setStatusFilter,onPriorityChange:s.setPriorityFilter,onTemplateTypeChange:s.setTemplateTypeFilter,onDepartmentChange:s.setDepartmentFilter,onSlaComplianceChange:s.setSlaComplianceFilter,onInitiatorChange:s.setInitiatorFilter,onApproverChange:s.setApproverFilter,onApproverTypeChange:s.setApproverFilterType,onDateRangeChange:s.handleDateRangeChange,onCustomStartDateChange:s.setCustomStartDate,onCustomEndDateChange:s.setCustomEndDate,onShowCustomDatePickerChange:s.setShowCustomDatePicker,onApplyCustomDate:s.handleApplyCustomDate,onClearFilters:s.clearFilters,hasActiveFilters:l()}),e.jsx(ag,{requests:I,loading:d,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(vr,{currentPage:s.currentPage||1,totalPages:w,totalRecords:k,itemsPerPage:_,onPageChange:U,loading:d,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function Y5(){const t=Ks();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(ee,{children:e.jsxs(se,{className:"p-8 text-center",children:[e.jsx(ze,{className:"w-12 h-12 text-yellow-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Approver ID Required"}),e.jsx("p",{className:"text-gray-600",children:"Please select an approver to view their performance details."}),e.jsxs(E,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(Ns,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function K5({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(cs,{className:"h-6 w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Approver Performance Report"}),e.jsx("p",{className:"text-sm text-gray-600",children:t})]})]}),e.jsxs(E,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx($t,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function X5({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(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[s,"%"]}),e.jsx("div",{className:`p-2 rounded-lg ${s>=95?"bg-green-100":s>=90?"bg-blue-100":s>=85?"bg-orange-100":"bg-red-100"}`,children:e.jsx(Ot,{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(na,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.totalApproved}),e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(De,{className:"w-5 h-5 text-blue-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Requests handled"})]})]}),e.jsxs(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[t.avgResponseHours.toFixed(1),"h"]}),e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(bo,{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(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.pendingCount}),e.jsx("div",{className:"p-2 bg-orange-100 rounded-lg",children:e.jsx(st,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function Z5({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(ee,{"data-testid":"approver-actions-stats",children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Approver's Actions"}),e.jsxs($e,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?Cj(a,r,n,""):"(all time)"]})]}),e.jsxs(se,{children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2",children:[e.jsx(cs,{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(De,{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(wt,{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(st,{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(fo,{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(Re,{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(Ot,{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(p0,{className:"w-5 h-5 text-green-600"}),e.jsx("span",{className:"text-xs text-green-600 font-medium",children:(s==null?void 0:s.tatCompliancePercent)!==void 0?`${s.tatCompliancePercent}%`:"N/A"})]}),e.jsx("div",{className:"text-2xl font-bold text-green-700",children:(s==null?void 0:s.withinTatCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"TAT Compliant"})]}),e.jsxs("div",{className:"p-4 bg-red-50 rounded-lg border border-red-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(ze,{className:"w-5 h-5 text-red-600"})}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:(s==null?void 0:s.breachedCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"TAT Breached"})]}),e.jsxs("div",{className:"p-4 bg-purple-50 rounded-lg border border-purple-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(Il,{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 J5({searchTerm:t,statusFilter:s,priorityFilter:a,slaComplianceFilter:r,dateRange:n,customStartDate:i,customEndDate:l,showCustomDatePicker:o,tempCustomStartDate:c,tempCustomEndDate:d,onSearchChange:m,onStatusChange:h,onPriorityChange:x,onSlaComplianceChange:u,onDateRangeChange:g,onShowCustomDatePickerChange:b,onTempStartDateChange:f,onTempEndDateChange:y,onApplyCustomDate:v,onClearFilters:w}){return e.jsxs(ee,{"data-testid":"approver-performance-filters",children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{children:"Filters"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:w,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(se,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Oe,{placeholder:"Search requests...",value:t,onChange:C=>m(C.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(We,{value:s,onValueChange:h,children:[e.jsx(Ye,{"data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]}),e.jsxs(We,{value:a,onValueChange:x,children:[e.jsx(Ye,{"data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"Priority"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Priority"}),e.jsx(Y,{value:"express",children:"Express"}),e.jsx(Y,{value:"standard",children:"Standard"})]})]}),e.jsxs(We,{value:r,onValueChange:u,children:[e.jsx(Ye,{"data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"SLA Compliance"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All SLA"}),e.jsx(Y,{value:"compliant",children:"Compliant"}),e.jsx(Y,{value:"on-track",children:"On Track"}),e.jsx(Y,{value:"approaching",children:"Approaching"}),e.jsx(Y,{value:"critical",children:"Critical"}),e.jsx(Y,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(We,{value:n,onValueChange:g,children:[e.jsx(Ye,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(Hs,{open:o,onOpenChange:b,children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(ot,{className:"w-4 h-4"}),c&&d?`${He(c,"MMM d")} - ${He(d,"MMM d")}`:"Select dates"]})}),e.jsx(Gs,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Oe,{id:"start-date",type:"date",value:c?He(c,"yyyy-MM-dd"):"",onChange:C=>{const k=C.target.value?new Date(C.target.value):void 0;k?(f(k),d&&k>d&&y(k)):f(void 0)},max:He(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Oe,{id:"end-date",type:"date",value:d?He(d,"yyyy-MM-dd"):"",onChange:C=>{const k=C.target.value?new Date(C.target.value):void 0;k?(y(k),c&&k{b(!1),f(i),y(l),(!i||!l)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const Q5=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ta,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ot,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ot,iconColor:"text-gray-600"}}},q5=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:De,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:wt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:st,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:De,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600"}}},ek=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 tk(t){if(!t)return"N/A";try{return He(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function sk(t){if(!t)return"N/A";try{return He(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function pi(t){const{requestId:s,status:a,request:r,navigate:n}=t;if((a==null?void 0:a.toLowerCase())==="draft"||a==="DRAFT"){n(`/edit-request/${s}`);return}const l=KT(s);n(l)}function ak({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o}){const c=Ks();return e.jsxs(ee,{"data-testid":"approver-performance-request-list",children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Request Details"}),e.jsxs($e,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(se,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx($t,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading requests..."})]}):t.length===0?e.jsxs("div",{className:"text-center py-12 text-gray-500","data-testid":"empty-state",children:[e.jsx(Re,{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=Q5(d.priority),h=q5(d.status),x=ek(d.slaStatus||""),u=m.icon,g=h.icon;return e.jsx(ee,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{pi({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":`request-card-${d.requestId}`,children:e.jsx(se,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm text-blue-600 hover:underline","data-testid":"request-number",children:d.requestNumber}),e.jsxs(ne,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(u,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(ne,{className:h.color,"data-testid":"status-badge",children:[e.jsx(g,{className:`w-3 h-3 mr-1 ${h.iconColor}`}),d.status]}),d.approvalStatus&&e.jsx(ne,{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(De,{className:"w-3 h-3 mr-1"}),"Approved"]}):d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(wt,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(st,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(ne,{className:x.color,"data-testid":"sla-status-badge",children:x.label})]}),e.jsx("h3",{className:"font-medium text-gray-900 mb-1 truncate","data-testid":"request-title",children:d.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-500 mt-2",children:[e.jsxs("span",{className:"flex items-center gap-1","data-testid":"initiator-info",children:[e.jsx(Vt,{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(st,{className:"w-3 h-3"}),"Submitted: ",tk(d.submissionDate)]}),d.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(De,{className:"w-3 h-3"}),"Action: ",sk(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(Ot,{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(bo,{className:"w-3 h-3"}),Ft(d.levelElapsedHours)," / ",Ft(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:b=>{b.stopPropagation(),pi({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":"view-request-button",children:e.jsx(ss,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(vr,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function rk(){const[t]=cx(),[s,a]=p.useState(""),[r,n]=p.useState(t.get("status")||"all"),[i,l]=p.useState(t.get("priority")||"all"),[o,c]=p.useState(t.get("slaCompliance")||"all"),[d,m]=p.useState(t.get("dateRange")||"all"),[h,x]=p.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[u,g]=p.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[b,f]=p.useState(!1),[y,v]=p.useState(void 0),[w,C]=p.useState(void 0),k=p.useCallback(()=>{a(""),n("all"),l("all"),c("all"),m("all"),x(void 0),g(void 0),v(void 0),C(void 0),f(!1)},[]),S=p.useCallback(D=>{const A=D;m(A),A!=="custom"?(x(void 0),g(void 0),v(void 0),C(void 0),f(!1)):(v(h),C(u),f(!0))},[h,u]),_=p.useCallback(()=>{if(y&&w){if(y>w){const D=y;x(w),g(D),v(w),C(D)}else x(y),g(w);f(!1)}},[y,w]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:o,dateRange:d,customStartDate:h,customEndDate:u,showCustomDatePicker:b,tempCustomStartDate:y,tempCustomEndDate:w,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:l,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:x,setCustomEndDate:g,setShowCustomDatePicker:f,setTempCustomStartDate:v,setTempCustomEndDate:C,clearFilters:k,handleDateRangeChange:S,handleApplyCustomDate:_}}function nk({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:l,searchTerm:o,itemsPerPage:c}){const[d,m]=p.useState([]),[h,x]=p.useState(null),[u,g]=p.useState([]),[b,f]=p.useState(!0),[y,v]=p.useState(!1),[w,C]=p.useState(1),[k,S]=p.useState(1),[_,D]=p.useState(0),A=p.useRef(!0),N=p.useCallback(async()=>{if(t)try{const F=s==="all"?void 0:s,$=await At.getSingleApproverStats(t,F,a,r,i!=="all"?i:void 0,l!=="all"?l:void 0);x($)}catch(F){console.error("[ApproverPerformance] Failed to fetch approver stats:",F),x(null)}},[t,s,a,r,i,l]),P=p.useCallback(async(F=1)=>{if(!t){f(!1);return}try{f(!0);const $=await At.getRequestsByApprover(t,F,c,s==="all"?void 0:s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,l!=="all"?l:void 0,o||void 0);m($.requests),D($.pagination.totalRecords),S($.pagination.totalPages),C($.pagination.currentPage),g($.requests)}catch($){console.error("Failed to fetch requests:",$)}finally{f(!1),v(!1)}},[t,s,a,r,n,i,l,o,c]);p.useEffect(()=>{A.current&&(A.current=!1,N(),P(1))},[]),p.useEffect(()=>{A.current||N()},[s,a,r,i,l]),p.useEffect(()=>{A.current||P(1)},[s,a,r,n,i,l,o]);const R=p.useCallback(()=>{v(!0),N(),P(1)},[N,P]),O=p.useCallback(F=>{P(F)},[P]);return{requests:d,approverStats:h,allFilteredRequests:u,loading:b,refreshing:y,currentPage:w,totalPages:k,totalRecords:_,handleRefresh:R,handlePageChange:O}}const Au=10;function ik(){const[t]=cx(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=rk(),n=nk({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:Au});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(K5,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(X5,{approverStats:n.approverStats}),n.approverStats&&e.jsx(Z5,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(J5,{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(ak,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:Au,onPageChange:n.handlePageChange})]}):e.jsx(Y5,{})}function lk(){const{user:t}=Kt(),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(ee,{className:"relative overflow-hidden shadow-xl border-0",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(se,{className:"relative z-10 p-8 lg:p-12",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-start md:items-center gap-6",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Zt,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Di,{src:(t==null?void 0:t.picture)||""}),e.jsx(Jt,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),lr(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(hs,{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:[lr(t)&&e.jsxs(ne,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(hs,{className:"w-3 h-3 mr-1"}),"Administrator"]}),Jr(t)&&e.jsxs(ne,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(cs,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(ne,{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(ee,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ge,{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(Vt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx($e,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(se,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Ra,{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(Vt,{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(Vt,{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(Vt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Display Name"}),e.jsx("p",{className:"text-base text-gray-900",children:t.displayName})]})]}),(t==null?void 0:t.phone)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(ji,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Phone"}),e.jsx("p",{className:"text-base text-gray-900",children:t.phone})]})]})]})})]}),e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ge,{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(Pd,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx($e,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(se,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[(t==null?void 0:t.employeeId)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Vt,{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(mo,{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(Pd,{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(hs,{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(ne,{variant:lr(t)||Jr(t)?"default":"secondary",className:lr(t)?"bg-yellow-400 text-slate-900":Jr(t)?"bg-blue-400 text-slate-900":"",children:lr(t)?"Administrator":Jr(t)?"Management":"User"}),(lr(t)||Jr(t))&&e.jsx(De,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ge,{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(ot,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx($e,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-green-50 rounded-lg border border-green-200",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-green-500 rounded-full",children:e.jsx(De,{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(ne,{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 zn="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",ok="https://reflow-uat.royalenfield.com";function Al(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:Al(zn)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Al(zn)})}catch(l){console.warn("[Push] Initial subscription failed, attempting to clear and retry...");try{const o=await t.pushManager.getSubscription();o&&await o.unsubscribe().catch(()=>{}),s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Al(zn)})}catch(o){const c=(l==null?void 0:l.message)||(o==null?void 0:o.message)||"Unknown error";throw c.includes("push service error")||c.includes("Registration failed")?new Error("Push service error: The browser's push service rejected the subscription. This may be due to an invalid VAPID key, network issues, or browser push service problems. Please verify your VAPID key configuration and try again."):new Error(`Failed to subscribe to push notifications: ${c}`)}}}catch(i){const l=(i==null?void 0:i.message)||"Unknown error";throw l.includes("push service error")||l.includes("Registration failed")?new Error("Push service error: The browser's push service rejected the subscription. Please verify your VAPID key is correct and matches the backend configuration. If the problem persists, try clearing your browser cache and service workers."):l.includes("Invalid key")?new Error("Invalid VAPID key format. Please verify that VITE_PUBLIC_VAPID_KEY is correctly set and matches the backend VAPID_PUBLIC_KEY."):new Error(`Failed to subscribe to push notifications: ${l}`)}const a=s.toJSON(),r=!0,n=null;try{const i={"Content-Type":"application/json"},l=await fetch(`${ok}/api/v1/workflows/notifications/subscribe`,{method:"POST",headers:i,credentials:"include",body:JSON.stringify(a)});if(!l.ok){const c=await l.json().catch(()=>({error:"Unknown error"}));throw new Error((c==null?void 0:c.error)||(c==null?void 0:c.message)||`Server error: ${l.status}`)}const o=await l.json();if(!o.success)throw new Error(o.error||"Failed to save subscription")}catch(i){throw i instanceof Error&&i.message.includes("Failed")?i:new Error(`Failed to save subscription to server: ${(i==null?void 0:i.message)||"Network error"}`)}return s}async function mk(){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 ck()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await dk(s)}catch(a){throw a}}function uk({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const l=p.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(jf,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:ke("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(Nf,{"data-slot":"slider-track",className:ke("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(wf,{"data-slot":"slider-range",className:ke("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:l.length},(o,c)=>e.jsx(Cf,{"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 xk({onConfigUpdate:t}){const[s,a]=p.useState([]),[r,n]=p.useState(!0),[i,l]=p.useState(null),[o,c]=p.useState(null),[d,m]=p.useState({}),[h,x]=p.useState(null);p.useEffect(()=>{u()},[]);const u=async()=>{var N,P;try{n(!0),c(null);const R=await X2();a(R)}catch(R){c(((P=(N=R.response)==null?void 0:N.data)==null?void 0:P.error)||"Failed to load configurations")}finally{n(!1)}},g=async N=>{var P,R;try{l(N.configKey),c(null);const O=d[N.configKey]??N.configValue;if(N.validationRules){const F=parseFloat(O);if(N.valueType==="NUMBER"){if(N.validationRules.min!==void 0&&FN.validationRules.max)throw new Error(`Value must be at most ${N.validationRules.max}`)}}await Z2(N.configKey,O),a(F=>F.map($=>$.configKey===N.configKey?{...$,configValue:O}:$)),m(F=>{const $={...F};return delete $[N.configKey],$}),x(`${N.displayName} updated successfully`),setTimeout(()=>x(null),3e3),t&&t()}catch(O){c(O.message||((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to save configuration")}finally{l(null)}},b=async N=>{var P,R;if(confirm(`Reset "${N.displayName}" to default value?`))try{l(N.configKey),c(null),await J2(N.configKey),a(O=>O.map(F=>F.configKey===N.configKey?{...F,configValue:F.defaultValue||""}:F)),m(O=>{const F={...O};return delete F[N.configKey],F}),x(`${N.displayName} reset to default`),setTimeout(()=>x(null),3e3)}catch(O){c(((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to reset configuration")}finally{l(null)}},f=(N,P)=>{m(R=>({...R,[N]:P}))},y=N=>d[N.configKey]??N.configValue,v=N=>d[N.configKey]!==void 0&&d[N.configKey]!==N.configValue,w=N=>{var O,F,$,V;const P=y(N),R=i===N.configKey;if(!N.isEditable)return e.jsxs("div",{className:"p-3 bg-slate-100 border border-slate-200 rounded-md",children:[e.jsx("p",{className:"text-sm text-slate-700 font-mono",children:N.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(ze,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(N.uiComponent||N.valueType.toLowerCase()){case"toggle":return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${P==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${P==="true"?"text-green-700":"text-slate-600"}`,children:P==="true"?"Enabled":"Disabled"})]}),e.jsx(on,{checked:P==="true",onCheckedChange:I=>f(N.configKey,I?"true":"false"),disabled:R})]});case"slider":const T=parseInt(P)||0,j=((O=N.validationRules)==null?void 0:O.min)||0,U=((F=N.validationRules)==null?void 0:F.max)||100;return e.jsxs("div",{className:"space-y-3 p-3 bg-slate-50 border border-slate-200 rounded-md",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-lg font-semibold text-slate-900",children:[T,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",j,"-",U]})]}),e.jsx(uk,{value:[T],min:j,max:U,step:1,onValueChange:([I])=>{I!==void 0&&f(N.configKey,I.toString())},disabled:R,className:"w-full"})]});case"number":return e.jsx(Oe,{type:"number",value:P,onChange:I=>f(N.configKey,I.target.value),disabled:R,min:($=N.validationRules)==null?void 0:$.min,max:(V=N.validationRules)==null?void 0:V.max,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"});case"text":case"input":default:return e.jsx(Oe,{type:"text",value:P,onChange:I=>f(N.configKey,I.target.value),disabled:R,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},C=N=>{switch(N){case"TAT_SETTINGS":return e.jsx(st,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Re,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(qs,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(qu,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(wn,{className:"w-5 h-5"});default:return e.jsx(Va,{className:"w-5 h-5"})}},k=["DASHBOARD_LAYOUT"],S=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],_=s.filter(N=>!k.includes(N.configCategory)&&!S.includes(N.configKey)),D=_.reduce((N,P)=>(N[P.configCategory]||(N[P.configCategory]=[]),N[P.configCategory].push(P),N),{});if(Object.keys(D).forEach(N=>{const P=D[N];P&&P.sort((R,O)=>R.sortOrder-O.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(lt,{className:"w-8 h-8 animate-spin text-gray-400"})});if(_.length===0)return e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(Va,{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 A=Object.keys(D);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(De,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:h})]}),o&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:o}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs($i,{defaultValue:A[0],className:"w-full",children:[e.jsx(Oi,{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:A.map(N=>e.jsx(qt,{value:N,className:"flex-1 min-w-[120px] text-[10px] xs:text-xs sm:text-sm font-medium py-2 sm:py-2.5 px-2 sm:px-3 rounded-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-slate-900 transition-all",children:e.jsx("span",{className:"truncate block",children:N.replace(/_/g," ")})},N))}),A.map(N=>{var P,R,O;return e.jsx(es,{value:N,className:"space-y-4 mt-6",children:e.jsxs(ee,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{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:C(N)})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-slate-900",children:N.replace(/_/g," ")}),e.jsxs($e,{className:"text-sm",children:[((P=D[N])==null?void 0:P.length)||0," setting",(((R=D[N])==null?void 0:R.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(se,{className:"space-y-6",children:(O=D[N])==null?void 0:O.map(F=>e.jsxs("div",{className:"space-y-3 pb-6 border-b border-slate-100 last:border-b-0 last:pb-0 hover:bg-slate-50/50 -mx-6 px-6 py-4 rounded-md transition-colors",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[e.jsx(re,{className:"text-sm font-semibold text-slate-900",children:F.displayName}),v(F)&&e.jsx(ne,{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"}),F.requiresRestart&&e.jsx(ne,{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"})]}),F.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:F.description}),F.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:F.defaultValue})]})]})}),w(F),F.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(E,{size:"sm",onClick:()=>g(F),disabled:!v(F)||i===F.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===F.configKey?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ox,{className:"w-4 h-4"}),"Save Changes"]})}),F.defaultValue&&e.jsxs(E,{size:"sm",variant:"outline",onClick:()=>b(F),disabled:i===F.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(g0,{className:"w-4 h-4"}),"Reset to Default"]})]})]},F.configKey))})]})},N)})]})]})}function hk(){const[t,s]=p.useState([]),[a,r]=p.useState(!0),[n,i]=p.useState(new Date().getFullYear()),[l,o]=p.useState(!1),[c,d]=p.useState(null),[m,h]=p.useState(null),[x,u]=p.useState(null),[g,b]=p.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});p.useEffect(()=>{f()},[n]);const f=async()=>{var N,P;try{r(!0),h(null);const R=await Q2(n);s(R)}catch(R){h(((P=(N=R.response)==null?void 0:N.data)==null?void 0:P.error)||"Failed to load holidays")}finally{r(!1)}},y=()=>{b({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),o(!0)},v=N=>{b({holidayDate:N.holidayDate,holidayName:N.holidayName,description:N.description||"",holidayType:N.holidayType,isRecurring:N.isRecurring}),d(N),o(!0)},w=()=>{if(c)return;const N=new Date;return N.setDate(N.getDate()+1),N.toISOString().split("T")[0]},C=async()=>{var N,P;try{if(h(null),!g.holidayDate||!g.holidayName){h("Holiday date and name are required");return}c?(await eS(c.holidayId,g),u("Holiday updated successfully")):(await q2(g),u("Holiday created successfully")),await f(),o(!1),setTimeout(()=>u(null),3e3)}catch(R){h(((P=(N=R.response)==null?void 0:N.data)==null?void 0:P.error)||"Failed to save holiday")}},k=async N=>{var P,R;if(confirm(`Delete "${N.holidayName}"?`))try{h(null),await tS(N.holidayId),u("Holiday deleted successfully"),await f(),setTimeout(()=>u(null),3e3)}catch(O){h(((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to delete holiday")}},S=N=>{switch(N){case"NATIONAL":return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300";case"REGIONAL":return"bg-gradient-to-r from-blue-50 to-cyan-50 text-blue-800 border-blue-300";case"ORGANIZATIONAL":return"bg-gradient-to-r from-purple-50 to-violet-50 text-purple-800 border-purple-300";case"OPTIONAL":return"bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-300"}},_=Array.from({length:5},(N,P)=>new Date().getFullYear()-1+P),D=t.reduce((N,P)=>{const R=new Date(P.holidayDate).toLocaleString("default",{month:"long"});return N[R]||(N[R]=[]),N[R].push(P),N},{}),A=Object.keys(D).sort((N,P)=>{const R=new Date(Date.parse(N+" 1, 2000")).getMonth(),O=new Date(Date.parse(P+" 1, 2000")).getMonth();return R-O});return e.jsxs("div",{className:"space-y-6",children:[x&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(De,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:x})]}),m&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:m}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>h(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ge,{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(ot,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx($e,{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(We,{value:n.toString(),onValueChange:N=>i(parseInt(N)),children:[e.jsx(Ye,{className:"w-24 sm:w-32 border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm",children:e.jsx(Ge,{})}),e.jsx(Ke,{className:"rounded-md",children:_.map(N=>e.jsx(Y,{value:N.toString(),children:N},N))})]}),e.jsxs(E,{onClick:y,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(gs,{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(lt,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(ot,{className:"w-10 h-10 text-slate-400"})}),e.jsxs("p",{className:"text-slate-700 font-medium text-lg",children:["No holidays found for ",n]}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 mb-6",children:"Add holidays to exclude them from TAT calculations"}),e.jsxs(E,{onClick:y,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(gs,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:A.map(N=>{var P,R,O;return e.jsxs(ee,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{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(fe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[N," ",n]}),e.jsxs($e,{className:"text-xs sm:text-sm",children:[((P=D[N])==null?void 0:P.length)||0," holiday",(((R=D[N])==null?void 0:R.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(ot,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(se,{className:"space-y-3 pt-4",children:(O=D[N])==null?void 0:O.map(F=>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:F.holidayName}),e.jsx(ne,{variant:"outline",className:`${S(F.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:F.holidayType}),F.isRecurring&&e.jsx(ne,{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:Yx(F.holidayDate)}),F.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:F.description})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>v(F),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>k(F),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(yo,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},F.holidayId))})]},N)})}),e.jsx(pt,{open:l,onOpenChange:o,children:e.jsxs(dt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(gt,{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(ot,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(mt,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(Dt,{className:"text-sm text-slate-600 mt-1",children:c?"Update holiday information":"Add a new holiday to the calendar for TAT calculations"})]})]})}),e.jsxs("div",{className:"space-y-5 py-6 px-6 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"date",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Oe,{id:"date",type:"date",value:g.holidayDate,onChange:N=>b({...g,holidayDate:N.target.value}),min:w(),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:c?"Select the holiday date":"Select the holiday date (minimum: tomorrow)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"name",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Holiday Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Oe,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:N=>b({...g,holidayName:N.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the official name of the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"description",className:"text-sm font-semibold text-slate-900",children:["Description ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Oe,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:N=>b({...g,description:N.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional description or notes about the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(We,{value:g.holidayType,onValueChange:N=>b({...g,holidayType:N}),children:[e.jsx(Ye,{id:"type",className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm",children:e.jsx(Ge,{})}),e.jsxs(Ke,{className:"rounded-lg",children:[e.jsx(Y,{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(Y,{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(Y,{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(Y,{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:()=>b({...g,isRecurring:!g.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:g.isRecurring,onChange:N=>b({...g,isRecurring:N.target.checked}),className:"mt-0.5 rounded border-slate-300 text-re-green focus:ring-2 focus:ring-re-green/20 focus:ring-offset-0 w-4 h-4 cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(re,{htmlFor:"recurring",className:"font-semibold cursor-pointer text-sm text-slate-900 block mb-1",children:"Recurring Holiday"}),e.jsx("p",{className:"text-xs text-slate-600",children:"This holiday will automatically repeat every year on the same date"})]})]})]}),e.jsxs(Tt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(E,{variant:"outline",onClick:()=>o(!1),className:"h-11 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:"Cancel"}),e.jsxs(E,{onClick:C,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(ot,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function pk(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function gk(){const[t,s]=p.useState(""),[a,r]=p.useState([]),[n,i]=p.useState(!1),[l,o]=p.useState(null),[c,d]=p.useState("USER"),[m,h]=p.useState(!1),[x,u]=p.useState(null),[g,b]=p.useState([]),[f,y]=p.useState(!1),[v,w]=p.useState({admins:0,management:0,users:0}),[C,k]=p.useState("ELEVATED"),[S,_]=p.useState(1),[D,A]=p.useState(1),[N,P]=p.useState(0),R=10,O=p.useRef(null),F=p.useRef(null),$=p.useCallback(pk(async L=>{var z,H,ye;if(!L||!L.startsWith("@")||L.length<2){r([]),i(!1);return}i(!0);try{const ae=L.slice(1),Q=((z=(await dr.searchUsers(ae,20)).data)==null?void 0:z.data)||[];r(Q)}catch(ae){console.error("Search failed:",ae),u({type:"error",text:((ye=(H=ae.response)==null?void 0:H.data)==null?void 0:ye.message)||"Failed to search users"})}finally{i(!1)}},300),[]),V=L=>{const z=L.target.value;s(z),$(z)},T=async L=>{o(L),s(L.email),r([]);const z=g.find(H=>H.email.toLowerCase()===L.email.toLowerCase()||H.userId===L.userId);if(z&&z.role)d(z.role);else try{const ye=(await dr.getAllUsers()).find(ae=>ae.email&&ae.email.toLowerCase()===L.email.toLowerCase()||ae.userId&&ae.userId===L.userId);ye&&ye.role?d(ye.role):d("USER")}catch(H){console.error("Failed to check user role:",H),d("USER")}},j=async()=>{var L,z;if(!l||!c){u({type:"error",text:"Please select a user and role"});return}h(!0),u(null);try{await dr.assignRole(l.email,c),u({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await U(),await I()}catch(H){console.error("Role assignment failed:",H),u({type:"error",text:((z=(L=H.response)==null?void 0:L.data)==null?void 0:z.error)||"Failed to assign role"})}finally{h(!1)}},U=async(L=S)=>{var z,H,ye,ae,me,Q;y(!0);try{const oe=await dr.getUsersByRole(C,L,R),Ce=((H=(z=oe.data)==null?void 0:z.data)==null?void 0:H.users)||[],Ee=(ae=(ye=oe.data)==null?void 0:ye.data)==null?void 0:ae.pagination,be=(Q=(me=oe.data)==null?void 0:me.data)==null?void 0:Q.summary;b(Ce),Ee&&(_(Ee.currentPage),A(Ee.totalPages),P(Ee.totalUsers)),be&&w({admins:be.ADMIN||0,management:be.MANAGEMENT||0,users:be.USER||0})}catch(oe){console.error("Failed to fetch users:",oe)}finally{y(!1)}},I=async()=>{var L,z,H,ye,ae,me;try{const Q=await dr.getRoleStatistics(),oe=((z=(L=Q.data)==null?void 0:L.data)==null?void 0:z.statistics)||((H=Q.data)==null?void 0:H.statistics)||[];w({admins:parseInt(((ye=oe.find(Ce=>Ce.role==="ADMIN"))==null?void 0:ye.count)||"0"),management:parseInt(((ae=oe.find(Ce=>Ce.role==="MANAGEMENT"))==null?void 0:ae.count)||"0"),users:parseInt(((me=oe.find(Ce=>Ce.role==="USER"))==null?void 0:me.count)||"0")})}catch(Q){console.error("Failed to fetch statistics:",Q)}};p.useEffect(()=>{U(1),I()},[C]);const M=L=>{k(L),_(1)},W=L=>{U(L)},G=L=>{k(L),_(1),requestAnimationFrame(()=>{const z=F.current;z&&z.scrollIntoView({behavior:"smooth",block:"start"})})};p.useEffect(()=>{const L=z=>{O.current&&!O.current.contains(z.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L)}},[a]);const ce=L=>{switch(L){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"}},te=L=>{switch(L){case"ADMIN":return e.jsx(Ln,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(cs,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(Vt,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(ee,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{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(f0,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx($e,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6",children:[e.jsx(ee,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${C==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>G("ADMIN"),children:e.jsx(se,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Administrators"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"admin-count",children:v.admins}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1 font-semibold",children:C==="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(Ln,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(ee,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${C==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>G("MANAGEMENT"),children:e.jsx(se,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Management"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"management-count",children:v.management}),e.jsx("p",{className:"text-xs text-blue-700 mt-1 font-semibold",children:C==="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(cs,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(ee,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${C==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>G("USER"),children:e.jsx(se,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Regular Users"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"user-count",children:v.users}),e.jsx("p",{className:"text-xs text-gray-700 mt-1 font-semibold",children:C==="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(Vt,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(Ts,{}),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:O,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(Oe,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:V,className:"pl-10 pr-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"user-search-input"}),n&&e.jsx(lt,{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(L=>e.jsxs("button",{onClick:()=>T(L),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${L.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:L.displayName||L.email}),e.jsx("p",{className:"text-xs text-gray-600",children:L.email}),L.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[L.department,L.designation?` â€ĸ ${L.designation}`:""]})]},L.userId))})]})]}),l&&e.jsx("div",{className:"border-2 border-slate-300 bg-gradient-to-br from-slate-100 to-slate-50 rounded-lg p-4 shadow-sm",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-gradient-to-br from-slate-700 to-slate-500 flex items-center justify-center text-white font-bold shadow-md",children:(l.displayName||l.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-slate-900",children:l.displayName||l.email}),e.jsx("p",{className:"text-sm text-slate-600",children:l.email}),l.department&&e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:[l.department,l.designation?` â€ĸ ${l.designation}`:""]})]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>{o(null),s("")},className:"hover:bg-slate-200",children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Select Role"}),e.jsxs(We,{value:c,onValueChange:L=>d(L),children:[e.jsx(Ye,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(Ge,{placeholder:"Select role"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(Y,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(Y,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ln,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(E,{onClick:j,disabled:!l||m,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"assign-role-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hs,{className:"w-4 h-4 mr-2"}),"Assign Role"]})}),x&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${x.type==="success"?"border-green-200 bg-green-50":"border-red-200 bg-red-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[x.type==="success"?e.jsx(De,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(ze,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${x.type==="success"?"text-green-800":"text-red-800"}`,children:x.text})]})})]})]}),e.jsx(Ts,{}),e.jsxs("div",{ref:F,children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"User Management"}),e.jsxs("p",{className:"text-sm text-gray-600",children:["View and manage user roles (",N," ",C!=="ALL"&&C!=="ELEVATED"?C.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(We,{value:C,onValueChange:M,children:[e.jsx(Ye,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Ge,{placeholder:"Filter by role"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",v.admins+v.management,")"]})]})}),e.jsx(Y,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ln,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",v.admins,")"]})]})}),e.jsx(Y,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",v.management,")"]})]})}),e.jsx(Y,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",v.users,")"]})]})}),e.jsx(Y,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",v.admins+v.management+v.users,")"]})]})})]})]})})]}),e.jsx("div",{className:"pt-2",children:f?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(lt,{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(cs,{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:C==="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(L=>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-${L.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 ${ce(L.role)} flex items-center justify-center shadow-sm`,children:te(L.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:L.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:L.email}),L.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[L.department,L.designation?` â€ĸ ${L.designation}`:""]})]})]}),e.jsx(ne,{className:`${ce(L.role)} shrink-0`,"data-testid":`role-badge-${L.role}`,children:L.role})]})},L.userId))}),D>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(S-1)*R+1," to ",Math.min(S*R,N)," of ",N," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>W(S-1),disabled:S===1,"data-testid":"prev-page-button",children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,D)},(L,z)=>{let H;return D<=5||S<=3?H=z+1:S>=D-2?H=D-4+z:H=S-2+z,e.jsx(E,{variant:S===H?"default":"outline",size:"sm",onClick:()=>W(H),className:`w-9 h-9 p-0 ${S===H?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${H}-button`,children:H},H)})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>W(S+1),disabled:S===D,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function fk(){const[t,s]=p.useState([]),[a,r]=p.useState(!0),[n,i]=p.useState(!1),[l,o]=p.useState(null),[c,d]=p.useState(null),[m,h]=p.useState(null),[x,u]=p.useState({title:"",itemCode:"",taxationType:"",sapRefNo:""});p.useEffect(()=>{g()},[]);const g=async()=>{var k,S;try{r(!0),d(null);const _=await aS(!1);s(_)}catch(_){const D=((S=(k=_.response)==null?void 0:k.data)==null?void 0:S.error)||"Failed to load activity types";d(D),K.error(D)}finally{r(!1)}},b=()=>{u({title:"",itemCode:"",taxationType:"",sapRefNo:""}),o(null),i(!0)},f=k=>{u({title:k.title,itemCode:k.itemCode||"",taxationType:k.taxationType||"",sapRefNo:k.sapRefNo||""}),o(k),i(!0)},y=async()=>{var k,S;try{if(d(null),!x.title.trim()){d("Activity type title is required");return}const _={title:x.title.trim(),itemCode:x.itemCode.trim()||null,taxationType:x.taxationType.trim()||null,sapRefNo:x.sapRefNo.trim()||null};l?(await nS(l.activityTypeId,_),h("Activity type updated successfully"),K.success("Activity type updated successfully")):(await rS(_),h("Activity type created successfully"),K.success("Activity type created successfully")),await g(),i(!1),setTimeout(()=>h(null),3e3)}catch(_){const D=((S=(k=_.response)==null?void 0:k.data)==null?void 0:S.error)||"Failed to save activity type";d(D),K.error(D)}},v=async k=>{var S,_;if(confirm(`Delete "${k.title}"? This will deactivate the activity type.`))try{d(null),await iS(k.activityTypeId),h("Activity type deleted successfully"),K.success("Activity type deleted successfully"),await g(),setTimeout(()=>h(null),3e3)}catch(D){const A=((_=(S=D.response)==null?void 0:S.data)==null?void 0:_.error)||"Failed to delete activity type";d(A),K.error(A)}},w=t.filter(k=>k.isActive!==!1&&k.isActive!==void 0),C=t.filter(k=>k.isActive===!1);return e.jsxs("div",{className:"space-y-6",children:[m&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(De,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:m})]}),c&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:c}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>d(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ge,{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(Re,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Activity Types"}),e.jsx($e,{className:"text-sm",children:"Manage dealer claim activity types"})]})]}),e.jsxs(E,{onClick:b,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm",children:[e.jsx(gs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Add Activity Type"}),e.jsx("span",{className:"xs:hidden",children:"Add"})]})]})})}),a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(lt,{className:"w-8 h-8 animate-spin text-gray-400"})}):w.length===0?e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(Re,{className:"w-10 h-10 text-slate-400"})}),e.jsx("p",{className:"text-slate-700 font-medium text-lg",children:"No activity types found"}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 mb-6",children:"Add activity types for dealer claim management"}),e.jsxs(E,{onClick:b,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(gs,{className:"w-4 h-4"}),"Add First Activity Type"]})]})}):e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(ee,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Active Activity Types"}),e.jsxs($e,{className:"text-xs sm:text-sm",children:[w.length," active type",w.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-green-50 rounded-md",children:e.jsx(De,{className:"w-4 h-4 text-green-600"})})]})}),e.jsx(se,{className:"space-y-3 pt-4",children:w.map(k=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 hover:border-slate-300 transition-all shadow-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-900 text-sm sm:text-base",children:k.title}),e.jsx(ne,{variant:"outline",className:"bg-gradient-to-r from-green-50 to-emerald-50 text-green-800 border-green-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Active"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs sm:text-sm text-slate-600",children:[k.itemCode&&e.jsxs("span",{className:"font-medium",children:["Item Code: ",e.jsx("span",{className:"text-slate-900",children:k.itemCode})]}),k.taxationType&&e.jsxs("span",{className:"font-medium",children:["Taxation: ",e.jsx("span",{className:"text-slate-900",children:k.taxationType})]}),k.sapRefNo&&e.jsxs("span",{className:"font-medium",children:["SAP Ref: ",e.jsx("span",{className:"text-slate-900",children:k.sapRefNo})]}),!k.itemCode&&!k.taxationType&&!k.sapRefNo&&e.jsx("span",{className:"text-slate-500 italic",children:"No additional details"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>f(k),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>v(k),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(yo,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},k.activityTypeId))})]}),C.length>0&&e.jsxs(ee,{className:"shadow-lg border-0 rounded-md border-amber-200",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Inactive Activity Types"}),e.jsxs($e,{className:"text-xs sm:text-sm",children:[C.length," inactive type",C.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-amber-50 rounded-md",children:e.jsx(ze,{className:"w-4 h-4 text-amber-600"})})]})}),e.jsx(se,{className:"space-y-3 pt-4",children:C.map(k=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-amber-50/50 border border-amber-200 rounded-md hover:bg-amber-50 hover:border-amber-300 transition-all shadow-sm",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-700 text-sm sm:text-base line-through",children:k.title}),e.jsx(ne,{variant:"outline",className:"bg-gradient-to-r from-amber-50 to-orange-50 text-amber-800 border-amber-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Inactive"})]})}),e.jsx("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>f(k),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]})})]},k.activityTypeId))})]})]}),e.jsx(pt,{open:n,onOpenChange:i,children:e.jsxs(dt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(gt,{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(Re,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(mt,{className:"text-xl font-semibold text-slate-900",children:l?"Edit Activity Type":"Add New Activity Type"}),e.jsx(Dt,{className:"text-sm text-slate-600 mt-1",children:l?"Update activity type information":"Add a new activity type for dealer claim management"})]})]})}),e.jsxs("div",{className:"space-y-5 py-6 px-6 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"title",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Title ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Oe,{id:"title",placeholder:"e.g., Riders Mania Claims, Legal Claims Reimbursement",value:x.title,onChange:k=>u({...x,title:k.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the activity type title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"itemCode",className:"text-sm font-semibold text-slate-900",children:["Item Code ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Oe,{id:"itemCode",placeholder:"e.g., 1, 2, 3",value:x.itemCode,onChange:k=>u({...x,itemCode:k.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional item code for the activity type"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"taxationType",className:"text-sm font-semibold text-slate-900",children:["Taxation Type ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Oe,{id:"taxationType",placeholder:"e.g., GST, VAT, Exempt",value:x.taxationType,onChange:k=>u({...x,taxationType:k.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 taxation type for the activity"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"sapRefNo",className:"text-sm font-semibold text-slate-900",children:["SAP Reference Number ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Oe,{id:"sapRefNo",placeholder:"e.g., SAP-12345",value:x.sapRefNo,onChange:k=>u({...x,sapRefNo:k.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 SAP reference number"})]})]}),e.jsxs(Tt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(E,{variant:"outline",onClick:()=>i(!1),className:"h-11 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:"Cancel"}),e.jsxs(E,{onClick:y,disabled:!x.title.trim(),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(Re,{className:"w-4 h-4 mr-2"}),l?"Update Activity Type":"Add Activity Type"]})]})]})})]})}function bk({open:t,onClose:s,success:a,message:r}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(qs,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(Dt,{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(De,{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(wt,{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(Tt,{children:e.jsx(E,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const yk=async()=>(await je.get("/user/preferences/notifications")).data.data,vk=async t=>(await je.put("/user/preferences/notifications",t)).data.data;function jk({open:t,onClose:s}){const[a,r]=p.useState({emailNotificationsEnabled:!0,pushNotificationsEnabled:!0,inAppNotificationsEnabled:!0}),[n,i]=p.useState(!0),[l,o]=p.useState(null),[c,d]=p.useState(null),[m,h]=p.useState(null);p.useEffect(()=>{t&&x()},[t]);const x=async()=>{var g,b;try{i(!0),h(null);const f=await yk();r(f)}catch(f){console.error("[NotificationPreferences] Failed to load preferences:",f),h(((b=(g=f.response)==null?void 0:g.data)==null?void 0:b.message)||"Failed to load notification preferences")}finally{i(!1)}},u=async(g,b)=>{var f,y;try{o(g),h(null),d(null);const v={[g]:b},w=await vk(v);r(w),d(`${g==="emailNotificationsEnabled"?"Email":g==="pushNotificationsEnabled"?"Push":"In-App"} notifications ${b?"enabled":"disabled"}`),setTimeout(()=>d(null),3e3)}catch(v){console.error("[NotificationPreferences] Failed to update preference:",v),h(((y=(f=v.response)==null?void 0:f.data)==null?void 0:y.message)||"Failed to update notification preference"),x()}finally{o(null)}};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(gt,{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(Va,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(mt,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(Dt,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx(Ts,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(lt,{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(De,{className:"w-4 h-4 text-green-600 shrink-0"}),e.jsx("p",{className:"text-sm text-green-800 font-medium",children:c})]}),m&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-md animate-in fade-in slide-in-from-top-2",children:[e.jsx(ze,{className:"w-4 h-4 text-red-600 shrink-0"}),e.jsx("p",{className:"text-sm text-red-800 font-medium",children:m})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(Ra,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Email Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Receive important updates and alerts via email"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="emailNotificationsEnabled"&&e.jsx(lt,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(on,{id:"email-notifications-modal",checked:a.emailNotificationsEnabled,onCheckedChange:g=>u("emailNotificationsEnabled",g),disabled:l==="emailNotificationsEnabled"})]})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(qs,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"push-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Push Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Get instant browser notifications for real-time updates"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="pushNotificationsEnabled"&&e.jsx(lt,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(on,{id:"push-notifications-modal",checked:a.pushNotificationsEnabled,onCheckedChange:g=>u("pushNotificationsEnabled",g),disabled:l==="pushNotificationsEnabled"})]})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(As,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"inapp-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"In-App Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"View notifications in the notification center"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="inAppNotificationsEnabled"&&e.jsx(lt,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(on,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>u("inAppNotificationsEnabled",g),disabled:l==="inAppNotificationsEnabled"})]})]})}),e.jsx(Ts,{}),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 Nk(){const{user:t}=Kt(),s=lr(t),[a,r]=p.useState(!1),[n,i]=p.useState(!1),[l,o]=p.useState(),[c,d]=p.useState(!1),[m,h]=p.useState(!1),[x,u]=p.useState(!1),[g,b]=p.useState(!0),[f,y]=p.useState(!1);p.useEffect(()=>{v()},[]);const v=async()=>{try{b(!0);const C=await ry();u(C.length>0)}catch(C){console.error("Failed to check subscription status:",C),u(!1)}finally{b(!1)}},w=async()=>{d(!0),r(!1);try{if(!("Notification"in window)){i(!1),o("Notifications are not supported in this browser. Please use a modern browser like Chrome, Firefox, or Edge."),r(!0),d(!1);return}let C=Notification.permission;if(C==="denied"){i(!1),o(`Notification permission was previously denied. To enable notifications: +`),i=new Blob([n],{type:"text/csv;charset=utf-8;"}),l=document.createElement("a"),o=URL.createObjectURL(i);l.setAttribute("href",o),l.setAttribute("download",`requests-export-${new Date().toISOString().split("T")[0]}.csv`),l.style.visibility="hidden",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o)}async function B5({page:t,itemsPerPage:s,filters:a,isOrgLevel:r}){var n,i,l,o;if(r){const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(c.templateType=a.templateType),a!=null&&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 ks.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 h=m.filter(g=>(g.status||"").toString().toUpperCase()!=="DRAFT"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:h.length,totalPages:1};return{data:h,allData:[],filteredData:h,pagination:{page:x.page,limit:x.limit||s,total:x.total||h.length,totalPages:x.totalPages||1}}}else{const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(c.templateType=a.templateType),a!=null&&a.department&&a.department!=="all"&&(c.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(c.initiator=a.initiator),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(c.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(c.dateRange=a.dateRange),a!=null&&a.startDate&&(c.startDate=(l=a.startDate)==null?void 0:l.toISOString()),a!=null&&a.endDate&&(c.endDate=(o=a.endDate)==null?void 0:o.toISOString());const d=await ks.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 h=m.filter(u=>(u.status||"").toString().toUpperCase()!=="DRAFT"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:h.length,totalPages:1};return{data:h,allData:[],filteredData:h,pagination:x}}}async function V5(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const l=t?await ks.listWorkflows({page:r,limit:100}):await ks.listParticipantRequests({page:r,limit:100});let o=[];if(Array.isArray(l==null?void 0:l.data)?o=l.data:Array.isArray(l)&&(o=l),o.length>0){const c=o.filter(d=>(d.status||"").toString().toUpperCase()!=="DRAFT");a.push(...c),r++,l!=null&&l.pagination?n=r<=l.pagination.totalPages:n=o.length===100}else n=!1}return a}function z5({onViewRequest:t}){const{user:s}=Kt(),a=zr(I=>I.dashboard.viewAsUser),r=p.useMemo(()=>ki(s),[s]),n=p.useMemo(()=>r&&!a,[r,a]),i=ng(),[l,o]=p.useState([]),[c,d]=p.useState(!1),[m,h]=p.useState(!1),[x,u]=p.useState(null),[g,b]=p.useState([]),[f,y]=p.useState(!1),[v,w]=p.useState(1),[C,k]=p.useState(0),[S]=p.useState(10),_=hi({filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter,source:"local"}),D=hi({filterValue:i.approverFilter,onFilterChange:i.setApproverFilter,source:"local"}),A=p.useCallback(async(I,M,W,G)=>{try{const ce=G==null?void 0:G.slaCompliance;if(ce&&ce!=="all"&&ce!=="breached"&&ce!=="compliant"){const L={};G!=null&&G.search&&(L.search=G.search),G!=null&&G.priority&&G.priority!=="all"&&(L.priority=G.priority),G!=null&&G.department&&G.department!=="all"&&(L.department=G.department),G!=null&&G.initiator&&G.initiator!=="all"&&(L.initiator=G.initiator),G!=null&&G.approver&&G.approver!=="all"&&(L.approver=G.approver,L.approverType=G.approverType||"current"),L.slaCompliance=ce,I&&(L.dateRange=I),M&&(L.startDate=M.toISOString()),W&&(L.endDate=W.toISOString());const z=n?await ks.listWorkflows({page:1,limit:1e3,...L}):await ks.listParticipantRequests({page:1,limit:1e3,...L}),H=Array.isArray(z==null?void 0:z.data)?z.data:[],ye=H.length,ae=H.filter(Ce=>{const Ee=(Ce.status||"").toString().toUpperCase();return Ee==="PENDING"||Ee==="IN_PROGRESS"}).length,me=H.filter(Ce=>(Ce.status||"").toString().toUpperCase()==="APPROVED").length,Q=H.filter(Ce=>(Ce.status||"").toString().toUpperCase()==="REJECTED").length,oe=H.filter(Ce=>(Ce.status||"").toString().toUpperCase()==="CLOSED").length;u({total:ye,pending:ae,paused:0,approved:me,rejected:Q,draft:0,closed:oe})}else{const L=await At.getRequestStats(I,M?M.toISOString():void 0,W?W.toISOString():void 0,void 0,G==null?void 0:G.priority,G==null?void 0:G.templateType,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,!n);u({total:L.totalRequests||0,pending:L.openRequests||0,paused:L.pausedRequests||0,approved:L.approvedRequests||0,rejected:L.rejectedRequests||0,draft:L.draftRequests||0,closed:L.closedRequests||0})}}catch(ce){console.error("Failed to fetch backend stats:",ce)}finally{}},[n]),N=p.useCallback(async()=>{try{y(!0);const I=await At.getDepartments();b(I)}catch{}finally{y(!1)}},[]),P=p.useRef(i),R=p.useRef(A);p.useEffect(()=>{P.current=i,R.current=A},[i,A]),p.useEffect(()=>{const I=new URLSearchParams(window.location.search),M=I.get("approver"),W=I.get("approverType"),G=I.get("slaCompliance"),ce=I.get("dateRange"),te=I.get("startDate"),L=I.get("endDate");M&&i.setApproverFilter(M),(W==="current"||W==="any")&&i.setApproverFilterType(W),G&&i.setSlaComplianceFilter(G),ce&&i.setDateRange(ce),te&&i.setCustomStartDate(new Date(te)),L&&i.setCustomEndDate(new Date(L))},[]);const O=p.useCallback(async(I=1)=>{try{I===1&&(d(!0),o([]));const M=P.current.getFilters(),W=await B5({page:I,itemsPerPage:S,filters:M,isOrgLevel:n});o(W.data),i.setCurrentPage(W.pagination.page),w(W.pagination.totalPages),k(W.pagination.total)}catch{o([])}finally{d(!1)}},[S,n]),F=p.useCallback(async()=>{try{h(!0);const I=await V5(n);await mg(I,i.getFilters())}catch(I){console.error("Failed to export requests:",I),alert("Failed to export requests. Please try again.")}finally{h(!1)}},[n,i]);p.useEffect(()=>{N()},[N]),p.useEffect(()=>{const I=setTimeout(()=>{const M={priority:i.priorityFilter!=="all"?i.priorityFilter:void 0,templateType:i.templateTypeFilter!=="all"?i.templateTypeFilter:void 0,department:i.departmentFilter!=="all"?i.departmentFilter:void 0,initiator:i.initiatorFilter!=="all"?i.initiatorFilter:void 0,approver:i.approverFilter!=="all"?i.approverFilter:void 0,approverType:i.approverFilter!=="all"?i.approverFilterType:void 0,search:i.searchTerm||void 0,slaCompliance:i.slaComplianceFilter!=="all"?i.slaComplianceFilter:void 0},W=i.dateRange||"all";R.current(W,i.customStartDate,i.customEndDate,M)},i.searchTerm?500:0);return()=>clearTimeout(I)},[n,i.dateRange,i.customStartDate,i.customEndDate,i.priorityFilter,i.templateTypeFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.searchTerm,i.slaComplianceFilter]);const $=p.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,slaComplianceFilter:i.slaComplianceFilter,departmentFilter:i.departmentFilter,initiatorFilter:i.initiatorFilter,approverFilter:i.approverFilter,approverFilterType:i.approverFilterType,dateRange:i.dateRange,customStartDate:i.customStartDate,customEndDate:i.customEndDate,isOrgLevel:n}),V=p.useRef(!1);p.useEffect(()=>{const I=i.currentPage||1;O(I),V.current=!0},[]),p.useEffect(()=>{if(!V.current)return;const I=$.current;if(!(I.searchTerm!==i.searchTerm||I.statusFilter!==i.statusFilter||I.priorityFilter!==i.priorityFilter||I.templateTypeFilter!==i.templateTypeFilter||I.slaComplianceFilter!==i.slaComplianceFilter||I.departmentFilter!==i.departmentFilter||I.initiatorFilter!==i.initiatorFilter||I.approverFilter!==i.approverFilter||I.approverFilterType!==i.approverFilterType||I.dateRange!==i.dateRange||I.customStartDate!==i.customStartDate||I.customEndDate!==i.customEndDate||I.isOrgLevel!==n))return;const W=setTimeout(()=>{i.setCurrentPage(1),O(1),$.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,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!==I.searchTerm?500:0);return()=>clearTimeout(W)},[n,i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter,i.slaComplianceFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.dateRange,i.customStartDate,i.customEndDate]);const T=p.useCallback(I=>{I>=1&&I<=v&&(i.setCurrentPage(I),O(I))},[v,O,i]),j=p.useMemo(()=>ig(l),[l]),U=p.useMemo(()=>x?{total:x.total||0,pending:x.pending||0,paused:x.paused||0,approved:x.approved||0,rejected:x.rejected||0,draft:x.draft||0,closed:x.closed||0}:L5([],n,x,!1,C,j),[n,x,C,j]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(tg,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:F}),e.jsx(sg,{stats:U,onStatusFilter:I=>{i.setStatusFilter(I)}}),e.jsx(ee,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(se,{className:"p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ya,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(ne,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),i.hasActiveFilters&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:i.clearFilters,className:"gap-2",children:[e.jsx($t,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Ts,{}),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(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Oe,{placeholder:"Search requests...",value:i.searchTerm,onChange:I=>i.setSearchTerm(I.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(We,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"paused",children:"Paused"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]}),e.jsxs(We,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"All Priority"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Priority"}),e.jsx(Y,{value:"express",children:"Express"}),e.jsx(Y,{value:"standard",children:"Standard"})]})]}),e.jsxs(We,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"All Templates"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Templates"}),e.jsx(Y,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Y,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]}),e.jsxs(We,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:f||g.length===0,children:[e.jsx(Ye,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ge,{placeholder:f?"Loading...":"All Departments"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Departments"}),g.map(I=>e.jsx(Y,{value:I,children:I},I))]})]}),e.jsxs(We,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(Ye,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"All SLA Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All SLA Status"}),e.jsx(Y,{value:"compliant",children:"Compliant"}),e.jsx(Y,{value:"on-track",children:"On Track"}),e.jsx(Y,{value:"approaching",children:"Approaching"}),e.jsx(Y,{value:"critical",children:"Critical"}),e.jsx(Y,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:_.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:_.selectedUser.displayName||_.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:_.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Oe,{placeholder:"Search initiator...",value:_.searchQuery,onChange:I=>_.handleSearch(I.target.value),onFocus:()=>{_.searchResults.length>0&&_.setShowResults(!0)},onBlur:()=>setTimeout(()=>_.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),_.showResults&&_.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:_.searchResults.map(I=>e.jsx("button",{type:"button",onClick:()=>_.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(re,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(We,{value:i.approverFilterType,onValueChange:I=>i.setApproverFilterType(I),children:[e.jsx(Ye,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"current",children:"Current Only"}),e.jsx(Y,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:D.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:D.selectedUser.displayName||D.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:D.handleClear,children:e.jsx(ft,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Oe,{placeholder:"Search approver...",value:D.searchQuery,onChange:I=>D.handleSearch(I.target.value),onFocus:()=>{D.searchResults.length>0&&D.setShowResults(!0)},onBlur:()=>setTimeout(()=>D.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),D.showResults&&D.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:D.searchResults.map(I=>e.jsx("button",{type:"button",onClick:()=>D.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(ot,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(We,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(Ye,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs(Hs,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ot,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${He(i.customStartDate,"MMM d, yyyy")} - ${He(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(Gs,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Ms,{value:i.customStartDate||null,onChange:I=>{const M=I?new Date(I):void 0;M?(i.setCustomStartDate(M),i.customEndDate&&M>i.customEndDate&&i.setCustomEndDate(M)):i.setCustomStartDate(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",children:"End Date"}),e.jsx(Ms,{value:i.customEndDate||null,onChange:I=>{const M=I?new Date(I):void 0;M?(i.setCustomEndDate(M),i.customStartDate&&M{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})})]})})]})]})]})})}),e.jsx(ag,{requests:j,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(vr,{currentPage:i.currentPage||1,totalPages:v,totalRecords:C,itemsPerPage:S,onPageChange:T,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function H5({page:t,itemsPerPage:s,filters:a}){const r={};a!=null&&a.search&&(r.search=a.search),a!=null&&a.status&&a.status!=="all"&&(r.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(r.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(r.templateType=a.templateType),a!=null&&a.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 ks.listParticipantRequests({page:t,limit:s,...r});let i=[];Array.isArray(n==null?void 0:n.data)?i=n.data:Array.isArray(n)&&(i=n);const l=i.filter(c=>(c.status||"").toString().toUpperCase()!=="DRAFT"),o=(n==null?void 0:n.pagination)||{page:t,limit:s,total:l.length,totalPages:1};return{data:l,allData:[],filteredData:l,pagination:{page:o.page,limit:o.limit||s,total:o.total||l.length,totalPages:o.totalPages||1}}}const Su=100;async function W5(t){const s=[];let a=!0,r=1;const n=100,i={};for(t!=null&&t.search&&(i.search=t.search),t!=null&&t.status&&t.status!=="all"&&(i.status=t.status),t!=null&&t.priority&&t.priority!=="all"&&(i.priority=t.priority),t!=null&&t.templateType&&t.templateType!=="all"&&(i.templateType=t.templateType),t!=null&&t.department&&t.department!=="all"&&(i.department=t.department),t!=null&&t.initiator&&t.initiator!=="all"&&(i.initiator=t.initiator),t!=null&&t.approver&&t.approver!=="all"&&(i.approver=t.approver,i.approverType=t.approverType||"current"),t!=null&&t.slaCompliance&&t.slaCompliance!=="all"&&(i.slaCompliance=t.slaCompliance),t!=null&&t.dateRange&&(i.dateRange=t.dateRange),t!=null&&t.startDate&&(i.startDate=t.startDate instanceof Date?t.startDate.toISOString():t.startDate),t!=null&&t.endDate&&(i.endDate=t.endDate instanceof Date?t.endDate.toISOString():t.endDate);a&&r<=n;){const l=await ks.listParticipantRequests({page:r,limit:Su,...i});let o=[];if(Array.isArray(l==null?void 0:l.data)?o=l.data:Array.isArray(l)&&(o=l),o.length===0)a=!1;else{const c=o.filter(d=>(d.status||"").toString().toUpperCase()!=="DRAFT");s.push(...c),r++,l!=null&&l.pagination?a=r<=l.pagination.totalPages:a=o.length===Su}}return s}function G5({onViewRequest:t}){const s=ng(),a=p.useMemo(()=>{try{const W=tt.getUserData();return Eo(W)}catch(W){return console.error("[UserAllRequests] Error getting user filter type:",W),"STANDARD"}},[]),r=p.useMemo(()=>vT(a),[a]),n=a==="DEALER",i=p.useCallback(()=>{const W=s.getFilters();if(n){const{priority:G,templateType:ce,department:te,slaCompliance:L,...z}=W;return z}return W},[s,n]),l=p.useCallback(()=>n?!!(s.searchTerm||s.statusFilter!=="all"||s.initiatorFilter!=="all"||s.approverFilter!=="all"||s.dateRange!=="all"||s.customStartDate||s.customEndDate):s.hasActiveFilters,[n,s]),[o,c]=p.useState([]),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(null),[b,f]=p.useState([]),[y,v]=p.useState(!1),[w,C]=p.useState(1),[k,S]=p.useState(0),[_]=p.useState(10),D=hi({filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter,source:"local"}),A=hi({filterValue:s.approverFilter,onFilterChange:s.setApproverFilter,source:"local"}),N=p.useCallback(async(W,G,ce,te)=>{try{const L=await At.getRequestStats(W,G?G.toISOString():void 0,ce?ce.toISOString():void 0,void 0,te==null?void 0:te.priority,te==null?void 0:te.templateType,te==null?void 0:te.department,te==null?void 0:te.initiator,te==null?void 0:te.approver,te==null?void 0:te.approverType,te==null?void 0:te.search,te==null?void 0:te.slaCompliance,!0);g({total:L.totalRequests||0,pending:L.openRequests||0,paused:L.pausedRequests||0,approved:L.approvedRequests||0,rejected:L.rejectedRequests||0,draft:L.draftRequests||0,closed:L.closedRequests||0})}catch(L){console.error("Failed to fetch backend stats:",L)}},[]),P=p.useCallback(async()=>{try{v(!0);const W=await At.getDepartments();f(W)}catch{}finally{v(!1)}},[]),R=p.useRef(s),O=p.useRef(N),F=p.useRef(i);p.useEffect(()=>{R.current=s,O.current=N,F.current=i},[s,N,i]);const $=p.useCallback(async(W=1)=>{try{W===1&&(m(!0),c([]));const G=F.current(),ce=await H5({page:W,itemsPerPage:_,filters:G});c(ce.data),s.setCurrentPage(ce.pagination.page),C(ce.pagination.totalPages),S(ce.pagination.total)}catch{c([])}finally{m(!1)}},[_,s]),V=p.useCallback(async()=>{try{x(!0);const W=i(),G=await W5(W);await mg(G,W)}catch(W){console.error("Failed to export requests:",W),alert("Failed to export requests. Please try again.")}finally{x(!1)}},[i]);p.useEffect(()=>{P()},[P]),p.useEffect(()=>{const W=setTimeout(()=>{const G={initiator:s.initiatorFilter!=="all"?s.initiatorFilter:void 0,approver:s.approverFilter!=="all"?s.approverFilter:void 0,approverType:s.approverFilter!=="all"?s.approverFilterType:void 0,search:s.searchTerm||void 0};n||(s.priorityFilter!=="all"&&(G.priority=s.priorityFilter),s.templateTypeFilter!=="all"&&(G.templateType=s.templateTypeFilter),s.departmentFilter!=="all"&&(G.department=s.departmentFilter),s.slaComplianceFilter!=="all"&&(G.slaCompliance=s.slaComplianceFilter));const ce=s.dateRange==="all"?"all":s.dateRange||"month";O.current(ce,s.customStartDate,s.customEndDate,G)},s.searchTerm?500:0);return()=>clearTimeout(W)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate,s.templateTypeFilter,n]);const T=p.useRef({searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}),j=p.useRef(!1);p.useEffect(()=>{const W=s.currentPage||1;$(W),j.current=!0},[]),p.useEffect(()=>{if(!j.current)return;const W=T.current;if(!(W.searchTerm!==s.searchTerm||W.statusFilter!==s.statusFilter||W.priorityFilter!==s.priorityFilter||W.templateTypeFilter!==s.templateTypeFilter||W.slaComplianceFilter!==s.slaComplianceFilter||W.departmentFilter!==s.departmentFilter||W.initiatorFilter!==s.initiatorFilter||W.approverFilter!==s.approverFilter||W.approverFilterType!==s.approverFilterType||W.dateRange!==s.dateRange||W.customStartDate!==s.customStartDate||W.customEndDate!==s.customEndDate))return;const ce=setTimeout(()=>{s.setCurrentPage(1),$(1),T.current={searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,slaComplianceFilter:s.slaComplianceFilter,departmentFilter:s.departmentFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate}},s.searchTerm!==W.searchTerm?500:0);return()=>clearTimeout(ce)},[s.searchTerm,s.statusFilter,s.priorityFilter,s.templateTypeFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate]);const U=p.useCallback(W=>{W>=1&&W<=w&&(s.setCurrentPage(W),$(W))},[w,$,s]),I=p.useMemo(()=>ig(o),[o]),M=p.useMemo(()=>{if(u)return{total:u.total||0,pending:u.pending||0,paused:u.paused||0,approved:u.approved||0,rejected:u.rejected||0,draft:u.draft||0,closed:u.closed||0};const W=I.filter(z=>{const H=(z.status||"").toString().toLowerCase();return H==="pending"||H==="in-progress"}).length,G=I.filter(z=>(z.status||"").toString().toLowerCase()==="paused").length,ce=I.filter(z=>(z.status||"").toString().toLowerCase()==="approved").length,te=I.filter(z=>(z.status||"").toString().toLowerCase()==="rejected").length,L=I.filter(z=>(z.status||"").toString().toLowerCase()==="closed").length;return{total:k>0?k:I.length,pending:W,paused:G,approved:ce,rejected:te,draft:0,closed:L}},[u,k,I]);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(tg,{isOrgLevel:!1,isAdmin:!1,loading:d,exporting:h,onExport:V}),e.jsx(sg,{stats:M,onStatusFilter:W=>{s.setStatusFilter(W)}}),e.jsx(r,{searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,departmentFilter:s.departmentFilter,slaComplianceFilter:s.slaComplianceFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate,showCustomDatePicker:s.showCustomDatePicker,departments:b,loadingDepartments:y,initiatorSearch:D,approverSearch:A,onSearchChange:s.setSearchTerm,onStatusChange:s.setStatusFilter,onPriorityChange:s.setPriorityFilter,onTemplateTypeChange:s.setTemplateTypeFilter,onDepartmentChange:s.setDepartmentFilter,onSlaComplianceChange:s.setSlaComplianceFilter,onInitiatorChange:s.setInitiatorFilter,onApproverChange:s.setApproverFilter,onApproverTypeChange:s.setApproverFilterType,onDateRangeChange:s.handleDateRangeChange,onCustomStartDateChange:s.setCustomStartDate,onCustomEndDateChange:s.setCustomEndDate,onShowCustomDatePickerChange:s.setShowCustomDatePicker,onApplyCustomDate:s.handleApplyCustomDate,onClearFilters:s.clearFilters,hasActiveFilters:l()}),e.jsx(ag,{requests:I,loading:d,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(vr,{currentPage:s.currentPage||1,totalPages:w,totalRecords:k,itemsPerPage:_,onPageChange:U,loading:d,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function Y5(){const t=Ks();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(ee,{children:e.jsxs(se,{className:"p-8 text-center",children:[e.jsx(ze,{className:"w-12 h-12 text-yellow-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Approver ID Required"}),e.jsx("p",{className:"text-gray-600",children:"Please select an approver to view their performance details."}),e.jsxs(E,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(Ns,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function K5({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(cs,{className:"h-6 w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Approver Performance Report"}),e.jsx("p",{className:"text-sm text-gray-600",children:t})]})]}),e.jsxs(E,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx($t,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function X5({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(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[s,"%"]}),e.jsx("div",{className:`p-2 rounded-lg ${s>=95?"bg-green-100":s>=90?"bg-blue-100":s>=85?"bg-orange-100":"bg-red-100"}`,children:e.jsx(Ot,{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(na,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.totalApproved}),e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(De,{className:"w-5 h-5 text-blue-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Requests handled"})]})]}),e.jsxs(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-3xl font-bold text-gray-900",children:[t.avgResponseHours.toFixed(1),"h"]}),e.jsx("div",{className:"p-2 bg-purple-100 rounded-lg",children:e.jsx(bo,{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(ee,{children:[e.jsx(ge,{className:"pb-3",children:e.jsx(fe,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(se,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-3xl font-bold text-gray-900",children:t.pendingCount}),e.jsx("div",{className:"p-2 bg-orange-100 rounded-lg",children:e.jsx(st,{className:"w-5 h-5 text-orange-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Awaiting approval"})]})]})]})}function Z5({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(ee,{"data-testid":"approver-actions-stats",children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Approver's Actions"}),e.jsxs($e,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?Cj(a,r,n,""):"(all time)"]})]}),e.jsxs(se,{children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("h4",{className:"text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2",children:[e.jsx(cs,{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(De,{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(wt,{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(st,{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(fo,{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(Re,{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(Ot,{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(p0,{className:"w-5 h-5 text-green-600"}),e.jsx("span",{className:"text-xs text-green-600 font-medium",children:(s==null?void 0:s.tatCompliancePercent)!==void 0?`${s.tatCompliancePercent}%`:"N/A"})]}),e.jsx("div",{className:"text-2xl font-bold text-green-700",children:(s==null?void 0:s.withinTatCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"TAT Compliant"})]}),e.jsxs("div",{className:"p-4 bg-red-50 rounded-lg border border-red-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(ze,{className:"w-5 h-5 text-red-600"})}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:(s==null?void 0:s.breachedCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"TAT Breached"})]}),e.jsxs("div",{className:"p-4 bg-purple-50 rounded-lg border border-purple-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(Il,{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 J5({searchTerm:t,statusFilter:s,priorityFilter:a,slaComplianceFilter:r,dateRange:n,customStartDate:i,customEndDate:l,showCustomDatePicker:o,tempCustomStartDate:c,tempCustomEndDate:d,onSearchChange:m,onStatusChange:h,onPriorityChange:x,onSlaComplianceChange:u,onDateRangeChange:g,onShowCustomDatePickerChange:b,onTempStartDateChange:f,onTempEndDateChange:y,onApplyCustomDate:v,onClearFilters:w}){return e.jsxs(ee,{"data-testid":"approver-performance-filters",children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{children:"Filters"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:w,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(se,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Oe,{placeholder:"Search requests...",value:t,onChange:C=>m(C.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(We,{value:s,onValueChange:h,children:[e.jsx(Ye,{"data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"Status"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Status"}),e.jsx(Y,{value:"pending",children:"Pending"}),e.jsx(Y,{value:"approved",children:"Approved"}),e.jsx(Y,{value:"rejected",children:"Rejected"}),e.jsx(Y,{value:"closed",children:"Closed"})]})]}),e.jsxs(We,{value:a,onValueChange:x,children:[e.jsx(Ye,{"data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"Priority"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Priority"}),e.jsx(Y,{value:"express",children:"Express"}),e.jsx(Y,{value:"standard",children:"Standard"})]})]}),e.jsxs(We,{value:r,onValueChange:u,children:[e.jsx(Ye,{"data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"SLA Compliance"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All SLA"}),e.jsx(Y,{value:"compliant",children:"Compliant"}),e.jsx(Y,{value:"on-track",children:"On Track"}),e.jsx(Y,{value:"approaching",children:"Approaching"}),e.jsx(Y,{value:"critical",children:"Critical"}),e.jsx(Y,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(We,{value:n,onValueChange:g,children:[e.jsx(Ye,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"all",children:"All Time"}),e.jsx(Y,{value:"today",children:"Today"}),e.jsx(Y,{value:"week",children:"This Week"}),e.jsx(Y,{value:"month",children:"This Month"}),e.jsx(Y,{value:"last7days",children:"Last 7 Days"}),e.jsx(Y,{value:"last30days",children:"Last 30 Days"}),e.jsx(Y,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(Hs,{open:o,onOpenChange:b,children:[e.jsx(Ws,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(ot,{className:"w-4 h-4"}),c&&d?`${He(c,"MMM d")} - ${He(d,"MMM d")}`:"Select dates"]})}),e.jsx(Gs,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Oe,{id:"start-date",type:"date",value:c?He(c,"yyyy-MM-dd"):"",onChange:C=>{const k=C.target.value?new Date(C.target.value):void 0;k?(f(k),d&&k>d&&y(k)):f(void 0)},max:He(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Oe,{id:"end-date",type:"date",value:d?He(d,"yyyy-MM-dd"):"",onChange:C=>{const k=C.target.value?new Date(C.target.value):void 0;k?(y(k),c&&k{b(!1),f(i),y(l),(!i||!l)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const Q5=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:ta,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:Ot,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ot,iconColor:"text-gray-600"}}},q5=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:De,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:wt,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,iconColor:"text-yellow-600"};case"in-progress":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:st,iconColor:"text-blue-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:De,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Re,iconColor:"text-gray-600"}}},ek=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 tk(t){if(!t)return"N/A";try{return He(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function sk(t){if(!t)return"N/A";try{return He(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function pi(t){const{requestId:s,status:a,request:r,navigate:n}=t;if((a==null?void 0:a.toLowerCase())==="draft"||a==="DRAFT"){n(`/edit-request/${s}`);return}const l=KT(s);n(l)}function ak({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o}){const c=Ks();return e.jsxs(ee,{"data-testid":"approver-performance-request-list",children:[e.jsxs(ge,{children:[e.jsx(fe,{children:"Request Details"}),e.jsxs($e,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(se,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx($t,{className:"w-6 h-6 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading requests..."})]}):t.length===0?e.jsxs("div",{className:"text-center py-12 text-gray-500","data-testid":"empty-state",children:[e.jsx(Re,{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=Q5(d.priority),h=q5(d.status),x=ek(d.slaStatus||""),u=m.icon,g=h.icon;return e.jsx(ee,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{pi({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":`request-card-${d.requestId}`,children:e.jsx(se,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm text-blue-600 hover:underline","data-testid":"request-number",children:d.requestNumber}),e.jsxs(ne,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(u,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(ne,{className:h.color,"data-testid":"status-badge",children:[e.jsx(g,{className:`w-3 h-3 mr-1 ${h.iconColor}`}),d.status]}),d.approvalStatus&&e.jsx(ne,{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(De,{className:"w-3 h-3 mr-1"}),"Approved"]}):d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(wt,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(st,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(ne,{className:x.color,"data-testid":"sla-status-badge",children:x.label})]}),e.jsx("h3",{className:"font-medium text-gray-900 mb-1 truncate","data-testid":"request-title",children:d.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-500 mt-2",children:[e.jsxs("span",{className:"flex items-center gap-1","data-testid":"initiator-info",children:[e.jsx(Vt,{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(st,{className:"w-3 h-3"}),"Submitted: ",tk(d.submissionDate)]}),d.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(De,{className:"w-3 h-3"}),"Action: ",sk(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(Ot,{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(bo,{className:"w-3 h-3"}),Ft(d.levelElapsedHours)," / ",Ft(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:b=>{b.stopPropagation(),pi({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":"view-request-button",children:e.jsx(ss,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(vr,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function rk(){const[t]=cx(),[s,a]=p.useState(""),[r,n]=p.useState(t.get("status")||"all"),[i,l]=p.useState(t.get("priority")||"all"),[o,c]=p.useState(t.get("slaCompliance")||"all"),[d,m]=p.useState(t.get("dateRange")||"all"),[h,x]=p.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[u,g]=p.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[b,f]=p.useState(!1),[y,v]=p.useState(void 0),[w,C]=p.useState(void 0),k=p.useCallback(()=>{a(""),n("all"),l("all"),c("all"),m("all"),x(void 0),g(void 0),v(void 0),C(void 0),f(!1)},[]),S=p.useCallback(D=>{const A=D;m(A),A!=="custom"?(x(void 0),g(void 0),v(void 0),C(void 0),f(!1)):(v(h),C(u),f(!0))},[h,u]),_=p.useCallback(()=>{if(y&&w){if(y>w){const D=y;x(w),g(D),v(w),C(D)}else x(y),g(w);f(!1)}},[y,w]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:o,dateRange:d,customStartDate:h,customEndDate:u,showCustomDatePicker:b,tempCustomStartDate:y,tempCustomEndDate:w,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:l,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:x,setCustomEndDate:g,setShowCustomDatePicker:f,setTempCustomStartDate:v,setTempCustomEndDate:C,clearFilters:k,handleDateRangeChange:S,handleApplyCustomDate:_}}function nk({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:l,searchTerm:o,itemsPerPage:c}){const[d,m]=p.useState([]),[h,x]=p.useState(null),[u,g]=p.useState([]),[b,f]=p.useState(!0),[y,v]=p.useState(!1),[w,C]=p.useState(1),[k,S]=p.useState(1),[_,D]=p.useState(0),A=p.useRef(!0),N=p.useCallback(async()=>{if(t)try{const F=s==="all"?void 0:s,$=await At.getSingleApproverStats(t,F,a,r,i!=="all"?i:void 0,l!=="all"?l:void 0);x($)}catch(F){console.error("[ApproverPerformance] Failed to fetch approver stats:",F),x(null)}},[t,s,a,r,i,l]),P=p.useCallback(async(F=1)=>{if(!t){f(!1);return}try{f(!0);const $=await At.getRequestsByApprover(t,F,c,s==="all"?void 0:s,a,r,n!=="all"?n:void 0,i!=="all"?i:void 0,l!=="all"?l:void 0,o||void 0);m($.requests),D($.pagination.totalRecords),S($.pagination.totalPages),C($.pagination.currentPage),g($.requests)}catch($){console.error("Failed to fetch requests:",$)}finally{f(!1),v(!1)}},[t,s,a,r,n,i,l,o,c]);p.useEffect(()=>{A.current&&(A.current=!1,N(),P(1))},[]),p.useEffect(()=>{A.current||N()},[s,a,r,i,l]),p.useEffect(()=>{A.current||P(1)},[s,a,r,n,i,l,o]);const R=p.useCallback(()=>{v(!0),N(),P(1)},[N,P]),O=p.useCallback(F=>{P(F)},[P]);return{requests:d,approverStats:h,allFilteredRequests:u,loading:b,refreshing:y,currentPage:w,totalPages:k,totalRecords:_,handleRefresh:R,handlePageChange:O}}const Au=10;function ik(){const[t]=cx(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=rk(),n=nk({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:Au});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(K5,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(X5,{approverStats:n.approverStats}),n.approverStats&&e.jsx(Z5,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(J5,{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(ak,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:Au,onPageChange:n.handlePageChange})]}):e.jsx(Y5,{})}function lk(){const{user:t}=Kt(),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(ee,{className:"relative overflow-hidden shadow-xl border-0",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(se,{className:"relative z-10 p-8 lg:p-12",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-start md:items-center gap-6",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Zt,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(Di,{src:(t==null?void 0:t.picture)||""}),e.jsx(Jt,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),lr(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(hs,{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:[lr(t)&&e.jsxs(ne,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(hs,{className:"w-3 h-3 mr-1"}),"Administrator"]}),Jr(t)&&e.jsxs(ne,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(cs,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(ne,{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(ee,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ge,{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(Vt,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx($e,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(se,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Ra,{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(Vt,{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(Vt,{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(Vt,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Display Name"}),e.jsx("p",{className:"text-base text-gray-900",children:t.displayName})]})]}),(t==null?void 0:t.phone)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(ji,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Phone"}),e.jsx("p",{className:"text-base text-gray-900",children:t.phone})]})]})]})})]}),e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ge,{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(Pd,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx($e,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(se,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[(t==null?void 0:t.employeeId)&&e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors",children:[e.jsx(Vt,{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(mo,{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(Pd,{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(hs,{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(ne,{variant:lr(t)||Jr(t)?"default":"secondary",className:lr(t)?"bg-yellow-400 text-slate-900":Jr(t)?"bg-blue-400 text-slate-900":"",children:lr(t)?"Administrator":Jr(t)?"Management":"User"}),(lr(t)||Jr(t))&&e.jsx(De,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(ee,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(ge,{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(ot,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx($e,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(se,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-green-50 rounded-lg border border-green-200",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-green-500 rounded-full",children:e.jsx(De,{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(ne,{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 zn="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",ok="https://reflow-uat.royalenfield.com";function Al(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:Al(zn)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Al(zn)})}catch(l){console.warn("[Push] Initial subscription failed, attempting to clear and retry...");try{const o=await t.pushManager.getSubscription();o&&await o.unsubscribe().catch(()=>{}),s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Al(zn)})}catch(o){const c=(l==null?void 0:l.message)||(o==null?void 0:o.message)||"Unknown error";throw c.includes("push service error")||c.includes("Registration failed")?new Error("Push service error: The browser's push service rejected the subscription. This may be due to an invalid VAPID key, network issues, or browser push service problems. Please verify your VAPID key configuration and try again."):new Error(`Failed to subscribe to push notifications: ${c}`)}}}catch(i){const l=(i==null?void 0:i.message)||"Unknown error";throw l.includes("push service error")||l.includes("Registration failed")?new Error("Push service error: The browser's push service rejected the subscription. Please verify your VAPID key is correct and matches the backend configuration. If the problem persists, try clearing your browser cache and service workers."):l.includes("Invalid key")?new Error("Invalid VAPID key format. Please verify that VITE_PUBLIC_VAPID_KEY is correctly set and matches the backend VAPID_PUBLIC_KEY."):new Error(`Failed to subscribe to push notifications: ${l}`)}const a=s.toJSON(),r=!0,n=null;try{const i={"Content-Type":"application/json"},l=await fetch(`${ok}/api/v1/workflows/notifications/subscribe`,{method:"POST",headers:i,credentials:"include",body:JSON.stringify(a)});if(!l.ok){const c=await l.json().catch(()=>({error:"Unknown error"}));throw new Error((c==null?void 0:c.error)||(c==null?void 0:c.message)||`Server error: ${l.status}`)}const o=await l.json();if(!o.success)throw new Error(o.error||"Failed to save subscription")}catch(i){throw i instanceof Error&&i.message.includes("Failed")?i:new Error(`Failed to save subscription to server: ${(i==null?void 0:i.message)||"Network error"}`)}return s}async function mk(){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 ck()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await dk(s)}catch(a){throw a}}function uk({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const l=p.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs(jf,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:ke("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(Nf,{"data-slot":"slider-track",className:ke("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(wf,{"data-slot":"slider-range",className:ke("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:l.length},(o,c)=>e.jsx(Cf,{"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 xk({onConfigUpdate:t}){const[s,a]=p.useState([]),[r,n]=p.useState(!0),[i,l]=p.useState(null),[o,c]=p.useState(null),[d,m]=p.useState({}),[h,x]=p.useState(null);p.useEffect(()=>{u()},[]);const u=async()=>{var N,P;try{n(!0),c(null);const R=await X2();a(R)}catch(R){c(((P=(N=R.response)==null?void 0:N.data)==null?void 0:P.error)||"Failed to load configurations")}finally{n(!1)}},g=async N=>{var P,R;try{l(N.configKey),c(null);const O=d[N.configKey]??N.configValue;if(N.validationRules){const F=parseFloat(O);if(N.valueType==="NUMBER"){if(N.validationRules.min!==void 0&&FN.validationRules.max)throw new Error(`Value must be at most ${N.validationRules.max}`)}}await Z2(N.configKey,O),a(F=>F.map($=>$.configKey===N.configKey?{...$,configValue:O}:$)),m(F=>{const $={...F};return delete $[N.configKey],$}),x(`${N.displayName} updated successfully`),setTimeout(()=>x(null),3e3),t&&t()}catch(O){c(O.message||((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to save configuration")}finally{l(null)}},b=async N=>{var P,R;if(confirm(`Reset "${N.displayName}" to default value?`))try{l(N.configKey),c(null),await J2(N.configKey),a(O=>O.map(F=>F.configKey===N.configKey?{...F,configValue:F.defaultValue||""}:F)),m(O=>{const F={...O};return delete F[N.configKey],F}),x(`${N.displayName} reset to default`),setTimeout(()=>x(null),3e3)}catch(O){c(((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to reset configuration")}finally{l(null)}},f=(N,P)=>{m(R=>({...R,[N]:P}))},y=N=>d[N.configKey]??N.configValue,v=N=>d[N.configKey]!==void 0&&d[N.configKey]!==N.configValue,w=N=>{var O,F,$,V;const P=y(N),R=i===N.configKey;if(!N.isEditable)return e.jsxs("div",{className:"p-3 bg-slate-100 border border-slate-200 rounded-md",children:[e.jsx("p",{className:"text-sm text-slate-700 font-mono",children:N.configValue}),e.jsxs("p",{className:"text-xs text-slate-500 mt-1.5 flex items-center gap-1",children:[e.jsx(ze,{className:"w-3 h-3"}),"This setting cannot be modified"]})]});switch(N.uiComponent||N.valueType.toLowerCase()){case"toggle":return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${P==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${P==="true"?"text-green-700":"text-slate-600"}`,children:P==="true"?"Enabled":"Disabled"})]}),e.jsx(on,{checked:P==="true",onCheckedChange:I=>f(N.configKey,I?"true":"false"),disabled:R})]});case"slider":const T=parseInt(P)||0,j=((O=N.validationRules)==null?void 0:O.min)||0,U=((F=N.validationRules)==null?void 0:F.max)||100;return e.jsxs("div",{className:"space-y-3 p-3 bg-slate-50 border border-slate-200 rounded-md",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-lg font-semibold text-slate-900",children:[T,"%"]}),e.jsxs("span",{className:"text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200",children:["Range: ",j,"-",U]})]}),e.jsx(uk,{value:[T],min:j,max:U,step:1,onValueChange:([I])=>{I!==void 0&&f(N.configKey,I.toString())},disabled:R,className:"w-full"})]});case"number":return e.jsx(Oe,{type:"number",value:P,onChange:I=>f(N.configKey,I.target.value),disabled:R,min:($=N.validationRules)==null?void 0:$.min,max:(V=N.validationRules)==null?void 0:V.max,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"});case"text":case"input":default:return e.jsx(Oe,{type:"text",value:P,onChange:I=>f(N.configKey,I.target.value),disabled:R,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},C=N=>{switch(N){case"TAT_SETTINGS":return e.jsx(st,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Re,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(qs,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(qu,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(wn,{className:"w-5 h-5"});default:return e.jsx(Va,{className:"w-5 h-5"})}},k=["DASHBOARD_LAYOUT"],S=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],_=s.filter(N=>!k.includes(N.configCategory)&&!S.includes(N.configKey)),D=_.reduce((N,P)=>(N[P.configCategory]||(N[P.configCategory]=[]),N[P.configCategory].push(P),N),{});if(Object.keys(D).forEach(N=>{const P=D[N];P&&P.sort((R,O)=>R.sortOrder-O.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(lt,{className:"w-8 h-8 animate-spin text-gray-400"})});if(_.length===0)return e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(Va,{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 A=Object.keys(D);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(De,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:h})]}),o&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:o}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs($i,{defaultValue:A[0],className:"w-full",children:[e.jsx(Oi,{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:A.map(N=>e.jsx(qt,{value:N,className:"flex-1 min-w-[120px] text-[10px] xs:text-xs sm:text-sm font-medium py-2 sm:py-2.5 px-2 sm:px-3 rounded-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-slate-900 transition-all",children:e.jsx("span",{className:"truncate block",children:N.replace(/_/g," ")})},N))}),A.map(N=>{var P,R,O;return e.jsx(es,{value:N,className:"space-y-4 mt-6",children:e.jsxs(ee,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{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:C(N)})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-slate-900",children:N.replace(/_/g," ")}),e.jsxs($e,{className:"text-sm",children:[((P=D[N])==null?void 0:P.length)||0," setting",(((R=D[N])==null?void 0:R.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(se,{className:"space-y-6",children:(O=D[N])==null?void 0:O.map(F=>e.jsxs("div",{className:"space-y-3 pb-6 border-b border-slate-100 last:border-b-0 last:pb-0 hover:bg-slate-50/50 -mx-6 px-6 py-4 rounded-md transition-colors",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[e.jsx(re,{className:"text-sm font-semibold text-slate-900",children:F.displayName}),v(F)&&e.jsx(ne,{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"}),F.requiresRestart&&e.jsx(ne,{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"})]}),F.description&&e.jsx("p",{className:"text-xs text-slate-600 mt-1 leading-relaxed",children:F.description}),F.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:F.defaultValue})]})]})}),w(F),F.isEditable&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(E,{size:"sm",onClick:()=>g(F),disabled:!v(F)||i===F.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===F.configKey?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ox,{className:"w-4 h-4"}),"Save Changes"]})}),F.defaultValue&&e.jsxs(E,{size:"sm",variant:"outline",onClick:()=>b(F),disabled:i===F.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(g0,{className:"w-4 h-4"}),"Reset to Default"]})]})]},F.configKey))})]})},N)})]})]})}function hk(){const[t,s]=p.useState([]),[a,r]=p.useState(!0),[n,i]=p.useState(new Date().getFullYear()),[l,o]=p.useState(!1),[c,d]=p.useState(null),[m,h]=p.useState(null),[x,u]=p.useState(null),[g,b]=p.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});p.useEffect(()=>{f()},[n]);const f=async()=>{var N,P;try{r(!0),h(null);const R=await Q2(n);s(R)}catch(R){h(((P=(N=R.response)==null?void 0:N.data)==null?void 0:P.error)||"Failed to load holidays")}finally{r(!1)}},y=()=>{b({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),o(!0)},v=N=>{b({holidayDate:N.holidayDate,holidayName:N.holidayName,description:N.description||"",holidayType:N.holidayType,isRecurring:N.isRecurring}),d(N),o(!0)},w=()=>{if(c)return;const N=new Date;return N.setDate(N.getDate()+1),N.toISOString().split("T")[0]},C=async()=>{var N,P;try{if(h(null),!g.holidayDate||!g.holidayName){h("Holiday date and name are required");return}c?(await eS(c.holidayId,g),u("Holiday updated successfully")):(await q2(g),u("Holiday created successfully")),await f(),o(!1),setTimeout(()=>u(null),3e3)}catch(R){h(((P=(N=R.response)==null?void 0:N.data)==null?void 0:P.error)||"Failed to save holiday")}},k=async N=>{var P,R;if(confirm(`Delete "${N.holidayName}"?`))try{h(null),await tS(N.holidayId),u("Holiday deleted successfully"),await f(),setTimeout(()=>u(null),3e3)}catch(O){h(((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to delete holiday")}},S=N=>{switch(N){case"NATIONAL":return"bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-300";case"REGIONAL":return"bg-gradient-to-r from-blue-50 to-cyan-50 text-blue-800 border-blue-300";case"ORGANIZATIONAL":return"bg-gradient-to-r from-purple-50 to-violet-50 text-purple-800 border-purple-300";case"OPTIONAL":return"bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-300"}},_=Array.from({length:5},(N,P)=>new Date().getFullYear()-1+P),D=t.reduce((N,P)=>{const R=new Date(P.holidayDate).toLocaleString("default",{month:"long"});return N[R]||(N[R]=[]),N[R].push(P),N},{}),A=Object.keys(D).sort((N,P)=>{const R=new Date(Date.parse(N+" 1, 2000")).getMonth(),O=new Date(Date.parse(P+" 1, 2000")).getMonth();return R-O});return e.jsxs("div",{className:"space-y-6",children:[x&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(De,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:x})]}),m&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:m}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>h(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ge,{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(ot,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx($e,{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(We,{value:n.toString(),onValueChange:N=>i(parseInt(N)),children:[e.jsx(Ye,{className:"w-24 sm:w-32 border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm",children:e.jsx(Ge,{})}),e.jsx(Ke,{className:"rounded-md",children:_.map(N=>e.jsx(Y,{value:N.toString(),children:N},N))})]}),e.jsxs(E,{onClick:y,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(gs,{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(lt,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(ot,{className:"w-10 h-10 text-slate-400"})}),e.jsxs("p",{className:"text-slate-700 font-medium text-lg",children:["No holidays found for ",n]}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 mb-6",children:"Add holidays to exclude them from TAT calculations"}),e.jsxs(E,{onClick:y,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(gs,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:A.map(N=>{var P,R,O;return e.jsxs(ee,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{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(fe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[N," ",n]}),e.jsxs($e,{className:"text-xs sm:text-sm",children:[((P=D[N])==null?void 0:P.length)||0," holiday",(((R=D[N])==null?void 0:R.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(ot,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(se,{className:"space-y-3 pt-4",children:(O=D[N])==null?void 0:O.map(F=>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:F.holidayName}),e.jsx(ne,{variant:"outline",className:`${S(F.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:F.holidayType}),F.isRecurring&&e.jsx(ne,{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:Yx(F.holidayDate)}),F.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-1.5 line-clamp-2",children:F.description})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>v(F),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>k(F),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(yo,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},F.holidayId))})]},N)})}),e.jsx(pt,{open:l,onOpenChange:o,children:e.jsxs(dt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(gt,{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(ot,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(mt,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(Dt,{className:"text-sm text-slate-600 mt-1",children:c?"Update holiday information":"Add a new holiday to the calendar for TAT calculations"})]})]})}),e.jsxs("div",{className:"space-y-5 py-6 px-6 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"date",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Oe,{id:"date",type:"date",value:g.holidayDate,onChange:N=>b({...g,holidayDate:N.target.value}),min:w(),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:c?"Select the holiday date":"Select the holiday date (minimum: tomorrow)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"name",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Holiday Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Oe,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:N=>b({...g,holidayName:N.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the official name of the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"description",className:"text-sm font-semibold text-slate-900",children:["Description ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Oe,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:N=>b({...g,description:N.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional description or notes about the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(We,{value:g.holidayType,onValueChange:N=>b({...g,holidayType:N}),children:[e.jsx(Ye,{id:"type",className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm",children:e.jsx(Ge,{})}),e.jsxs(Ke,{className:"rounded-lg",children:[e.jsx(Y,{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(Y,{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(Y,{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(Y,{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:()=>b({...g,isRecurring:!g.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:g.isRecurring,onChange:N=>b({...g,isRecurring:N.target.checked}),className:"mt-0.5 rounded border-slate-300 text-re-green focus:ring-2 focus:ring-re-green/20 focus:ring-offset-0 w-4 h-4 cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(re,{htmlFor:"recurring",className:"font-semibold cursor-pointer text-sm text-slate-900 block mb-1",children:"Recurring Holiday"}),e.jsx("p",{className:"text-xs text-slate-600",children:"This holiday will automatically repeat every year on the same date"})]})]})]}),e.jsxs(Tt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(E,{variant:"outline",onClick:()=>o(!1),className:"h-11 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:"Cancel"}),e.jsxs(E,{onClick:C,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(ot,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function pk(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function gk(){const[t,s]=p.useState(""),[a,r]=p.useState([]),[n,i]=p.useState(!1),[l,o]=p.useState(null),[c,d]=p.useState("USER"),[m,h]=p.useState(!1),[x,u]=p.useState(null),[g,b]=p.useState([]),[f,y]=p.useState(!1),[v,w]=p.useState({admins:0,management:0,users:0}),[C,k]=p.useState("ELEVATED"),[S,_]=p.useState(1),[D,A]=p.useState(1),[N,P]=p.useState(0),R=10,O=p.useRef(null),F=p.useRef(null),$=p.useCallback(pk(async L=>{var z,H,ye;if(!L||!L.startsWith("@")||L.length<2){r([]),i(!1);return}i(!0);try{const ae=L.slice(1),Q=((z=(await dr.searchUsers(ae,20)).data)==null?void 0:z.data)||[];r(Q)}catch(ae){console.error("Search failed:",ae),u({type:"error",text:((ye=(H=ae.response)==null?void 0:H.data)==null?void 0:ye.message)||"Failed to search users"})}finally{i(!1)}},300),[]),V=L=>{const z=L.target.value;s(z),$(z)},T=async L=>{o(L),s(L.email),r([]);const z=g.find(H=>H.email.toLowerCase()===L.email.toLowerCase()||H.userId===L.userId);if(z&&z.role)d(z.role);else try{const ye=(await dr.getAllUsers()).find(ae=>ae.email&&ae.email.toLowerCase()===L.email.toLowerCase()||ae.userId&&ae.userId===L.userId);ye&&ye.role?d(ye.role):d("USER")}catch(H){console.error("Failed to check user role:",H),d("USER")}},j=async()=>{var L,z;if(!l||!c){u({type:"error",text:"Please select a user and role"});return}h(!0),u(null);try{await dr.assignRole(l.email,c),u({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await U(),await I()}catch(H){console.error("Role assignment failed:",H),u({type:"error",text:((z=(L=H.response)==null?void 0:L.data)==null?void 0:z.error)||"Failed to assign role"})}finally{h(!1)}},U=async(L=S)=>{var z,H,ye,ae,me,Q;y(!0);try{const oe=await dr.getUsersByRole(C,L,R),Ce=((H=(z=oe.data)==null?void 0:z.data)==null?void 0:H.users)||[],Ee=(ae=(ye=oe.data)==null?void 0:ye.data)==null?void 0:ae.pagination,be=(Q=(me=oe.data)==null?void 0:me.data)==null?void 0:Q.summary;b(Ce),Ee&&(_(Ee.currentPage),A(Ee.totalPages),P(Ee.totalUsers)),be&&w({admins:be.ADMIN||0,management:be.MANAGEMENT||0,users:be.USER||0})}catch(oe){console.error("Failed to fetch users:",oe)}finally{y(!1)}},I=async()=>{var L,z,H,ye,ae,me;try{const Q=await dr.getRoleStatistics(),oe=((z=(L=Q.data)==null?void 0:L.data)==null?void 0:z.statistics)||((H=Q.data)==null?void 0:H.statistics)||[];w({admins:parseInt(((ye=oe.find(Ce=>Ce.role==="ADMIN"))==null?void 0:ye.count)||"0"),management:parseInt(((ae=oe.find(Ce=>Ce.role==="MANAGEMENT"))==null?void 0:ae.count)||"0"),users:parseInt(((me=oe.find(Ce=>Ce.role==="USER"))==null?void 0:me.count)||"0")})}catch(Q){console.error("Failed to fetch statistics:",Q)}};p.useEffect(()=>{U(1),I()},[C]);const M=L=>{k(L),_(1)},W=L=>{U(L)},G=L=>{k(L),_(1),requestAnimationFrame(()=>{const z=F.current;z&&z.scrollIntoView({behavior:"smooth",block:"start"})})};p.useEffect(()=>{const L=z=>{O.current&&!O.current.contains(z.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",L),()=>{document.removeEventListener("mousedown",L)}},[a]);const ce=L=>{switch(L){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"}},te=L=>{switch(L){case"ADMIN":return e.jsx(Ln,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(cs,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(Vt,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(ee,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{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(f0,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx($e,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6",children:[e.jsx(ee,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${C==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>G("ADMIN"),children:e.jsx(se,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Administrators"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"admin-count",children:v.admins}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1 font-semibold",children:C==="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(Ln,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(ee,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${C==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>G("MANAGEMENT"),children:e.jsx(se,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Management"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"management-count",children:v.management}),e.jsx("p",{className:"text-xs text-blue-700 mt-1 font-semibold",children:C==="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(cs,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(ee,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${C==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>G("USER"),children:e.jsx(se,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Regular Users"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"user-count",children:v.users}),e.jsx("p",{className:"text-xs text-gray-700 mt-1 font-semibold",children:C==="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(Vt,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(Ts,{}),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:O,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(Oe,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:V,className:"pl-10 pr-10 border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"user-search-input"}),n&&e.jsx(lt,{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(L=>e.jsxs("button",{onClick:()=>T(L),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${L.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:L.displayName||L.email}),e.jsx("p",{className:"text-xs text-gray-600",children:L.email}),L.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[L.department,L.designation?` â€ĸ ${L.designation}`:""]})]},L.userId))})]})]}),l&&e.jsx("div",{className:"border-2 border-slate-300 bg-gradient-to-br from-slate-100 to-slate-50 rounded-lg p-4 shadow-sm",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-gradient-to-br from-slate-700 to-slate-500 flex items-center justify-center text-white font-bold shadow-md",children:(l.displayName||l.email).charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-slate-900",children:l.displayName||l.email}),e.jsx("p",{className:"text-sm text-slate-600",children:l.email}),l.department&&e.jsxs("p",{className:"text-xs text-slate-500 mt-1",children:[l.department,l.designation?` â€ĸ ${l.designation}`:""]})]})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>{o(null),s("")},className:"hover:bg-slate-200",children:"Clear"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Select Role"}),e.jsxs(We,{value:c,onValueChange:L=>d(L),children:[e.jsx(Ye,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(Ge,{placeholder:"Select role"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-gray-600"}),e.jsx("span",{children:"User - Regular access"})]})}),e.jsx(Y,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(Y,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ln,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(E,{onClick:j,disabled:!l||m,className:"w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"assign-role-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hs,{className:"w-4 h-4 mr-2"}),"Assign Role"]})}),x&&e.jsx("div",{className:`border-2 rounded-lg p-4 ${x.type==="success"?"border-green-200 bg-green-50":"border-red-200 bg-red-50"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[x.type==="success"?e.jsx(De,{className:"w-5 h-5 text-green-600 shrink-0 mt-0.5"}):e.jsx(ze,{className:"w-5 h-5 text-red-600 shrink-0 mt-0.5"}),e.jsx("p",{className:`text-sm ${x.type==="success"?"text-green-800":"text-red-800"}`,children:x.text})]})})]})]}),e.jsx(Ts,{}),e.jsxs("div",{ref:F,children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"User Management"}),e.jsxs("p",{className:"text-sm text-gray-600",children:["View and manage user roles (",N," ",C!=="ALL"&&C!=="ELEVATED"?C.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(We,{value:C,onValueChange:M,children:[e.jsx(Ye,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(Ge,{placeholder:"Filter by role"})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",v.admins+v.management,")"]})]})}),e.jsx(Y,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ln,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",v.admins,")"]})]})}),e.jsx(Y,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",v.management,")"]})]})}),e.jsx(Y,{value:"USER",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["Users (",v.users,")"]})]})}),e.jsx(Y,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",v.admins+v.management+v.users,")"]})]})})]})]})})]}),e.jsx("div",{className:"pt-2",children:f?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(lt,{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(cs,{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:C==="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(L=>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-${L.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 ${ce(L.role)} flex items-center justify-center shadow-sm`,children:te(L.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:L.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:L.email}),L.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[L.department,L.designation?` â€ĸ ${L.designation}`:""]})]})]}),e.jsx(ne,{className:`${ce(L.role)} shrink-0`,"data-testid":`role-badge-${L.role}`,children:L.role})]})},L.userId))}),D>1&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:["Showing ",(S-1)*R+1," to ",Math.min(S*R,N)," of ",N," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>W(S-1),disabled:S===1,"data-testid":"prev-page-button",children:"Previous"}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,D)},(L,z)=>{let H;return D<=5||S<=3?H=z+1:S>=D-2?H=D-4+z:H=S-2+z,e.jsx(E,{variant:S===H?"default":"outline",size:"sm",onClick:()=>W(H),className:`w-9 h-9 p-0 ${S===H?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${H}-button`,children:H},H)})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>W(S+1),disabled:S===D,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function fk(){const[t,s]=p.useState([]),[a,r]=p.useState(!0),[n,i]=p.useState(!1),[l,o]=p.useState(null),[c,d]=p.useState(null),[m,h]=p.useState(null),[x,u]=p.useState({title:"",itemCode:"",taxationType:"",sapRefNo:""});p.useEffect(()=>{g()},[]);const g=async()=>{var k,S;try{r(!0),d(null);const _=await aS(!1);s(_)}catch(_){const D=((S=(k=_.response)==null?void 0:k.data)==null?void 0:S.error)||"Failed to load activity types";d(D),K.error(D)}finally{r(!1)}},b=()=>{u({title:"",itemCode:"",taxationType:"",sapRefNo:""}),o(null),i(!0)},f=k=>{u({title:k.title,itemCode:k.itemCode||"",taxationType:k.taxationType||"",sapRefNo:k.sapRefNo||""}),o(k),i(!0)},y=async()=>{var k,S;try{if(d(null),!x.title.trim()){d("Activity type title is required");return}const _={title:x.title.trim(),itemCode:x.itemCode.trim()||null,taxationType:x.taxationType.trim()||null,sapRefNo:x.sapRefNo.trim()||null};l?(await nS(l.activityTypeId,_),h("Activity type updated successfully"),K.success("Activity type updated successfully")):(await rS(_),h("Activity type created successfully"),K.success("Activity type created successfully")),await g(),i(!1),setTimeout(()=>h(null),3e3)}catch(_){const D=((S=(k=_.response)==null?void 0:k.data)==null?void 0:S.error)||"Failed to save activity type";d(D),K.error(D)}},v=async k=>{var S,_;if(confirm(`Delete "${k.title}"? This will deactivate the activity type.`))try{d(null),await iS(k.activityTypeId),h("Activity type deleted successfully"),K.success("Activity type deleted successfully"),await g(),setTimeout(()=>h(null),3e3)}catch(D){const A=((_=(S=D.response)==null?void 0:S.data)==null?void 0:_.error)||"Failed to delete activity type";d(A),K.error(A)}},w=t.filter(k=>k.isActive!==!1&&k.isActive!==void 0),C=t.filter(k=>k.isActive===!1);return e.jsxs("div",{className:"space-y-6",children:[m&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(De,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:m})]}),c&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(ze,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-red-900",children:c}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>d(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsx(ge,{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(Re,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Activity Types"}),e.jsx($e,{className:"text-sm",children:"Manage dealer claim activity types"})]})]}),e.jsxs(E,{onClick:b,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm",children:[e.jsx(gs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Add Activity Type"}),e.jsx("span",{className:"xs:hidden",children:"Add"})]})]})})}),a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(lt,{className:"w-8 h-8 animate-spin text-gray-400"})}):w.length===0?e.jsx(ee,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(se,{className:"p-12 text-center",children:[e.jsx("div",{className:"p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4",children:e.jsx(Re,{className:"w-10 h-10 text-slate-400"})}),e.jsx("p",{className:"text-slate-700 font-medium text-lg",children:"No activity types found"}),e.jsx("p",{className:"text-sm text-slate-500 mt-2 mb-6",children:"Add activity types for dealer claim management"}),e.jsxs(E,{onClick:b,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(gs,{className:"w-4 h-4"}),"Add First Activity Type"]})]})}):e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(ee,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Active Activity Types"}),e.jsxs($e,{className:"text-xs sm:text-sm",children:[w.length," active type",w.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-green-50 rounded-md",children:e.jsx(De,{className:"w-4 h-4 text-green-600"})})]})}),e.jsx(se,{className:"space-y-3 pt-4",children:w.map(k=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 hover:border-slate-300 transition-all shadow-sm",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-900 text-sm sm:text-base",children:k.title}),e.jsx(ne,{variant:"outline",className:"bg-gradient-to-r from-green-50 to-emerald-50 text-green-800 border-green-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Active"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs sm:text-sm text-slate-600",children:[k.itemCode&&e.jsxs("span",{className:"font-medium",children:["Item Code: ",e.jsx("span",{className:"text-slate-900",children:k.itemCode})]}),k.taxationType&&e.jsxs("span",{className:"font-medium",children:["Taxation: ",e.jsx("span",{className:"text-slate-900",children:k.taxationType})]}),k.sapRefNo&&e.jsxs("span",{className:"font-medium",children:["SAP Ref: ",e.jsx("span",{className:"text-slate-900",children:k.sapRefNo})]}),!k.itemCode&&!k.taxationType&&!k.sapRefNo&&e.jsx("span",{className:"text-slate-500 italic",children:"No additional details"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:[e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>f(k),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>v(k),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(yo,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},k.activityTypeId))})]}),C.length>0&&e.jsxs(ee,{className:"shadow-lg border-0 rounded-md border-amber-200",children:[e.jsx(ge,{className:"pb-3 sm:pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(fe,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Inactive Activity Types"}),e.jsxs($e,{className:"text-xs sm:text-sm",children:[C.length," inactive type",C.length!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-amber-50 rounded-md",children:e.jsx(ze,{className:"w-4 h-4 text-amber-600"})})]})}),e.jsx(se,{className:"space-y-3 pt-4",children:C.map(k=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 p-3 sm:p-4 bg-amber-50/50 border border-amber-200 rounded-md hover:bg-amber-50 hover:border-amber-300 transition-all shadow-sm",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx("p",{className:"font-semibold text-slate-700 text-sm sm:text-base line-through",children:k.title}),e.jsx(ne,{variant:"outline",className:"bg-gradient-to-r from-amber-50 to-orange-50 text-amber-800 border-amber-300 text-[10px] sm:text-xs font-medium shadow-sm",children:"Inactive"})]})}),e.jsx("div",{className:"flex items-center gap-2 sm:gap-2 self-end sm:self-auto",children:e.jsxs(E,{size:"sm",variant:"ghost",onClick:()=>f(k),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]})})]},k.activityTypeId))})]})]}),e.jsx(pt,{open:n,onOpenChange:i,children:e.jsxs(dt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(gt,{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(Re,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(mt,{className:"text-xl font-semibold text-slate-900",children:l?"Edit Activity Type":"Add New Activity Type"}),e.jsx(Dt,{className:"text-sm text-slate-600 mt-1",children:l?"Update activity type information":"Add a new activity type for dealer claim management"})]})]})}),e.jsxs("div",{className:"space-y-5 py-6 px-6 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"title",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Title ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Oe,{id:"title",placeholder:"e.g., Riders Mania Claims, Legal Claims Reimbursement",value:x.title,onChange:k=>u({...x,title:k.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the activity type title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"itemCode",className:"text-sm font-semibold text-slate-900",children:["Item Code ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Oe,{id:"itemCode",placeholder:"e.g., 1, 2, 3",value:x.itemCode,onChange:k=>u({...x,itemCode:k.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional item code for the activity type"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"taxationType",className:"text-sm font-semibold text-slate-900",children:["Taxation Type ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Oe,{id:"taxationType",placeholder:"e.g., GST, VAT, Exempt",value:x.taxationType,onChange:k=>u({...x,taxationType:k.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 taxation type for the activity"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"sapRefNo",className:"text-sm font-semibold text-slate-900",children:["SAP Reference Number ",e.jsx("span",{className:"text-slate-400 font-normal text-xs",children:"(Optional)"})]}),e.jsx(Oe,{id:"sapRefNo",placeholder:"e.g., SAP-12345",value:x.sapRefNo,onChange:k=>u({...x,sapRefNo:k.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 SAP reference number"})]})]}),e.jsxs(Tt,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(E,{variant:"outline",onClick:()=>i(!1),className:"h-11 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:"Cancel"}),e.jsxs(E,{onClick:y,disabled:!x.title.trim(),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(Re,{className:"w-4 h-4 mr-2"}),l?"Update Activity Type":"Add Activity Type"]})]})]})})]})}function bk({open:t,onClose:s,success:a,message:r}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(qs,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(Dt,{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(De,{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(wt,{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(Tt,{children:e.jsx(E,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const yk=async()=>(await je.get("/user/preferences/notifications")).data.data,vk=async t=>(await je.put("/user/preferences/notifications",t)).data.data;function jk({open:t,onClose:s}){const[a,r]=p.useState({emailNotificationsEnabled:!0,pushNotificationsEnabled:!0,inAppNotificationsEnabled:!0}),[n,i]=p.useState(!0),[l,o]=p.useState(null),[c,d]=p.useState(null),[m,h]=p.useState(null);p.useEffect(()=>{t&&x()},[t]);const x=async()=>{var g,b;try{i(!0),h(null);const f=await yk();r(f)}catch(f){console.error("[NotificationPreferences] Failed to load preferences:",f),h(((b=(g=f.response)==null?void 0:g.data)==null?void 0:b.message)||"Failed to load notification preferences")}finally{i(!1)}},u=async(g,b)=>{var f,y;try{o(g),h(null),d(null);const v={[g]:b},w=await vk(v);r(w),d(`${g==="emailNotificationsEnabled"?"Email":g==="pushNotificationsEnabled"?"Push":"In-App"} notifications ${b?"enabled":"disabled"}`),setTimeout(()=>d(null),3e3)}catch(v){console.error("[NotificationPreferences] Failed to update preference:",v),h(((y=(f=v.response)==null?void 0:f.data)==null?void 0:y.message)||"Failed to update notification preference"),x()}finally{o(null)}};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(gt,{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(Va,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(mt,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(Dt,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx(Ts,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(lt,{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(De,{className:"w-4 h-4 text-green-600 shrink-0"}),e.jsx("p",{className:"text-sm text-green-800 font-medium",children:c})]}),m&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-md animate-in fade-in slide-in-from-top-2",children:[e.jsx(ze,{className:"w-4 h-4 text-red-600 shrink-0"}),e.jsx("p",{className:"text-sm text-red-800 font-medium",children:m})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(Ra,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Email Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Receive important updates and alerts via email"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="emailNotificationsEnabled"&&e.jsx(lt,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(on,{id:"email-notifications-modal",checked:a.emailNotificationsEnabled,onCheckedChange:g=>u("emailNotificationsEnabled",g),disabled:l==="emailNotificationsEnabled"})]})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(qs,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"push-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"Push Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Get instant browser notifications for real-time updates"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="pushNotificationsEnabled"&&e.jsx(lt,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(on,{id:"push-notifications-modal",checked:a.pushNotificationsEnabled,onCheckedChange:g=>u("pushNotificationsEnabled",g),disabled:l==="pushNotificationsEnabled"})]})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg border border-gray-200 hover:border-gray-300 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 bg-white rounded-lg shadow-sm",children:e.jsx(As,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"inapp-notifications-modal",className:"text-base font-semibold text-gray-900 cursor-pointer",children:"In-App Notifications"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"View notifications in the notification center"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l==="inAppNotificationsEnabled"&&e.jsx(lt,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(on,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>u("inAppNotificationsEnabled",g),disabled:l==="inAppNotificationsEnabled"})]})]})}),e.jsx(Ts,{}),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 Nk(){const{user:t}=Kt(),s=lr(t),[a,r]=p.useState(!1),[n,i]=p.useState(!1),[l,o]=p.useState(),[c,d]=p.useState(!1),[m,h]=p.useState(!1),[x,u]=p.useState(!1),[g,b]=p.useState(!0),[f,y]=p.useState(!1);p.useEffect(()=>{v()},[]);const v=async()=>{try{b(!0);const C=await ry();u(C.length>0)}catch(C){console.error("Failed to check subscription status:",C),u(!1)}finally{b(!1)}},w=async()=>{d(!0),r(!1);try{if(!("Notification"in window)){i(!1),o("Notifications are not supported in this browser. Please use a modern browser like Chrome, Firefox, or Edge."),r(!0),d(!1);return}let C=Notification.permission;if(C==="denied"){i(!1),o(`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 diff --git a/build/index.html b/build/index.html index ea30cc7..d6cebea 100644 --- a/build/index.html +++ b/build/index.html @@ -13,7 +13,7 @@ - + diff --git a/src/app.ts b/src/app.ts index 636683a..09d1e1c 100644 --- a/src/app.ts +++ b/src/app.ts @@ -25,7 +25,7 @@ const app: express.Application = express(); // 1. Security middleware - Manual "Gold Standard" CSP to ensure it survives 301/404/etc. // This handles a specific Express/Helmet edge case where redirects lose headers. app.use((req: express.Request, res: express.Response, next: express.NextFunction) => { - const isDev = process.env.NODE_ENV !== 'production'; + const isDev = process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'local'; const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3000'; // Build connect-src dynamically @@ -49,8 +49,8 @@ app.use((req: express.Request, res: express.Response, next: express.NextFunction "base-uri 'self'", "default-src 'none'", `connect-src ${connectSrc.join(' ')}`, - "style-src 'self' https://fonts.googleapis.com 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=' 'sha256-Od9mHMH7x2G6QuoV3hsPkDCwIyqbg2DX3F5nLeCYQBc=' 'sha256-eSB4TBEI8J+pgd6+gnmCP4Q+C+Yrx5BdjBEoPvZUzZI=' 'sha256-nzTgYzXYDNe6BAHiiI7NNlfK8n/auuOAhh2t92YvuXo='", - "style-src-elem 'self' https://fonts.googleapis.com 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=' 'sha256-Od9mHMH7x2G6QuoV3hsPkDCwIyqbg2DX3F5nLeCYQBc=' 'sha256-eSB4TBEI8J+pgd6+gnmCP4Q+C+Yrx5BdjBEoPvZUzZI=' 'sha256-nzTgYzXYDNe6BAHiiI7NNlfK8n/auuOAhh2t92YvuXo='", + "style-src 'self' https://fonts.googleapis.com 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=' 'sha256-Od9mHMH7x2G6QuoV3hsPkDCwIyqbg2DX3F5nLeCYQBc=' 'sha256-eSB4TBEI8J+pgd6+gnmCP4Q+C+Yrx5BdjBEoPvZUzZI=' 'sha256-nzTgYzXYDNe6BAHiiI7NNlfK8n/auuOAhh2t92YvuXo=' 'sha256-441zG27rExd4/il+NvIqyL8zFx5XmyNQtE381kSkUJk='", + "style-src-elem 'self' https://fonts.googleapis.com 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=' 'sha256-Od9mHMH7x2G6QuoV3hsPkDCwIyqbg2DX3F5nLeCYQBc=' 'sha256-eSB4TBEI8J+pgd6+gnmCP4Q+C+Yrx5BdjBEoPvZUzZI=' 'sha256-nzTgYzXYDNe6BAHiiI7NNlfK8n/auuOAhh2t92YvuXo=' 'sha256-441zG27rExd4/il+NvIqyL8zFx5XmyNQtE381kSkUJk='", "style-src-attr 'unsafe-inline'", "script-src 'self'", "script-src-elem 'self'",