diff --git a/build/assets/conclusionApi-DRbYq2Mu.js b/build/assets/conclusionApi-CeVXrM6b.js similarity index 90% rename from build/assets/conclusionApi-DRbYq2Mu.js rename to build/assets/conclusionApi-CeVXrM6b.js index d7e4ea4..47b78b7 100644 --- a/build/assets/conclusionApi-DRbYq2Mu.js +++ b/build/assets/conclusionApi-CeVXrM6b.js @@ -1 +1 @@ -import{a as s}from"./index-CIAyP-D4.js";import"./radix-vendor-CYvDqP9X.js";import"./charts-vendor-BVfwAPj-.js";import"./utils-vendor-BTBPSQfW.js";import"./ui-vendor-CxsBWvVP.js";import"./socket-vendor-TjCxX7sJ.js";import"./redux-vendor-tbZCm13o.js";import"./router-vendor-BATWUvr6.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-DyTD6GiQ.js";import"./radix-vendor-CYvDqP9X.js";import"./charts-vendor-BVfwAPj-.js";import"./utils-vendor-BTBPSQfW.js";import"./ui-vendor-CxsBWvVP.js";import"./socket-vendor-TjCxX7sJ.js";import"./redux-vendor-tbZCm13o.js";import"./router-vendor-BATWUvr6.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-CIAyP-D4.js b/build/assets/index-DyTD6GiQ.js similarity index 84% rename from build/assets/index-CIAyP-D4.js rename to build/assets/index-DyTD6GiQ.js index 1e869d5..8a90e54 100644 --- a/build/assets/index-CIAyP-D4.js +++ b/build/assets/index-DyTD6GiQ.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-DRbYq2Mu.js","assets/radix-vendor-CYvDqP9X.js","assets/charts-vendor-BVfwAPj-.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-CxsBWvVP.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-BATWUvr6.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-CeVXrM6b.js","assets/radix-vendor-CYvDqP9X.js","assets/charts-vendor-BVfwAPj-.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-CxsBWvVP.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-BATWUvr6.js"])))=>i.map(i=>d[i]); var $0=Object.defineProperty;var U0=(t,s,a)=>s in t?$0(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var xl=(t,s,a)=>U0(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Ox,R as $x,I as Ux,F as Bx,a as B0,T as V0,P as z0,C as H0,b as W0,O as Vx,c as zx,d as G0,e as Y0,f as K0,D as Q0,g as X0,A as J0,h as Z0,i as q0,k as ef,l as tf,m as sf,n as af,V as rf,o as nf,p as lf,q as of,r as cf,s as df,t as mf,u as uf,v as xf,w as hf,x as pf,y as gf,z as ff,B as bf,E as jf,G as yf,H as vf,J as Nf,K as wf,L as Cf,M as Sf,N as Af,Q as Hx,U as Wx,W as Tf,X as Gx,Y as Yx,Z as kf,_ as Rf,$ as Df,a0 as Ff,a1 as If,a2 as Pf,a3 as Ef,a4 as _f,a5 as Mf,a6 as Lf,a7 as Of,a8 as $f,a9 as Uf,aa as Bf,ab as Vf}from"./radix-vendor-CYvDqP9X.js";import{a as zf,r as h,c as Kx,d as Qr,B as to,C as Si,X as Ai,Y as Ti,T as Xr,L as ki,e as ka,P as Qx,f as Xx,g as Jx,h as Hf,i as Cm,j as Vi,k as zi,b as Wf}from"./charts-vendor-BVfwAPj-.js";import{a as Eo,f as Zx,s as aa,e as _o,b as Sm,c as Gf,d as Ia,g as Mn,i as Mo,h as qx,j as Xs,k as ea,l as hl,m as Va,n as Yf,o as so,p as Kf,q as et,r as ao,t as Qf,u as Xf,v as Jf,w as Zf,x as pl,y as Am,z as qf,A as eh,B as th,C as Lo,D as Oo,E as eb,F as tb,G as sh,H as Ur,I as gl,J as sb,K as ab,L as rb}from"./utils-vendor-BTBPSQfW.js";import{A as fs,S as ps,C as Ze,a as us,L as Qe,X as jt,H as nb,b as ah,U as Vt,F as Ie,c as Oe,d as an,R as Pt,e as rn,f as nn,P as bs,g as ib,h as lb,B as Ms,i as cr,j as fl,k as $o,l as za,m as Hi,n as Uo,o as dt,p as Pa,q as Ut,I as _r,T as qt,r as st,s as Ca,t as ob,u as es,M as Hs,v as Wi,w as $t,x as ro,D as Rt,Z as Gi,y as Jt,z as cb,E as db,G as mb,J as ub,K as xb,N as hb,O as pb,Q as gb,V as fb,W as rh,Y as bb,_ as jb,$ as nh,a0 as fa,a1 as Hn,a2 as dr,a3 as Ri,a4 as Tm,a5 as ri,a6 as Di,a7 as ih,a8 as At,a9 as yb,aa as X,ab as Ws,ac as Bo,ad as Cs,ae as Yi,af as lh,ag as St,ah as vb,ai as Nb,aj as oh,ak as Ki,al as ch,am as wb,an as Vo,ao as js,ap as Ha,aq as dh,ar as Qi,as as Xi,at as Ss,au as Cb,av as Sb,aw as mh,ax as uh,ay as hi,az as ir,aA as zo,aB as Ji,aC as Fi,aD as xh,aE as hh,aF as Ho,aG as Zi,aH as qi,aI as Ab,aJ as or,aK as ph,aL as Ii,aM as Tb,aN as kb,aO as Rb,aP as el,aQ as tl,aR as Wo,aS as Db,aT as km,aU as Ea,aV as ln,aW as Fb,aX as Vr,aY as Ib,aZ as gh,a_ as Rm,a$ as fh,b0 as Pb,b1 as Eb,b2 as _b,b3 as Mb,b4 as bh,b5 as Lb,b6 as Ob,b7 as $b,b8 as Ub,b9 as Bb}from"./ui-vendor-CxsBWvVP.js";import{l as Vb}from"./socket-vendor-TjCxX7sJ.js";import{c as on,a as zb}from"./redux-vendor-tbZCm13o.js";import{u as ys,a as _a,b as jh,c as Hb,B as Wb,R as Gb,d as It,O as Yb}from"./router-vendor-BATWUvr6.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 no={},Dm=zf;no.createRoot=Dm.createRoot,no.hydrateRoot=Dm.hydrateRoot;var yh={exports:{}},vh={};var Wn=h;function Kb(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var Qb=typeof Object.is=="function"?Object.is:Kb,Xb=Wn.useSyncExternalStore,Jb=Wn.useRef,Zb=Wn.useEffect,qb=Wn.useMemo,ej=Wn.useDebugValue;vh.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=Jb(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=qb(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 p=g}return p=u}if(g=p,Qb(m,u))return g;var f=r(u);return n!==void 0&&n(g,f)?(m=u,g):(m=u,p=f)}var d=!1,m,p,x=a===void 0?null:a;return[function(){return c(s())},x===null?void 0:function(){return c(x())}]},[s,a,r,n]);var o=Xb(t,i[0],i[1]);return Zb(function(){l.hasValue=!0,l.value=o},[o]),ej(o),o};yh.exports=vh;var tj=yh.exports;function sj(t){t()}function aj(){let t=null,s=null;return{clear(){t=null,s=null},notify(){sj(()=>{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 Fm={notify(){},get:()=>[]};function rj(t,s){let a,r=Fm,n=0,i=!1;function l(f){m();const b=r.subscribe(f);let j=!1;return()=>{j||(j=!0,b(),p())}}function o(){r.notify()}function c(){g.onStateChange&&g.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=aj())}function p(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Fm)}function x(){i||(i=!0,m())}function u(){i&&(i=!1,p())}const g={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:c,isSubscribed:d,trySubscribe:x,tryUnsubscribe:u,getListeners:()=>r};return g}var nj=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",ij=nj(),lj=()=>typeof navigator<"u"&&navigator.product==="ReactNative",oj=lj(),cj=()=>ij||oj?h.useLayoutEffect:h.useEffect,dj=cj(),bl=Symbol.for("react-redux-context"),jl=typeof globalThis<"u"?globalThis:{};function mj(){if(!h.createContext)return{};const t=jl[bl]??(jl[bl]=new Map);let s=t.get(h.createContext);return s||(s=h.createContext(null),t.set(h.createContext,s)),s}var mr=mj();function uj(t){const{children:s,context:a,serverState:r,store:n}=t,i=h.useMemo(()=>{const c=rj(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=h.useMemo(()=>n.getState(),[n]);dj(()=>{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||mr;return h.createElement(o.Provider,{value:i},s)}var xj=uj;function Go(t=mr){return function(){return h.useContext(t)}}var Nh=Go();function wh(t=mr){const s=t===mr?Nh:Go(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var hj=wh();function pj(t=mr){const s=t===mr?hj:wh(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var gj=pj(),fj=(t,s)=>t===s;function bj(t=mr){const s=t===mr?Nh:Go(t),a=(r,n={})=>{const{equalityFn:i=fj}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:c,getServerState:d}=l;h.useRef(!0);const m=h.useCallback({[r.name](x){return r(x)}}[r.name],[r]),p=tj.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return h.useDebugValue(p),p};return Object.assign(a,{withTypes:()=>a}),a}var jj=bj(),io=function(t,s){return io=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])},io(t,s)};function yj(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");io(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var Pi=function(){return Pi=Object.assign||function(s){for(var a,r=1,n=arguments.length;r0&&g[g.length-1])||v[0]!==6&&v[0]!==2)){b=0;continue}if(v[0]===3&&(!g||v[1]>g[0]&&v[1]0?setTimeout(u,w):u(null)}}window.addEventListener("storage",j),m.addToWaiting(j);var y=setTimeout(j,Math.max(0,p-Date.now()))})];case 1:return x.sent(),[2]}})})},m.addToWaiting=function(p){this.removeFromWaiting(p),m.waiters!==void 0&&m.waiters.push(p)},m.removeFromWaiting=function(p){m.waiters!==void 0&&(m.waiters=m.waiters.filter(function(x){return x!==p}))},m.notifyWaiters=function(){m.waiters!==void 0&&m.waiters.slice().forEach(function(p){return p()})},m.prototype.releaseLock=function(p){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,this.releaseLock__private__(p)];case 1:return[2,x.sent()]}})})},m.prototype.releaseLock__private__=function(p){return a(this,void 0,void 0,function(){var x,u,g,f;return r(this,function(b){switch(b.label){case 0:return x=this.storageHandler===void 0?l:this.storageHandler,u=i+"-"+p,(g=x.getItemSync(u))===null?[2]:(f=JSON.parse(g)).id!==this.id?[3,2]:[4,vr.default().lock(f.iat)];case 1:b.sent(),this.acquiredIatSet.delete(f.iat),x.removeItemSync(u),vr.default().unlock(f.iat),m.notifyWaiters(),b.label=2;case 2:return[2]}})})},m.lockCorrector=function(p){for(var x=Date.now()-5e3,u=p,g=[],f=0;;){var b=u.keySync(f);if(b===null)break;g.push(b),f++}for(var j=!1,y=0;y.")},wj=Pi(Pi({},Nj),{buildAuthorizeUrl:Ys,buildLogoutUrl:Ys,getAccessTokenSilently:Ys,getAccessTokenWithPopup:Ys,getIdTokenClaims:Ys,loginWithRedirect:Ys,loginWithPopup:Ys,connectAccountWithRedirect:Ys,logout:Ys,handleRedirectCallback:Ys,getDpopNonce:Ys,setDpopNonce:Ys,generateDpopProof:Ys,createFetcher:Ys}),Cj=h.createContext(wj);(function(t){yj(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 Sj=function(t){return t===void 0&&(t=Cj),h.useContext(t)};const yl="idToken",vl="userData",Aj=()=>!0;class at{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(yl,s)}static getIdToken(){return sessionStorage.getItem(yl)}static setUserData(s){localStorage.setItem(vl,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(vl);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(vl),sessionStorage.removeItem(yl)}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 Aj()}}function Nl(t,s=5){if(!t)return!0;try{const a=t.split(".");if(a.length!==3||!a[1])return!0;const n=JSON.parse(atob(a[1])).exp*1e3,i=Date.now(),l=s*60*1e3;return n-i{if(t.data instanceof FormData){const s=t.headers;delete s["Content-Type"],s.common&&typeof s.common=="object"&&delete s.common["Content-Type"],s.post&&typeof s.post=="object"&&delete s.post["Content-Type"]}return t},t=>Promise.reject(t));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=at.getRefreshToken(),l=await Eo.post(`${Ch}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),c=(l.data.data||l.data).accessToken;return je(s)}catch(i){return at.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function Tj(t,s){const r=(await je.post("/auth/login",{username:t,password:s},{withCredentials:!0})).data,n=r.data||r;return n.user&&at.setUserData(n.user),n.accessToken&&n.refreshToken&&(at.setAccessToken(n.accessToken),at.setRefreshToken(n.refreshToken)),n}async function kj(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&&at.setUserData(l.user),l.idToken&&at.setIdToken(l.idToken),l.accessToken&&l.refreshToken&&(at.setAccessToken(l.accessToken),at.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 Rj(){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 An(){const s=(await je.get("/auth/me")).data;return s.data||s}async function Dj(){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 lo="https://ssodev.rebridge.co.in/realms/RE",Sh="REFLOW",Qo=`${window.location.origin}/login/callback`;function Fj(){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=`${lo}/protocol/openid-connect/auth?client_id=${Sh}&response_type=code&scope=openid&redirect_uri=${encodeURIComponent(Qo)}&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 Ij(t,s){var r,n,i;const a="https://reflow-uat.royalenfield.com/api/v1/";try{const l=await Eo.post(`${a}/auth/tanflow/token-exchange`,{code:t,redirectUri:Qo,state:s},{withCredentials:!0,headers:{"Content-Type":"application/json"}}),o=((r=l.data)==null?void 0:r.data)||l.data;return o.accessToken&&at.setAccessToken(o.accessToken),o.refreshToken&&at.setRefreshToken(o.refreshToken),o.idToken&&at.setIdToken(o.idToken),o.user&&at.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 Pj(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=Qo,a=new URL(`${lo}/protocol/openid-connect/logout`);a.searchParams.set("client_id",Sh),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:`${lo}/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 Ah=h.createContext(void 0);function Ej({children:t}){const[s,a]=h.useState(!1),[r,n]=h.useState(!0),[i,l]=h.useState(null),[o,c]=h.useState(null),[d,m]=h.useState(!1);h.useEffect(()=>{const w=sessionStorage.getItem("__logout_in_progress__"),v=sessionStorage.getItem("__force_logout__");if(w==="true"||v==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),at.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(D){console.error("Error clearing storage:",D)}a(!1),l(null),n(!1),c(null);return}const C=new URLSearchParams(window.location.search),A=C.has("code");if((C.has("logout")||C.has("okta_logged_out")||C.has("tanflow_logged_out"))&&!A){console.log("🚪 Logout parameter detected in URL, clearing all tokens"),at.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);try{sessionStorage.setItem("__force_reauth_after_logout__","true")}catch(D){console.warn("Could not set force reauth flag:",D)}window.history.replaceState({},document.title,"/");return}window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback"||(at.getUserData(),d?n(!1):x())},[d]),h.useEffect(()=>{if(!s)return;const w=async()=>{try{await j()}catch(A){console.error("Silent refresh failed:",A)}},v=10*60*1e3,C=setInterval(w,v);return()=>clearInterval(C)},[s]);const p=h.useRef(!1);h.useEffect(()=>{if(p.current||window.location.pathname!=="/login/callback")return;(async()=>{const v=new URLSearchParams(window.location.search);if(sessionStorage.getItem("auth_provider")==="tanflow")return;if((v.has("logout")||v.has("tanflow_logged_out")||v.has("okta_logged_out"))&&!v.get("code")){console.log("🚪 Logout redirect detected in callback, redirecting to home");const D=new URLSearchParams;v.has("tanflow_logged_out")&&D.set("tanflow_logged_out","true"),v.has("okta_logged_out")&&D.set("okta_logged_out","true"),v.has("logout")&&D.set("logout",v.get("logout")||Date.now().toString());const R=D.toString()?`/?${D.toString()}`:"/?logout="+Date.now();window.location.replace(R);return}p.current=!0;const A=v.get("code"),L=v.get("error");if(window.history.replaceState({},document.title,"/login/callback"),L){c(new Error(`Authentication error: ${L}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!A){n(!1),sessionStorage.removeItem("auth_provider");return}try{n(!0),a(!1),c(null);const D=`${window.location.origin}/login/callback`,R=await kj(A,D);l(R.user),a(!0),c(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(D){console.error("❌ Token exchange error in AuthContext:",D),c(D),a(!1),l(null),sessionStorage.removeItem("auth_provider"),p.current=!1}finally{n(!1)}})()},[]);const x=async()=>{var v;if(d){n(!1);return}const w=!0;try{if(n(!0),w){const L=at.getUserData();try{const D=await An();l(D),at.setUserData(D),a(!0)}catch(D){if(((v=D==null?void 0:D.response)==null?void 0:v.status)===401)try{await j();const R=await An();l(R),at.setUserData(R),a(!0)}catch{at.clearAll(),a(!1),l(null)}else D!=null&&D.isConnectionError?L?(l(L),a(!0)):(a(!1),l(null)):(at.clearAll(),a(!1),l(null))}return}const C=at.getAccessToken(),A=at.getUserData();if(!C){a(!1),l(null),n(!1);return}if(Nl(C))try{await j();const L=at.getAccessToken();if(L&&!Nl(L)){const D=at.getUserData();if(D)l(D),a(!0);else try{const R=await An();l(R),at.setUserData(R),a(!0)}catch{at.clearAll(),a(!1),l(null)}}else at.clearAll(),a(!1),l(null)}catch{at.clearAll(),a(!1),l(null)}else if(A)l(A),a(!0);else try{const L=await An();l(L),at.setUserData(L),a(!0)}catch{at.clearAll(),a(!1),l(null)}}catch(C){console.error("Error checking auth status:",C),c(C),at.clearAll(),a(!1),l(null)}finally{n(!1)}},u=async()=>{try{c(null);const w="https://dev-830839.oktapreview.com",v="0oa2jgzvrpdwx2iqd0h8",C=`${window.location.origin}/login/callback`,A="code",L="openid profile email",D=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const R=new URLSearchParams(window.location.search),N=R.has("logout")||R.has("okta_logged_out")||R.has("tanflow_logged_out"),_=sessionStorage.getItem("__force_reauth_after_logout__")==="true",S=N||_;let U=`${w}/oauth2/default/v1/authorize?client_id=${v}&redirect_uri=${encodeURIComponent(C)}&response_type=${A}&scope=${encodeURIComponent(L)}&state=${D}`;S&&(U+="&prompt=login",sessionStorage.removeItem("__force_reauth_after_logout__")),window.location.href=U}catch(w){throw c(w),w}},g=async(w,v)=>{c(null),n(!0);try{const C=await Tj(w,v);l(C.user),a(!0),window.history.replaceState({},document.title,"/")}catch(C){throw c(C),a(!1),l(null),C}finally{n(!1)}},f=async()=>{try{const w=at.getIdToken(),v=sessionStorage.getItem("auth_provider")||(w&&w.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 Dj(),console.log("🚪 Backend logout API called successfully")}catch(R){console.error("🚪 Logout API error:",R),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const C=sessionStorage.getItem("__logout_in_progress__"),A=sessionStorage.getItem("__force_logout__"),L=sessionStorage.getItem("auth_provider");if(at.clearAll(),C&&sessionStorage.setItem("__logout_in_progress__",C),A&&sessionStorage.setItem("__force_logout__",A),w&&at.setIdToken(w),L&&sessionStorage.setItem("auth_provider",L),await new Promise(R=>setTimeout(R,100)),v==="tanflow"&&w){console.log("🚪 Initiating Tanflow logout...");try{Pj(w);return}catch(R){console.error("🚪 Tanflow logout error:",R)}}console.log("🚪 Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),w&&at.clearAll();const D=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(D)}catch(w){console.error("🚪 Logout error:",w);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const v=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(v)}catch{window.location.replace("/?logout="+Date.now())}}},b=async()=>{{if(s)return"cookie-based-auth";try{return await j(),s?"cookie-based-auth":null}catch{return null}}const w=at.getAccessToken();if(w&&!Nl(w))return w;try{return await j(),at.getAccessToken()}catch{return null}},j=async()=>{try{const v=await Rj();return}catch(v){throw at.clearAll(),a(!1),l(null),v}},y={isAuthenticated:s,isLoading:r,user:i,error:o,login:u,loginWithPassword:g,logout:f,getAccessTokenSilently:b,refreshTokenSilently:j};return e.jsx(Ah.Provider,{value:y,children:t})}function _j({children:t}){return e.jsx(Ej,{children:t})}function cs(){const t=h.useContext(Ah);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function Nr(t){return(t==null?void 0:t.role)==="ADMIN"}function bn(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function sl(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const Em=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,_m=Kx,Xo=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return _m(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,l=Object.keys(n).map(d=>{const m=a==null?void 0:a[d],p=i==null?void 0:i[d];if(m===null)return null;const x=Em(m)||Em(p);return n[d][x]}),o=a&&Object.entries(a).reduce((d,m)=>{let[p,x]=m;return x===void 0||(d[p]=x),d},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((d,m)=>{let{class:p,className:x,...u}=m;return Object.entries(u).every(g=>{let[f,b]=g;return Array.isArray(b)?b.includes({...i,...o}[f]):{...i,...o}[f]===b})?[...d,p,x]:d},[]);return _m(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},Jo="-",Mj=t=>{const s=Oj(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(Jo);return o[0]===""&&o.length!==1&&o.shift(),Th(o,s)||Lj(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},Th=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?Th(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(Jo);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Mm=/^\[(.+)\]$/,Lj=t=>{if(Mm.test(t)){const s=Mm.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},Oj=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return Uj(Object.entries(t.classGroups),a).forEach(([i,l])=>{oo(l,r,i,s)}),r},oo=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:Lm(s,n);i.classGroupId=a;return}if(typeof n=="function"){if($j(n)){oo(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{oo(l,Lm(s,i),a,r)})})},Lm=(t,s)=>{let a=t;return s.split(Jo).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},$j=t=>t.isThemeGetter,Uj=(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,Bj=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)}}},kh="!",Vj=t=>{const{separator:s,experimentalParseClassName:a}=t,r=s.length===1,n=s[0],i=s.length,l=o=>{const c=[];let d=0,m=0,p;for(let b=0;bm?p-m:void 0;return{modifiers:c,hasImportantModifier:u,baseClassName:g,maybePostfixModifierPosition:f}};return a?o=>a({className:o,parseClassName:l}):l},zj=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},Hj=t=>({cache:Bj(t.cacheSize),parseClassName:Vj(t),...Mj(t)}),Wj=/\s+/,Gj=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(Wj);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:m,hasImportantModifier:p,baseClassName:x,maybePostfixModifierPosition:u}=a(d);let g=!!u,f=r(g?x.substring(0,u):x);if(!f){if(!g){o=d+(o.length>0?" "+o:o);continue}if(f=r(x),!f){o=d+(o.length>0?" "+o:o);continue}g=!1}const b=zj(m).join(":"),j=p?b+kh:b,y=j+f;if(i.includes(y))continue;i.push(y);const w=n(f,g);for(let v=0;v0?" "+o:o)}return o};function Yj(){let t=0,s,a,r="";for(;t{if(typeof t=="string")return t;let s,a="";for(let r=0;rp(m),t());return a=Hj(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=Gj(c,a);return n(c,m),m}return function(){return i(Yj.apply(null,arguments))}}const Yt=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},Dh=/^\[(?:([a-z-]+):)?(.+)\]$/i,Qj=/^\d+\/\d+$/,Xj=new Set(["px","full","screen"]),Jj=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Zj=/\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$/,qj=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,ey=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ty=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,$a=t=>Jr(t)||Xj.has(t)||Qj.test(t),ar=t=>cn(t,"length",cy),Jr=t=>!!t&&!Number.isNaN(Number(t)),wl=t=>cn(t,"number",Jr),jn=t=>!!t&&Number.isInteger(Number(t)),sy=t=>t.endsWith("%")&&Jr(t.slice(0,-1)),bt=t=>Dh.test(t),rr=t=>Jj.test(t),ay=new Set(["length","size","percentage"]),ry=t=>cn(t,ay,Fh),ny=t=>cn(t,"position",Fh),iy=new Set(["image","url"]),ly=t=>cn(t,iy,my),oy=t=>cn(t,"",dy),yn=()=>!0,cn=(t,s,a)=>{const r=Dh.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},cy=t=>Zj.test(t)&&!qj.test(t),Fh=()=>!1,dy=t=>ey.test(t),my=t=>ty.test(t),uy=()=>{const t=Yt("colors"),s=Yt("spacing"),a=Yt("blur"),r=Yt("brightness"),n=Yt("borderColor"),i=Yt("borderRadius"),l=Yt("borderSpacing"),o=Yt("borderWidth"),c=Yt("contrast"),d=Yt("grayscale"),m=Yt("hueRotate"),p=Yt("invert"),x=Yt("gap"),u=Yt("gradientColorStops"),g=Yt("gradientColorStopPositions"),f=Yt("inset"),b=Yt("margin"),j=Yt("opacity"),y=Yt("padding"),w=Yt("saturate"),v=Yt("scale"),C=Yt("sepia"),A=Yt("skew"),L=Yt("space"),D=Yt("translate"),R=()=>["auto","contain","none"],N=()=>["auto","hidden","clip","visible","scroll"],_=()=>["auto",bt,s],S=()=>[bt,s],U=()=>["",$a,ar],F=()=>["auto",Jr,bt],$=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],P=()=>["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"],k=()=>["start","end","center","between","around","evenly","stretch"],B=()=>["","0",bt],I=()=>["auto","avoid","all","avoid-page","page","left","right","column"],E=()=>[Jr,bt];return{cacheSize:500,separator:":",theme:{colors:[yn],spacing:[$a,ar],blur:["none","",rr,bt],brightness:E(),borderColor:[t],borderRadius:["none","","full",rr,bt],borderSpacing:S(),borderWidth:U(),contrast:E(),grayscale:B(),hueRotate:E(),invert:B(),gap:S(),gradientColorStops:[t],gradientColorStopPositions:[sy,ar],inset:_(),margin:_(),opacity:E(),padding:S(),saturate:E(),scale:E(),sepia:B(),skew:E(),space:S(),translate:S()},classGroups:{aspect:[{aspect:["auto","square","video",bt]}],container:["container"],columns:[{columns:[rr]}],"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:[...$(),bt]}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],overscroll:[{overscroll:R()}],"overscroll-x":[{"overscroll-x":R()}],"overscroll-y":[{"overscroll-y":R()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[f]}],"inset-x":[{"inset-x":[f]}],"inset-y":[{"inset-y":[f]}],start:[{start:[f]}],end:[{end:[f]}],top:[{top:[f]}],right:[{right:[f]}],bottom:[{bottom:[f]}],left:[{left:[f]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",jn,bt]}],basis:[{basis:_()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",bt]}],grow:[{grow:B()}],shrink:[{shrink:B()}],order:[{order:["first","last","none",jn,bt]}],"grid-cols":[{"grid-cols":[yn]}],"col-start-end":[{col:["auto",{span:["full",jn,bt]},bt]}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":[yn]}],"row-start-end":[{row:["auto",{span:[jn,bt]},bt]}],"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",bt]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",bt]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...k()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...k(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...k(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[b]}],mx:[{mx:[b]}],my:[{my:[b]}],ms:[{ms:[b]}],me:[{me:[b]}],mt:[{mt:[b]}],mr:[{mr:[b]}],mb:[{mb:[b]}],ml:[{ml:[b]}],"space-x":[{"space-x":[L]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[L]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",bt,s]}],"min-w":[{"min-w":[bt,s,"min","max","fit"]}],"max-w":[{"max-w":[bt,s,"none","full","min","max","fit","prose",{screen:[rr]},rr]}],h:[{h:[bt,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[bt,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[bt,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[bt,s,"auto","min","max","fit"]}],"font-size":[{text:["base",rr,ar]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",wl]}],"font-family":[{font:[yn]}],"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",bt]}],"line-clamp":[{"line-clamp":["none",Jr,wl]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",$a,bt]}],"list-image":[{"list-image":["none",bt]}],"list-style-type":[{list:["none","disc","decimal",bt]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[j]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...P(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",$a,ar]}],"underline-offset":[{"underline-offset":["auto",$a,bt]}],"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:S()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",bt]}],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",bt]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[j]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...$(),ny]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",ry]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},ly]}],"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":[j]}],"border-style":[{border:[...P(),"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":[j]}],"divide-style":[{divide:P()}],"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:["",...P()]}],"outline-offset":[{"outline-offset":[$a,bt]}],"outline-w":[{outline:[$a,ar]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:U()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[$a,ar]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",rr,oy]}],"shadow-color":[{shadow:[yn]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...T(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":T()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",rr,bt]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[p]}],saturate:[{saturate:[w]}],sepia:[{sepia:[C]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[j]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[C]}],"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",bt]}],duration:[{duration:E()}],ease:[{ease:["linear","in","out","in-out",bt]}],delay:[{delay:E()}],animate:[{animate:["none","spin","ping","pulse","bounce",bt]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[v]}],"scale-x":[{"scale-x":[v]}],"scale-y":[{"scale-y":[v]}],rotate:[{rotate:[jn,bt]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[A]}],"skew-y":[{"skew-y":[A]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",bt]}],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",bt]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":S()}],"scroll-mx":[{"scroll-mx":S()}],"scroll-my":[{"scroll-my":S()}],"scroll-ms":[{"scroll-ms":S()}],"scroll-me":[{"scroll-me":S()}],"scroll-mt":[{"scroll-mt":S()}],"scroll-mr":[{"scroll-mr":S()}],"scroll-mb":[{"scroll-mb":S()}],"scroll-ml":[{"scroll-ml":S()}],"scroll-p":[{"scroll-p":S()}],"scroll-px":[{"scroll-px":S()}],"scroll-py":[{"scroll-py":S()}],"scroll-ps":[{"scroll-ps":S()}],"scroll-pe":[{"scroll-pe":S()}],"scroll-pt":[{"scroll-pt":S()}],"scroll-pr":[{"scroll-pr":S()}],"scroll-pb":[{"scroll-pb":S()}],"scroll-pl":[{"scroll-pl":S()}],"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",bt]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[$a,ar,wl]}],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"]}}},xy=Kj(uy);function Me(...t){return xy(Kx(t))}const Ln=Xo("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"}}),M=h.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?Ox:"button";return e.jsx(l,{"data-slot":"button",className:Me(Ln({variant:s,size:a,className:t})),ref:i,...n})});M.displayName="Button";function q({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:Me("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function oe({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:Me("@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 de({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:Me("leading-none",t),...s})}function ye({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:Me("text-muted-foreground",t),...s})}function ee({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:Me("px-6 [&:last-child]:pb-6",t),...s})}const al="/assets/Re_Logo-By51taPS.png",Om="/assets/landing_page_image-ClTD-4qZ.jpg";function hy(){var p,x;const{login:t,isLoading:s,error:a}=cs(),[r,n]=h.useState(!1),[i,l]=h.useState(null),[o,c]=h.useState(!1);h.useEffect(()=>{const u=new Image;u.src=Om,u.onload=()=>c(!0),u.complete&&c(!0)},[]);const d=async()=>{const u=sessionStorage.getItem("__force_reauth_after_logout__");localStorage.clear(),sessionStorage.clear(),u&&sessionStorage.setItem("__force_reauth_after_logout__",u);try{sessionStorage.setItem("auth_provider","okta"),await t()}catch(g){console.error("OKTA LOGIN ERROR",g)}},m=()=>{l(null),localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("auth_provider","tanflow"),n(!0);try{Fj()}catch(u){const g=u instanceof Error?u.message:"Dealer login failed. Check console for details.";console.error("TANFLOW LOGIN ERROR",u),l(g),n(!1)}};return a&&console.error("Auth Error:",{message:a.message,error:a}),e.jsxs("div",{className:"min-h-screen flex items-center justify-center p-4 relative overflow-hidden",style:{backgroundImage:o?`url(${Om})`:"none",backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},children:[!o&&e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 to-slate-800"}),e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-[2px]","aria-hidden":!0}),e.jsx("div",{className:"absolute inset-0 bg-black/30","aria-hidden":!0}),e.jsxs(q,{className:"w-full max-w-md shadow-2xl relative z-10 bg-gray-900/95 border border-gray-700 text-white",children:[e.jsx(oe,{className:"space-y-1 text-center pb-6 pt-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:al,alt:"Royal Enfield",className:"h-9 w-auto max-w-[180px] object-contain mb-2"}),e.jsx("p",{className:"text-sm text-gray-400",children:"Approval Portal"})]})}),e.jsxs(ee,{className:"space-y-5 pb-8 px-8",children:[a&&e.jsxs("div",{className:"bg-red-900/40 border border-red-700 text-red-200 px-4 py-3 rounded-lg text-sm",children:[e.jsx("p",{className:"font-medium",children:"Authentication Error"}),e.jsx("p",{children:a.message}),(((p=a.message)==null?void 0:p.includes("401"))||((x=a.message)==null?void 0:x.toLowerCase().includes("unauthorized")))&&e.jsxs("p",{className:"mt-2 text-xs text-red-300",children:["If you see 401 from Okta: your Okta admin must add this site’s URL to ",e.jsx("strong",{children:"Trusted Origins"})," and ensure the RE Employee application is active. Use ",e.jsx("strong",{children:"Dealer Login"})," if you are a dealer."]})]}),i&&e.jsxs("div",{className:"bg-amber-900/40 border border-amber-700 text-amber-200 px-4 py-3 rounded-lg text-sm",children:[e.jsx("p",{className:"font-medium",children:"Dealer Login (Tanflow)"}),e.jsx("p",{children:i})]}),e.jsx(M,{onClick:d,disabled:s||r,className:"w-full h-12 bg-re-red hover:bg-re-red/90 text-white font-semibold text-base border-0",size:"lg",children:s?e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-white border-t-transparent"}):e.jsxs(e.Fragment,{children:[e.jsx(fs,{className:"mr-2 h-5 w-5"}),"RE Employee Login"]})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex-1 h-px bg-gray-600"}),e.jsx("span",{className:"text-sm text-gray-400 uppercase tracking-wide",children:"Or"}),e.jsx("span",{className:"flex-1 h-px bg-gray-600"})]}),e.jsx(M,{onClick:m,disabled:s||r,className:"w-full h-12 bg-blue-600 hover:bg-blue-700 text-white font-semibold text-base border-0",size:"lg",children:r?e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-white border-t-transparent"}):e.jsxs(e.Fragment,{children:[e.jsx(ps,{className:"mr-2 h-5 w-5"}),"Dealer Login"]})}),e.jsxs("div",{className:"text-center pt-2",children:[e.jsx("p",{className:"text-sm text-gray-400",children:"Secure Single Sign On"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Choose your authentication provider."})]})]})]})]})}function Ih(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=cs(),[n,i]=h.useState("exchanging");h.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:al,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(us,{className:"w-16 h-16 text-green-500"})}),e.jsx(us,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Qe,{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 $0=Object.defineProperty;var U0=(t,s,a)=>s in t?$0(t,s,{enumerable:!0,config ${g}px !important; top: ${p}px !important; } - `),()=>{b.contains(f)&&b.removeChild(f)}},[s]),e.jsx(YC,{isPresent:s,childRef:i,sizeRef:l,children:h.cloneElement(t,{ref:c})})}const QC=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=cc(XC),m=h.useId();let p=!0,x=h.useMemo(()=>(p=!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&&p&&(x={...x}),h.useMemo(()=>{d.forEach((u,g)=>d.set(g,!1))},[a]),h.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(KC,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(il.Provider,{value:x,children:t})};function XC(){return new Map}function lg(t=!0){const s=h.useContext(il);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=h.useId();h.useEffect(()=>{if(t)return n(i)},[t]);const l=h.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const oi=t=>t.key||"";function ju(t){const s=[];return h.Children.forEach(t,a=>{h.isValidElement(a)&&s.push(a)}),s}const ll=({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]=lg(l),p=h.useMemo(()=>ju(t),[t]),x=l&&!d?[]:p.map(oi),u=h.useRef(!0),g=h.useRef(p),f=cc(()=>new Map),[b,j]=h.useState(p),[y,w]=h.useState(p);gp(()=>{u.current=!1,g.current=p;for(let A=0;A{const L=oi(A),D=l&&!d?!1:p===y||x.includes(L),R=()=>{if(f.has(L))f.set(L,!0);else return;let N=!0;f.forEach(_=>{_||(N=!1)}),N&&(C==null||C(),w(g.current),l&&(m==null||m()),r&&r())};return e.jsx(QC,{isPresent:D,initial:!u.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:D?void 0:R,anchorX:o,children:A},L)})})},og=h.createContext({strict:!1}),yu={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"]},sn={};for(const t in yu)sn[t]={isEnabled:s=>yu[t].some(a=>!!s[a])};function JC(t){for(const s in t)sn[s]={...sn[s],...t[s]}}const ZC=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 Oi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||ZC.has(t)}let cg=t=>!Oi(t);function qC(t){typeof t=="function"&&(cg=s=>s.startsWith("on")?!Oi(s):t(s))}try{qC(require("@emotion/is-prop-valid").default)}catch{}function e2(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(cg(n)||a===!0&&Oi(n)||!s&&!Oi(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const ol=h.createContext({});function cl(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Bn(t){return typeof t=="string"||Array.isArray(t)}const Pc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Ec=["initial",...Pc];function dl(t){return cl(t.animate)||Ec.some(s=>Bn(t[s]))}function dg(t){return!!(dl(t)||t.variants)}function t2(t,s){if(dl(t)){const{initial:a,animate:r}=t;return{initial:a===!1||Bn(a)?a:void 0,animate:Bn(r)?r:void 0}}return t.inherit!==!1?s:{}}function s2(t){const{initial:s,animate:a}=t2(t,h.useContext(ol));return h.useMemo(()=>({initial:s,animate:a}),[vu(s),vu(a)])}function vu(t){return Array.isArray(t)?t.join(" "):t}const Vn={};function a2(t){for(const s in t)Vn[s]=t[s],bc(s)&&(Vn[s].isCSSVariable=!0)}function mg(t,{layout:s,layoutId:a}){return hn.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!Vn[t]||t==="opacity")}const r2={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},n2=xn.length;function i2(t,s,a){let r="",n=!0;for(let i=0;i({style:{},transform:{},transformOrigin:{},vars:{}});function ug(t,s,a){for(const r in s)!$s(s[r])&&!mg(r,a)&&(t[r]=s[r])}function l2({transformTemplate:t},s){return h.useMemo(()=>{const a=Mc();return _c(a,s,t),Object.assign({},a.vars,a.style)},[s])}function o2(t,s){const a=t.style||{},r={};return ug(r,a,t),Object.assign(r,l2(t,s)),r}function c2(t,s){const a={},r=o2(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 d2={offset:"stroke-dashoffset",array:"stroke-dasharray"},m2={offset:"strokeDashoffset",array:"strokeDasharray"};function u2(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?d2:m2;t[i.offset]=nt.transform(-r);const l=nt.transform(s),o=nt.transform(a);t[i.array]=`${l} ${o}`}function xg(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(_c(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:p,style:x}=t;p.transform&&(x.transform=p.transform,delete p.transform),(x.transform||p.transformOrigin)&&(x.transformOrigin=p.transformOrigin??"50% 50%",delete p.transformOrigin),x.transform&&(x.transformBox=(m==null?void 0:m.transformBox)??"fill-box",delete p.transformBox),s!==void 0&&(p.x=s),a!==void 0&&(p.y=a),r!==void 0&&(p.scale=r),n!==void 0&&u2(p,n,i,l,!1)}const hg=()=>({...Mc(),attrs:{}}),pg=t=>typeof t=="string"&&t.toLowerCase()==="svg";function x2(t,s,a,r){const n=h.useMemo(()=>{const i=hg();return xg(i,s,pg(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};ug(i,t.style,t),n.style={...i,...n.style}}return n}const h2=["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 Lc(t){return typeof t!="string"||t.includes("-")?!1:!!(h2.indexOf(t)>-1||/[A-Z]/u.test(t))}function p2(t,s,a,{latestValues:r},n,i=!1){const o=(Lc(t)?x2:c2)(s,r,n,t),c=e2(s,typeof t=="string",i),d=t!==h.Fragment?{...c,...o,ref:a}:{},{children:m}=s,p=h.useMemo(()=>$s(m)?m.get():m,[m]);return h.createElement(t,{...d,children:p})}function Nu(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function Oc(t,s,a,r){if(typeof s=="function"){const[n,i]=Nu(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]=Nu(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Ni(t){return $s(t)?t.get():t}function g2({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:f2(a,r,n,t),renderState:s()}}function f2(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=Ni(i[x]);let{initial:l,animate:o}=t;const c=dl(t),d=dg(t);s&&d&&!c&&t.inherit!==!1&&(l===void 0&&(l=s.initial),o===void 0&&(o=s.animate));let m=a?a.initial===!1:!1;m=m||l===!1;const p=m?o:l;if(p&&typeof p!="boolean"&&!cl(p)){const x=Array.isArray(p)?p:[p];for(let u=0;u(s,a)=>{const r=h.useContext(ol),n=h.useContext(il),i=()=>g2(t,s,r,n);return a?i():cc(i)};function $c(t,s,a){var i;const{style:r}=t,n={};for(const l in r)($s(r[l])||s.style&&$s(s.style[l])||mg(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const b2=gg({scrapeMotionValuesFromProps:$c,createRenderState:Mc});function fg(t,s,a){const r=$c(t,s,a);for(const n in t)if($s(t[n])||$s(s[n])){const i=xn.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const j2=gg({scrapeMotionValuesFromProps:fg,createRenderState:hg}),y2=Symbol.for("motionComponentSymbol");function Hr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function v2(t,s,a){return h.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):Hr(a)&&(a.current=r))},[s])}const Uc=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),N2="framerAppearId",bg="data-"+Uc(N2),jg=h.createContext({});function w2(t,s,a,r,n){var f,b;const{visualElement:i}=h.useContext(ol),l=h.useContext(og),o=h.useContext(il),c=h.useContext(Ic).reducedMotion,d=h.useRef(null);r=r||l.renderer,!d.current&&r&&(d.current=r(t,{visualState:s,parent:i,props:a,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:c}));const m=d.current,p=h.useContext(jg);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&C2(d.current,a,n,p);const x=h.useRef(!1);h.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const u=a[bg],g=h.useRef(!!u&&!((f=window.MotionHandoffIsComplete)!=null&&f.call(window,u))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,u)));return gp(()=>{m&&(x.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),h.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var j;(j=window.MotionHandoffMarkAsComplete)==null||j.call(window,u)}),g.current=!1),m.enteringChildren=void 0)}),m}function C2(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:yg(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&Hr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function yg(t){if(t)return t.options.allowProjection!==!1?t.projection:yg(t.parent)}function Ml(t,{forwardMotionProps:s=!1}={},a,r){a&&JC(a);const n=Lc(t)?j2:b2;function i(o,c){let d;const m={...h.useContext(Ic),...o,layoutId:S2(o)},{isStatic:p}=m,x=s2(o),u=n(o,p);if(!p&&dc){A2();const g=T2(m);d=g.MeasureLayout,x.visualElement=w2(t,u,m,r,g.ProjectionNode)}return e.jsxs(ol.Provider,{value:x,children:[d&&x.visualElement?e.jsx(d,{visualElement:x.visualElement,...m}):null,p2(t,o,v2(u,x.visualElement,c),u,p,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=h.forwardRef(i);return l[y2]=t,l}function S2({layoutId:t}){const s=h.useContext(oc).id;return s&&t!==void 0?s+"-"+t:t}function A2(t,s){h.useContext(og).strict}function T2(t){const{drag:s,layout:a}=sn;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 k2(t,s){if(typeof Proxy>"u")return Ml;const a=new Map,r=(i,l)=>Ml(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,Ml(l,void 0,t,s)),a.get(l))})}function vg({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function R2({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function D2(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 Ll(t){return t===void 0||t===1}function So({scale:t,scaleX:s,scaleY:a}){return!Ll(t)||!Ll(s)||!Ll(a)}function Cr(t){return So(t)||Ng(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Ng(t){return wu(t.x)||wu(t.y)}function wu(t){return t&&t!=="0%"}function $i(t,s,a){const r=t-a,n=s*r;return a+n}function Cu(t,s,a,r,n){return n!==void 0&&(t=$i(t,n,r)),$i(t,a,r)+s}function Ao(t,s=0,a=1,r,n){t.min=Cu(t.min,s,a,r,n),t.max=Cu(t.max,s,a,r,n)}function wg(t,{x:s,y:a}){Ao(t.x,s.translate,s.scale,s.originPoint),Ao(t.y,a.translate,a.scale,a.originPoint)}const Su=.999999999999,Au=1.0000000000001;function F2(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,l;for(let o=0;oSu&&(s.x=1),s.ySu&&(s.y=1)}function Wr(t,s){t.min=t.min+s,t.max=t.max+s}function Tu(t,s,a,r,n=.5){const i=as(t.min,t.max,n);Ao(t,s,a,i,r)}function Gr(t,s){Tu(t.x,s.x,s.scaleX,s.scale,s.originX),Tu(t.y,s.y,s.scaleY,s.scale,s.originY)}function Cg(t,s){return vg(D2(t.getBoundingClientRect(),s))}function I2(t,s,a){const r=Cg(t,a),{scroll:n}=s;return n&&(Wr(r.x,n.offset.x),Wr(r.y,n.offset.y)),r}const ku=()=>({translate:0,scale:1,origin:0,originPoint:0}),Yr=()=>({x:ku(),y:ku()}),Ru=()=>({min:0,max:0}),ds=()=>({x:Ru(),y:Ru()}),To={current:null},Sg={current:!1};function P2(){if(Sg.current=!0,!!dc)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>To.current=t.matches;t.addEventListener("change",s),s()}else To.current=!1}const E2=new WeakMap;function _2(t,s,a){for(const r in s){const n=s[r],i=a[r];if($s(n))t.addValue(r,n);else if($s(i))t.addValue(r,tn(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,tn(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Du=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class M2{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=Tc,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=Zs.now();this.renderScheduledAtthis.bindToMotionValue(n,r)),Sg.current||P2(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:To.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),ur(this.notifyUpdate),ur(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=hn.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&Zt.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 sn){const a=sn[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):ds()}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=tn(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"&&(fp(r)||jp(r))?r=parseFloat(r):!HC(r)&&xr.test(a)&&(r=eg(s,a)),this.setBaseTarget(s,$s(r)?r.get():r)),$s(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=Oc(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&&!$s(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 pc),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){Dc.render(this.render)}}class Ag extends M2{constructor(){super(...arguments),this.KeyframeResolver=IC}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;$s(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function Tg(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 L2(t){return window.getComputedStyle(t)}class O2 extends Ag{constructor(){super(...arguments),this.type="html",this.renderInstance=Tg}readValueFromInstance(s,a){var r;if(hn.has(a))return(r=this.projection)!=null&&r.isProjecting?bo(a):J1(s,a);{const n=L2(s),i=(bc(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return Cg(s,a)}build(s,a,r){_c(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return $c(s,a,r)}}const kg=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 $2(t,s,a,r){Tg(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(kg.has(n)?n:Uc(n),s.attrs[n])}class U2 extends Ag{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ds}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(hn.has(a)){const r=qp(a);return r&&r.default||0}return a=kg.has(a)?a:Uc(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return fg(s,a,r)}build(s,a,r){xg(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){$2(s,a,r,n)}mount(s){this.isSVGTag=pg(s.tagName),super.mount(s)}}const B2=(t,s)=>Lc(t)?new U2(s):new O2(s,{allowProjection:t!==h.Fragment});function qr(t,s,a){const r=t.getProps();return Oc(r,s,a!==void 0?a:r.custom,t)}const ko=t=>Array.isArray(t);function V2(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,tn(a))}function z2(t){return ko(t)?t[t.length-1]||0:t}function H2(t,s){const a=qr(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=z2(i[l]);V2(t,l,o)}}function W2(t){return!!($s(t)&&t.add)}function Ro(t,s){const a=t.getValue("willChange");if(W2(a))return a.add(s);if(!a&&Ga.WillChange){const r=new Ga.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function Rg(t){return t.props[bg]}const G2=t=>t!==null;function Y2(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(G2),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const K2={type:"spring",stiffness:500,damping:25,restSpeed:10},Q2=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),X2={type:"keyframes",duration:.8},J2={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Z2=(t,{keyframes:s})=>s.length>2?X2:hn.has(t)?t.startsWith("scale")?Q2(s[1]):K2:J2;function q2({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 Bc=(t,s,a,r={},n,i)=>l=>{const o=kc(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-Da(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};q2(o)||Object.assign(m,Z2(t,m)),m.duration&&(m.duration=Da(m.duration)),m.repeatDelay&&(m.repeatDelay=Da(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let p=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(wo(m),m.delay===0&&(p=!0)),(Ga.instantAnimations||Ga.skipAnimations)&&(p=!0,wo(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,p&&!i&&s.get()!==void 0){const x=Y2(m.keyframes,o);if(x!==void 0){Zt.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new Ac(m):new yC(m)};function eS({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Dg(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in o){const p=t.getValue(m,t.latestValues[m]??null),x=o[m];if(x===void 0||d&&eS(d,m))continue;const u={delay:a,...kc(i||{},m)},g=p.get();if(g!==void 0&&!p.isAnimating&&!Array.isArray(x)&&x===g&&!u.velocity)continue;let f=!1;if(window.MotionHandoffAnimation){const j=Rg(t);if(j){const y=window.MotionHandoffAnimation(j,m,Zt);y!==null&&(u.startTime=y,f=!0)}}Ro(t,m),p.start(Bc(m,p,x,t.shouldReduceMotion&&Xp.has(m)?{type:!1}:u,t,f));const b=p.animation;b&&c.push(b)}return l&&Promise.all(c).then(()=>{Zt.update(()=>{l&&H2(t,l)})}),c}function Fg(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 Do(t,s,a={}){var c;const r=qr(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(Dg(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:p,staggerDirection:x}=n;return tS(t,s,d,m,p,x,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[d,m]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function tS(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(Do(c,s,{...l,delay:a+(typeof r=="function"?0:r)+Fg(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function sS(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>Do(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=Do(t,s,a);else{const n=typeof s=="function"?qr(t,s,a.custom):s;r=Promise.all(Dg(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function Ig(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})=>sS(t,a,r)))}function lS(t){let s=iS(t),a=Fu(),r=!0;const n=c=>(d,m)=>{var x;const p=qr(t,m,c==="exit"?(x=t.presenceContext)==null?void 0:x.custom:void 0);if(p){const{transition:u,transitionEnd:g,...f}=p;d={...d,...f,...g}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=Pg(t.parent)||{},p=[],x=new Set;let u={},g=1/0;for(let b=0;bg&&v,R=!1;const N=Array.isArray(w)?w:[w];let _=N.reduce(n(j),{});C===!1&&(_={});const{prevResolvedValues:S={}}=y,U={...S,..._},F=T=>{D=!0,x.has(T)&&(R=!0,x.delete(T)),y.needsAnimating[T]=!0;const k=t.getValue(T);k&&(k.liveStyle=!1)};for(const T in U){const k=_[T],B=S[T];if(u.hasOwnProperty(T))continue;let I=!1;ko(k)&&ko(B)?I=!Ig(k,B):I=k!==B,I?k!=null?F(T):x.add(T):k!==void 0&&x.has(T)?F(T):y.protectedKeys[T]=!0}y.prevProp=w,y.prevResolvedValues=_,y.isActive&&(u={...u,..._}),r&&t.blockInitialAnimation&&(D=!1);const $=A&&L;D&&(!$||R)&&p.push(...N.map(T=>{const k={type:j};if(typeof T=="string"&&r&&!$&&t.manuallyAnimateOnMount&&t.parent){const{parent:B}=t,I=qr(B,T);if(B.enteringChildren&&I){const{delayChildren:E}=I.transition||{};k.delay=Fg(B.enteringChildren,t,E)}}return{animation:T,options:k}}))}if(x.size){const b={};if(typeof d.initial!="boolean"){const j=qr(t,Array.isArray(d.initial)?d.initial[0]:d.initial);j&&j.transition&&(b.transition=j.transition)}x.forEach(j=>{const y=t.getBaseTarget(j),w=t.getValue(j);w&&(w.liveStyle=!0),b[j]=y??null}),p.push({animation:b})}let f=!!p.length;return r&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(f=!1),r=!1,f?s(p):Promise.resolve()}function o(c,d){var p;if(a[c].isActive===d)return Promise.resolve();(p=t.variantChildren)==null||p.forEach(x=>{var 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=Fu()}}}function oS(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!Ig(s,t):!1}function yr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Fu(){return{animate:yr(!0),whileInView:yr(),whileHover:yr(),whileTap:yr(),whileDrag:yr(),whileFocus:yr(),exit:yr()}}class hr{constructor(s){this.isMounted=!1,this.node=s}update(){}}class cS extends hr{constructor(s){super(s),s.animationState||(s.animationState=lS(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();cl(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 dS=0;class mS extends hr{constructor(){super(...arguments),this.id=dS++}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 uS={animation:{Feature:cS},exit:{Feature:mS}};function zn(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function ei(t){return{point:{x:t.pageX,y:t.pageY}}}const xS=t=>s=>Fc(s)&&t(s,ei(s));function Pn(t,s,a,r){return zn(t,s,xS(a),r)}const Eg=1e-4,hS=1-Eg,pS=1+Eg,_g=.01,gS=0-_g,fS=0+_g;function zs(t){return t.max-t.min}function bS(t,s,a){return Math.abs(t-s)<=a}function Iu(t,s,a,r=.5){t.origin=r,t.originPoint=as(s.min,s.max,t.origin),t.scale=zs(a)/zs(s),t.translate=as(a.min,a.max,t.origin)-t.originPoint,(t.scale>=hS&&t.scale<=pS||isNaN(t.scale))&&(t.scale=1),(t.translate>=gS&&t.translate<=fS||isNaN(t.translate))&&(t.translate=0)}function En(t,s,a,r){Iu(t.x,s.x,a.x,r?r.originX:void 0),Iu(t.y,s.y,a.y,r?r.originY:void 0)}function Pu(t,s,a){t.min=a.min+s.min,t.max=t.min+zs(s)}function jS(t,s,a){Pu(t.x,s.x,a.x),Pu(t.y,s.y,a.y)}function Eu(t,s,a){t.min=s.min-a.min,t.max=t.min+zs(s)}function _n(t,s,a){Eu(t.x,s.x,a.x),Eu(t.y,s.y,a.y)}function xa(t){return[t("x"),t("y")]}const Mg=({current:t})=>t?t.ownerDocument.defaultView:null,_u=(t,s)=>Math.abs(t-s);function yS(t,s){const a=_u(t.x,s.x),r=_u(t.y,s.y);return Math.sqrt(a**2+r**2)}class Lg{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=$l(this.lastMoveEventInfo,this.history),u=this.startEvent!==null,g=yS(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!u&&!g)return;const{point:f}=x,{timestamp:b}=Ps;this.history.push({...f,timestamp:b});const{onStart:j,onMove:y}=this.handlers;u||(j&&j(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),y&&y(this.lastMoveEvent,x)},this.handlePointerMove=(x,u)=>{this.lastMoveEvent=x,this.lastMoveEventInfo=Ol(u,this.transformPagePoint),Zt.update(this.updatePoint,!0)},this.handlePointerUp=(x,u)=>{this.end();const{onEnd:g,onSessionEnd:f,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const j=$l(x.type==="pointercancel"?this.lastMoveEventInfo:Ol(u,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,j),f&&f(x,j)},!Fc(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=ei(s),c=Ol(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=Ps;this.history=[{...d,timestamp:m}];const{onSessionStart:p}=a;p&&p(s,$l(c,this.history)),this.removeListeners=Jn(Pn(this.contextWindow,"pointermove",this.handlePointerMove),Pn(this.contextWindow,"pointerup",this.handlePointerUp),Pn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),ur(this.updatePoint)}}function Ol(t,s){return s?{point:s(t.point)}:t}function Mu(t,s){return{x:t.x-s.x,y:t.y-s.y}}function $l({point:t},s){return{point:t,delta:Mu(t,Og(s)),offset:Mu(t,vS(s)),velocity:NS(s,.1)}}function vS(t){return t[0]}function Og(t){return t[t.length-1]}function NS(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=Og(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>Da(s)));)a--;if(!r)return{x:0,y:0};const i=ha(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 wS(t,{min:s,max:a},r){return s!==void 0&&ta&&(t=r?as(a,t,r.max):Math.min(t,a)),t}function Lu(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 CS(t,{top:s,left:a,bottom:r,right:n}){return{x:Lu(t.x,a,n),y:Lu(t.y,s,r)}}function Ou(t,s){let a=s.min-t.min,r=s.max-t.max;return s.max-s.minr?a=On(s.min,s.max-r,t.min):r>n&&(a=On(t.min,t.max-n,s.min)),Wa(0,1,a)}function TS(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 Fo=.35;function kS(t=Fo){return t===!1?t=0:t===!0&&(t=Fo),{x:$u(t,"left","right"),y:$u(t,"top","bottom")}}function $u(t,s,a){return{min:Uu(t,s),max:Uu(t,a)}}function Uu(t,s){return typeof t=="number"?t:t[s]||0}const RS=new WeakMap;class DS{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=ds(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:a=!1,distanceThreshold:r}={}){const{presenceContext:n}=this.visualElement;if(n&&n.isPresent===!1)return;const i=p=>{const{dragSnapToOrigin:x}=this.getProps();x?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(ei(p).point)},l=(p,x)=>{const{drag:u,dragPropagation:g,onDragStart:f}=this.getProps();if(u&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=MC(u),!this.openDragLock))return;this.latestPointerEvent=p,this.latestPanInfo=x,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),xa(j=>{let y=this.getAxisMotionValue(j).get()||0;if(Fa.test(y)){const{projection:w}=this.visualElement;if(w&&w.layout){const v=w.layout.layoutBox[j];v&&(y=zs(v)*(parseFloat(y)/100))}}this.originPoint[j]=y}),f&&Zt.postRender(()=>f(p,x)),Ro(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},o=(p,x)=>{this.latestPointerEvent=p,this.latestPanInfo=x;const{dragPropagation:u,dragDirectionLock:g,onDirectionLock:f,onDrag:b}=this.getProps();if(!u&&!this.openDragLock)return;const{offset:j}=x;if(g&&this.currentDirection===null){this.currentDirection=FS(j),this.currentDirection!==null&&f&&f(this.currentDirection);return}this.updateAxis("x",x.point,j),this.updateAxis("y",x.point,j),this.visualElement.render(),b&&b(p,x)},c=(p,x)=>{this.latestPointerEvent=p,this.latestPanInfo=x,this.stop(p,x),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>xa(p=>{var x;return this.getAnimationState(p)==="paused"&&((x=this.getAxisMotionValue(p).animation)==null?void 0:x.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new Lg(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:Mg(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&&Zt.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||!ci(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=wS(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&&Hr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=CS(r.layoutBox,s):this.constraints=!1,this.elastic=kS(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&xa(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=TS(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!Hr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=I2(r,n.root,this.visualElement.getTransformPagePoint());let l=SS(n.layout.layoutBox,i);if(a){const o=a(R2(l));this.hasMutatedConstraints=!!o,o&&(l=vg(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=xa(m=>{if(!ci(m,a,this.currentDirection))return;let p=c&&c[m]||{};l&&(p={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,...p};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return Ro(this.visualElement,s),r.start(Bc(s,r,0,a,this.visualElement,!1))}stopAnimation(){xa(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){xa(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){xa(a=>{const{drag:r}=this.getProps();if(!ci(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]-as(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!Hr(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};xa(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=AS({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(),xa(l=>{if(!ci(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(as(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;RS.set(this.visualElement,this);const s=this.visualElement.current,a=Pn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();Hr(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()),Zt.read(r);const l=zn(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(xa(m=>{const p=this.getAxisMotionValue(m);p&&(this.originPoint[m]+=c[m].translate,p.set(p.get()+c[m].translate))}),this.visualElement.render())});return()=>{l(),a(),i(),o&&o()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:l=Fo,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function ci(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function FS(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class IS extends hr{constructor(s){super(s),this.removeGroupControls=pa,this.removeListeners=pa,this.controls=new DS(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||pa}unmount(){this.removeGroupControls(),this.removeListeners()}}const Bu=t=>(s,a)=>{t&&Zt.postRender(()=>t(s,a))};class PS extends hr{constructor(){super(...arguments),this.removePointerDownListener=pa}onPointerDown(s){this.session=new Lg(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Mg(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Bu(s),onStart:Bu(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&Zt.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=Pn(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 wi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Vu(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const vn={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(nt.test(t))t=parseFloat(t);else return t;const a=Vu(t,s.target.x),r=Vu(t,s.target.y);return`${a}% ${r}%`}},ES={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=xr.parse(t);if(n.length>5)return r;const i=xr.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=as(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 Ul=!1;class _S extends h.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;a2(MS),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),Ul&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),wi.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,Ul=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||Zt.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Dc.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;Ul=!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 $g(t){const[s,a]=lg(),r=h.useContext(oc);return e.jsx(_S,{...t,layoutGroup:r,switchLayoutGroup:h.useContext(jg),isPresent:s,safeToRemove:a})}const MS={borderRadius:{...vn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:vn,borderTopRightRadius:vn,borderBottomLeftRadius:vn,borderBottomRightRadius:vn,boxShadow:ES};function LS(t,s,a){const r=$s(t)?t:tn(t);return r.start(Bc("",r,s,a)),r.animation}const OS=(t,s)=>t.depth-s.depth;class $S{constructor(){this.children=[],this.isDirty=!1}add(s){mc(this.children,s),this.isDirty=!0}remove(s){uc(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(OS),this.isDirty=!1,this.children.forEach(s)}}function US(t,s){const a=Zs.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(ur(r),t(i-s))};return Zt.setup(r,!0),()=>ur(r)}const Ug=["TopLeft","TopRight","BottomLeft","BottomRight"],BS=Ug.length,zu=t=>typeof t=="string"?parseFloat(t):t,Hu=t=>typeof t=="number"||nt.test(t);function VS(t,s,a,r,n,i){n?(t.opacity=as(0,a.opacity??1,zS(r)),t.opacityExit=as(s.opacity??1,0,HS(r))):i&&(t.opacity=as(s.opacity??1,a.opacity??1,r));for(let l=0;lrs?1:a(On(t,s,r))}function Gu(t,s){t.min=s.min,t.max=s.max}function ua(t,s){Gu(t.x,s.x),Gu(t.y,s.y)}function Yu(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function Ku(t,s,a,r,n){return t-=s,t=$i(t,1/a,r),n!==void 0&&(t=$i(t,1/n,r)),t}function WS(t,s=0,a=1,r=.5,n,i=t,l=t){if(Fa.test(s)&&(s=parseFloat(s),s=as(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=as(i.min,i.max,r);t===i&&(o-=s),t.min=Ku(t.min,s,a,o,n),t.max=Ku(t.max,s,a,o,n)}function Qu(t,s,[a,r,n],i,l){WS(t,s[a],s[r],s[n],s.scale,i,l)}const GS=["x","scaleX","originX"],YS=["y","scaleY","originY"];function Xu(t,s,a,r){Qu(t.x,s,GS,a?a.x:void 0,r?r.x:void 0),Qu(t.y,s,YS,a?a.y:void 0,r?r.y:void 0)}function Ju(t){return t.translate===0&&t.scale===1}function Vg(t){return Ju(t.x)&&Ju(t.y)}function Zu(t,s){return t.min===s.min&&t.max===s.max}function KS(t,s){return Zu(t.x,s.x)&&Zu(t.y,s.y)}function qu(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function zg(t,s){return qu(t.x,s.x)&&qu(t.y,s.y)}function ex(t){return zs(t.x)/zs(t.y)}function tx(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class QS{constructor(){this.members=[]}add(s){mc(this.members,s),s.scheduleRender()}remove(s){if(uc(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 XS(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,l=(a==null?void 0:a.z)||0;if((n||i||l)&&(r=`translate3d(${n}px, ${i}px, ${l}px) `),(s.x!==1||s.y!==1)&&(r+=`scale(${1/s.x}, ${1/s.y}) `),a){const{transformPerspective:d,rotate:m,rotateX:p,rotateY:x,skewX:u,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),p&&(r+=`rotateX(${p}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 Bl=["","X","Y","Z"],JS=1e3;let ZS=0;function Vl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Hg(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=Rg(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",Zt,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Hg(r)}function Wg({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=ZS++,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(tA),this.nodes.forEach(nA),this.nodes.forEach(iA),this.nodes.forEach(sA)},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;Zt.read(()=>{p=window.innerWidth}),t(l,()=>{const u=window.innerWidth;u!==p&&(p=u,this.root.updateBlockedByResize=!0,m&&m(),m=US(x,250),wi.hasAnimatedSinceResize&&(wi.hasAnimatedSinceResize=!1,this.nodes.forEach(rx)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:p,hasRelativeLayoutChanged:x,layout:u})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||mA,{onLayoutAnimationStart:f,onLayoutAnimationComplete:b}=d.getProps(),j=!this.targetLayout||!zg(this.targetLayout,u),y=!p&&x;if(this.options.layoutRoot||this.resumeFrom||y||p&&(j||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...kc(g,"layout"),onPlay:f,onComplete:b};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(m,y)}else p||rx(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(),ur(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(lA),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&&Hg(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&&!zs(this.snapshot.measuredBox.x)&&!zs(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 C=v/1e3;nx(p.x,l.x,C),nx(p.y,l.y,C),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(_n(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),cA(this.relativeTarget,this.relativeTargetOrigin,x,C),w&&KS(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=ds()),ua(w,this.relativeTarget)),f&&(this.animationValues=m,VS(m,d,this.latestValues,C,y,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=C},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&&(ur(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Zt.update(()=>{wi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=tn(0)),this.currentAnimation=LS(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(JS),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&&Gg(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||ds();const p=zs(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+p;const x=zs(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+x}ua(o,c),Gr(o,m),En(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new QS),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&&Vl("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(sx),this.root.sharedNodes.clear()}}}function qS(t){t.updateLayout()}function eA(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"?xa(p=>{const x=l?s.measuredBox[p]:s.layoutBox[p],u=zs(x);x.min=r[p].min,x.max=x.min+u}):Gg(i,s.layoutBox,r)&&xa(p=>{const x=l?s.measuredBox[p]:s.layoutBox[p],u=zs(r[p]);x.max=x.min+u,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[p].max=t.relativeTarget[p].min+u)});const o=Yr();En(o,r,s.layoutBox);const c=Yr();l?En(c,t.applyTransform(n,!0),s.measuredBox):En(c,r,s.layoutBox);const d=!Vg(o);let m=!1;if(!t.resumeFrom){const p=t.getClosestProjectingParent();if(p&&!p.resumeFrom){const{snapshot:x,layout:u}=p;if(x&&u){const g=ds();_n(g,s.layoutBox,x.layoutBox);const f=ds();_n(f,r,u.layoutBox),zg(g,f)||(m=!0),p.options.layoutRoot&&(t.relativeTarget=f,t.relativeTargetOrigin=g,t.relativeParent=p)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function tA(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 sA(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function aA(t){t.clearSnapshot()}function sx(t){t.clearMeasurements()}function ax(t){t.isLayoutDirty=!1}function rA(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function rx(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function nA(t){t.resolveTargetDelta()}function iA(t){t.calcProjection()}function lA(t){t.resetSkewAndRotation()}function oA(t){t.removeLeadSnapshot()}function nx(t,s,a){t.translate=as(s.translate,0,a),t.scale=as(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function ix(t,s,a,r){t.min=as(s.min,a.min,r),t.max=as(s.max,a.max,r)}function cA(t,s,a,r){ix(t.x,s.x,a.x,r),ix(t.y,s.y,a.y,r)}function dA(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const mA={duration:.45,ease:[.4,0,.1,1]},lx=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),ox=lx("applewebkit/")&&!lx("chrome/")?Math.round:pa;function cx(t){t.min=ox(t.min),t.max=ox(t.max)}function uA(t){cx(t.x),cx(t.y)}function Gg(t,s,a){return t==="position"||t==="preserve-aspect"&&!bS(ex(s),ex(a),.2)}function xA(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const hA=Wg({attachResizeListener:(t,s)=>zn(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),zl={current:void 0},Yg=Wg({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!zl.current){const t=new hA({});t.mount(window),t.setOptions({layoutScroll:!0}),zl.current=t}return zl.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),pA={pan:{Feature:PS},drag:{Feature:IS,ProjectionNode:Yg,MeasureLayout:$g}};function dx(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&&Zt.postRender(()=>i(s,ei(s)))}class gA extends hr{mount(){const{current:s}=this.node;s&&(this.unmount=LC(s,(a,r)=>(dx(this.node,r,"Start"),n=>dx(this.node,n,"End"))))}unmount(){}}class fA extends hr{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=Jn(zn(this.node.current,"focus",()=>this.onFocus()),zn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function mx(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&&Zt.postRender(()=>i(s,ei(s)))}class bA extends hr{mount(){const{current:s}=this.node;s&&(this.unmount=BC(s,(a,r)=>(mx(this.node,r,"Start"),(n,{success:i})=>mx(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Io=new WeakMap,Hl=new WeakMap,jA=t=>{const s=Io.get(t.target);s&&s(t)},yA=t=>{t.forEach(jA)};function vA({root:t,...s}){const a=t||document;Hl.has(a)||Hl.set(a,{});const r=Hl.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(yA,{root:t,...s})),r[n]}function NA(t,s,a){const r=vA(s);return Io.set(t,a),r.observe(t),()=>{Io.delete(t),r.unobserve(t)}}const wA={some:0,all:1};class CA extends hr{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:wA[n]},o=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:p}=this.node.getProps(),x=d?m:p;x&&x(c)};return NA(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(SA(s,a))&&this.startObserver()}unmount(){}}function SA({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const AA={inView:{Feature:CA},tap:{Feature:bA},focus:{Feature:fA},hover:{Feature:gA}},TA={layout:{ProjectionNode:Yg,MeasureLayout:$g}},kA={...uS,...AA,...pA,...TA},Ht=k2(kA,B2),Nn=[{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:Pt,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:lh,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 RA({open:t,onClose:s,onSelectTemplate:a}){var d,m,p;const[r,n]=h.useState(null),[i,l]=h.useState(!1);h.useEffect(()=>{const x=at.getUserData();l((x==null?void 0:x.jobTitle)==="Dealer")},[]);const o=x=>{if(i)return;const u=Nn.find(g=>g.id===x);u!=null&&u.disabled||n(x)},c=()=>{r&&(a(r),s())};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{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(ut,{className:"sr-only",children:"Select a Template"}),e.jsx(_t,{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(Cs,{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(Ht.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(Yi,{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:Nn.map((x,u)=>{const g=x.icon,f=r===x.id,b=i||x.disabled;return e.jsx(Ht.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:u*.1},whileHover:b?{}:{scale:1.03},whileTap:b?{}:{scale:.98},children:e.jsxs(q,{className:`h-full transition-all duration-300 border-2 ${b?"opacity-50 cursor-not-allowed border-gray-200":f?"cursor-pointer border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"cursor-pointer border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>o(x.id),children:[e.jsxs(oe,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl bg-gradient-to-br ${x.color} flex items-center justify-center shadow-md`,children:e.jsx(g,{className:"w-7 h-7 text-white"})}),f&&e.jsx(Ht.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(za,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(de,{className:"text-xl mb-2",children:x.name}),e.jsx(ye,{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(ee,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(ae,{variant:"secondary",className:"text-xs",children:x.category})}),e.jsx(Qt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(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(qt,{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((j,y)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(Oe,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:j})]},y)),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(Ht.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(M,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(M,{onClick:c,disabled:!r||i||((d=Nn.find(x=>x.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=Nn.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(fs,{className:"w-4 h-4"})]})]}),e.jsx(ll,{children:r&&e.jsx(Ht.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},className:"mt-6 text-center",children:e.jsxs("p",{className:"text-sm text-gray-600",children:["Selected: ",e.jsx("span",{className:"font-semibold text-blue-600",children:(p=Nn.find(x=>x.id===r))==null?void 0:p.name})]})})})]})})]})})}function Lr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=h.useState(100),[m,p]=h.useState(0),[x,u]=h.useState(null),[g,f]=h.useState(!1),[b,j]=h.useState(null),y=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),w=s.toLowerCase().includes("pdf"),v=y||w;h.useEffect(()=>{if(!l||!v||!a){u(null);return}return(async()=>{f(!0),j(null);try{let S=a;a.startsWith("/")&&!a.startsWith("//")&&(S=`${window.location.origin}${a}`);const F=await fetch(S,{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 P=window.URL.createObjectURL($);u(P)}catch(N){console.error("Failed to load file for preview:",N),j(N instanceof Error?N.message:"Failed to load file for preview")}finally{f(!1)}})(),()=>{x&&(window.URL.revokeObjectURL(x),u(null))}},[l,a,v,w]);const C=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},A=()=>d(R=>Math.min(R+25,200)),L=()=>d(R=>Math.max(R-25,50)),D=()=>p(R=>(R+90)%360);return e.jsx(ht,{open:l,onOpenChange:o,children:e.jsx(mt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(pt,{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(St,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ut,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`• ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[y&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(M,{variant:"ghost",size:"sm",onClick:L,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(vb,{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(M,{variant:"ghost",size:"sm",onClick:A,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(Nb,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:D,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(oh,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(M,{variant:"outline",size:"sm",onClick:C,className:"gap-2 h-9",children:[e.jsx(Rt,{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(Qe,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):b?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(jt,{className:"w-10 h-10 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Failed"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:b}),i&&n&&e.jsxs(M,{onClick:C,className:"gap-2",children:[e.jsx(Rt,{className:"h-4 w-4"}),"Download ",t]})]}):v&&x?e.jsxs(e.Fragment,{children:[y&&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:()=>{j("Failed to load PDF preview")}})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(St,{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(M,{onClick:C,className:"gap-2",children:[e.jsx(Rt,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function ti({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following policy violations were detected:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:a.map((n,i)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:n.type}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:n.message}),n.currentValue!==void 0&&n.maxValue!==void 0&&e.jsxs("p",{className:"text-xs text-red-600 mt-1 font-semibold",children:["Current: ",n.currentValue," / Maximum: ",n.maxValue]})]},i))}),r&&e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"System Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[r.maxApprovalLevels!==void 0&&e.jsxs("li",{children:["Maximum approval levels: ",r.maxApprovalLevels]}),r.maxParticipants!==void 0&&e.jsxs("li",{children:["Maximum participants per request: ",r.maxParticipants]}),r.allowSpectators!==void 0&&e.jsxs("li",{children:["Allow adding spectators: ",r.allowSpectators?"Yes":"No"]}),r.maxSpectators!==void 0&&e.jsxs("li",{children:["Maximum spectators per request: ",r.maxSpectators]})]})]})]})})]}),e.jsx(Et,{children:e.jsx(M,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const la=async t=>{const s=t?{category:t}:{};return(await je.get("/users/configurations",{params:s})).data.data},ml=async t=>{const s=t?{category:t}:{};return(await je.get("/admin/configurations",{params:s})).data.data},Vs=async(t,s)=>{await je.put(`/admin/configurations/${t}`,{configValue:s})},DA=async t=>{await je.post(`/admin/configurations/${t}/reset`)},FA=async()=>{const t=await je.get("/admin/form16-config");return t.data.data??t.data},IA=async t=>{await je.put("/admin/form16-config",t)},PA=async t=>{const s=t?{year:t}:{};return(await je.get("/admin/holidays",{params:s})).data.data},EA=async t=>(await je.post("/admin/holidays",t)).data.data,_A=async(t,s)=>(await je.put(`/admin/holidays/${t}`,s)).data.data,MA=async t=>{await je.delete(`/admin/holidays/${t}`)},LA=async()=>(await je.get("/config/activity-types")).data.data,OA=async t=>{const s={activeOnly:t.toString()};return(await je.get("/admin/activity-types",{params:s})).data.data},$A=async t=>(await je.post("/admin/activity-types",t)).data.data,UA=async(t,s)=>(await je.put(`/admin/activity-types/${t}`,s)).data.data,BA=async t=>{await je.delete(`/admin/activity-types/${t}`)},VA={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 zA(t,s,a){const[r,n]=h.useState(VA),[i,l]=h.useState(null),[o,c]=h.useState(t),[d,m]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[p,x]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[u,g]=h.useState([]);return h.useEffect(()=>{(async()=>{var j;try{const y=await la("DOCUMENT_POLICY"),w={};y.forEach(_=>{w[_.configKey]=_.configValue});const v=parseInt(w.MAX_FILE_SIZE_MB||"10"),A=(w.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(_=>_.trim().toLowerCase());x({maxFileSizeMB:v,allowedFileTypes:A});const L=await la("SYSTEM_SETTINGS"),D=await la("WORKFLOW_SHARING"),R=[...L,...D],N={};R.forEach(_=>{N[_.configKey]=_.configValue}),m({maxApprovalLevels:parseInt(N.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(N.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((j=N.ALLOW_ADD_SPECTATOR)==null?void 0:j.toLowerCase())==="true",maxSpectators:parseInt(N.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(y){console.error("Failed to load policies:",y)}})()},[]),h.useEffect(()=>{if(!t||!s)return;let b=!0;return(async()=>{try{c(!0);const j=await Es(s);if(!b||!j)return;const y=j.workflow||{},w=Array.isArray(j.approvals)?j.approvals:[],v=Array.isArray(j.participants)?j.participants:[],C=Array.isArray(j.documents)?j.documents.filter(S=>!S.isDeleted):[];g(C);const A=(y.priority||"").toString().toLowerCase(),L={standard:"standard",express:"express"},D=y.templateType==="TEMPLATE"?"existing-template":"custom",R=a.find(S=>S.id===D)||a[0]||null;l(R);const N=w.sort((S,U)=>(S.levelNumber||0)-(U.levelNumber||0)).map(S=>{const U=Number(S.tatHours||24),F=Math.floor(U/24),$=U%24;return{id:S.approverId||`temp-${S.levelNumber}`,name:S.approverName||S.approverEmail||"",email:S.approverEmail||"",role:S.levelName||`Level ${S.levelNumber}`,department:"",avatar:(S.approverName||S.approverEmail||"XX").substring(0,2).toUpperCase(),level:S.levelNumber||1,canClose:!1,tat:F>0?F:$,tatType:F>0?"days":"hours",userId:S.approverId}}),_=v.filter(S=>(S.participantType||S.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(S.userEmail||S.user_email||S.email):!1).map((S,U)=>{const F=S.userId||S.user_id||S.id,$=S.userName||S.user_name||S.name||"",P=S.userEmail||S.user_email||S.email||"",k=($||P||"XX").split(" ").map(B=>B[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:F||`spectator-${s}-${U}-${Date.now()}`,userId:F,name:$||P||"Spectator",email:P,role:"Spectator",department:S.department||"",avatar:k,level:1,canClose:!1}});n(S=>({...S,template:D,title:y.title||"",description:y.description||"",priority:L[A]||"standard",approvers:N,approverCount:N.length||1,spectators:_,maxLevel:Math.max(...N.map(U=>U.level||1),1)}))}catch(j){console.error("Failed to load draft:",j)}finally{b&&c(!1)}})(),()=>{b=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(b,j)=>{n(y=>({...y,[b]:j}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:d,documentPolicy:p,existingDocuments:u,setExistingDocuments:g}}const ux=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function HA(t,s,a){const[r,n]=h.useState(t?2:1),i=ux.length,l=p=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p),o=()=>{switch(r){case 1:return s!==null;case 2:return a.title.trim()!==""&&a.description.trim()!==""&&a.priority!=="";case 3:return(a.approverCount||1)>0&&a.approvers.length===(a.approverCount||1)&&a.approvers.every(p=>{if(!p||!p.email||!l(p.email))return!1;if(!p.userId)return!0;const x=p.tatType||"hours";return x==="hours"?p.tat&&p.tat>0&&p.tat<=720:x==="days"?p.tat&&p.tat>0&&p.tat<=30:!1});case 4:return!0;case 5:return!0;case 6:return!0;default:return!1}};return{currentStep:r,setCurrentStep:n,totalSteps:i,stepNames:ux,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:p=>{p>=1&&p<=i&&n(p)},validateEmail:l}}function WA(){const[t,s]=h.useState({open:!1,type:"error",email:"",message:""}),[a,r]=h.useState({open:!1,violations:[]}),[n,i]=h.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 GA(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function YA(t,s,a){var n;const r=GA(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 KA(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return YA(a,n,n===s)})}function xx(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 hx(t,s,a,r=!1){const n=KA(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 QA(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 px(t,s){return{id:(await ic(t,s||[],"SUPPORTING")).id}}async function gx(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await Pw(t,s,a||[],r):await Iw(t,s)}function XA({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=h.useState(!1),[m,p]=h.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var f,b;if(c||m)return;const g=QA(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const j=hx(t,n,r,!1);await gx(l,j,a,r),X.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 j=xx(t,s,n,!1),y=await px(j,a);X.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been created and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:y.id,template:s})}}catch(j){console.error("Failed to submit workflow:",j),X.error("Failed to Submit Request",{description:((b=(f=j==null?void 0:j.response)==null?void 0:f.data)==null?void 0:b.message)||(j==null?void 0:j.message)||"An error occurred while submitting the request.",duration:5e3}),d(!1)}},handleSaveDraft:async()=>{var g,f;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||m)){p(!0);try{if(i&&l){const b=hx(t,n,r,!0);await gx(l,b,a,r),X.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const b=xx(t,s,n,!0),j=await px(b,a);X.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:j.id,template:s})}}catch(b){console.error("Failed to save draft:",b),X.error("Failed to Save Draft",{description:((f=(g=b==null?void 0:b.response)==null?void 0:g.data)==null?void 0:f.message)||(b==null?void 0:b.message)||"An error occurred while saving the draft.",duration:5e3}),p(!1)}}}}}async function ba(t,s=10,a="default"){return await je.get("/users/search",{params:{q:t,limit:s,source:a}})}async function ga(t){var a;const s=await je.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function JA(t,s){return await je.post("/admin/users/assign-role",{email:t,role:s})}async function ZA(t,s){return await je.put(`/admin/users/${t}/role`,{role:s})}async function qA(t,s=1,a=10){return await je.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function eT(){return await je.get("/admin/users/role-statistics")}async function tT(t){var a;const s=await je.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function sT(){var s,a;return((a=(s=(await je.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const sa={searchUsers:ba,getUserById:tT,ensureUserExists:ga,assignRole:JA,updateUserRole:ZA,getUsersByRole:qA,getRoleStatistics:eT,getAllUsers:sT};async function aT(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 ba(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 ga({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 rT(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 R=new Date;R.setDate(R.getDate()+D.suggestedSLA),a("slaEndDate",R),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"){f(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&p){const _=r.approverCount||1;if(_>m.maxApprovalLevels){p([{type:"Maximum Approval Levels Exceeded",message:`The request has ${_} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:_,maxValue:m.maxApprovalLevels}]);return}}const R=((D=c==null?void 0:c.email)==null?void 0:D.toLowerCase())||"",N=await rT(r.approvers,R);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,R)=>{if(R){const N=D.documentId||D.document_id||"";j({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:mn(N),fileSize:Number(D.fileSize||D.file_size||0),documentId:N})}else{const N=URL.createObjectURL(D);j({fileName:D.name,fileType:D.type||"application/octet-stream",fileUrl:N,fileSize:D.size,file:D})}},closePreview:()=>{b!=null&&b.fileUrl&&(b!=null&&b.file)&&URL.revokeObjectURL(b.fileUrl),j(null)}}}const fx=[{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:Ki,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:Ie,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let Pr=null;const bx=()=>Pr,iT=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 Pr&&Pr.push(r),r},ul=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 Pr=a,a},lT=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 Pr&&(Pr=Pr.map(i=>i.id===t?n:i)),n};function Kg({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 oT({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(M,{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(Cs,{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(M,{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(Qe,{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(M,{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(Qe,{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(ch,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(M,{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(fs,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const jx=t=>{switch(t){case"high":return e.jsx(Ca,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(qt,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ws,{className:"w-4 h-4 text-green-600"});default:return e.jsx(qt,{className:"w-4 h-4 text-gray-600"})}};function cT({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=h.useState("main"),l=ys(),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(Ht.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(M,{variant:"ghost",className:"gap-2",onClick:()=>i("main"),children:[e.jsx(Cs,{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(wb,{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(Ht.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${m.id}`,children:e.jsxs(q,{className:`h-full transition-all duration-300 border-2 ${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(oe,{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(Ht.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(za,{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(de,{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(ae,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),jx(m.priority)]})]})]}),e.jsxs(ee,{className:"pt-0 space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed line-clamp-2","data-testid":`template-card-${m.id}-description`,children:m.description}),!x&&e.jsxs(e.Fragment,{children:[e.jsx(Qt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-estimated-time`,children:[e.jsx(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(Jt,{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(ll,{children:s&&e.jsx(Ht.div,{initial:{opacity:0,y:20,height:0},animate:{opacity:1,y:0,height:"auto"},exit:{opacity:0,y:-20,height:0},transition:{duration:.3},className:"w-full max-w-6xl","data-testid":"template-details-card",children:e.jsxs(q,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(_r,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(ee,{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(te,{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(te,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[jx(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(te,{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(te,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((d=s.commonApprovers)==null?void 0:d.length)>0?s.commonApprovers.map((m,p)=>e.jsx(ae,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${p}`,children:m},`${s.id}-approver-${p}-${m}`)):e.jsx("span",{className:"text-sm text-gray-500 italic",children:"No specific approvers defined"})})]})]})]})})})]})}function Ce({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:Me("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 dT({className:t,...s}){return e.jsx(Df,{"data-slot":"radio-group",className:Me("grid gap-3",t),...s})}function yx({className:t,...s}){return e.jsx(Ff,{"data-slot":"radio-group-item",className:Me("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(If,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(Bo,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function mT({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(Ht.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(Ie,{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(te,{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(Ce,{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(te,{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(Xn,{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(te,{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(dT,{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(yx,{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(Gi,{className:"w-4 h-4 text-red-600"}),e.jsx(te,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(ae,{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(yx,{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(te,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(ae,{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(te,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(Ce,{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(te,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(He,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Ge,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(We,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"USD",children:"USD ($)"}),e.jsx(J,{value:"EUR",children:"EUR (€)"}),e.jsx(J,{value:"GBP",children:"GBP (£)"}),e.jsx(J,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(te,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(Ce,{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(te,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(Ce,{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(te,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(Ce,{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 Qg(){const[t,s]=h.useState([]),[a,r]=h.useState(!1),n=h.useRef(null);return{searchResults:t,searchLoading:a,searchUsersDebounced:async(c,d=10)=>{if(n.current&&clearTimeout(n.current),!c||!c.startsWith("@")||c.length<2){s([]),r(!1);return}r(!0),n.current=setTimeout(async()=>{var m;try{const p=c.slice(1),u=((m=(await ba(p,d)).data)==null?void 0:m.data)||[];s(u)}catch(p){console.error("User search failed:",p),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await ga({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 Xg(){const[t,s]=h.useState({}),[a,r]=h.useState({}),n=h.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(o,c,d=10)=>{if(n.current[o]&&clearTimeout(n.current[o]),!c||!c.startsWith("@")||c.length<2){s(m=>({...m,[o]:[]})),r(m=>({...m,[o]:!1}));return}r(m=>({...m,[o]:!0})),n.current[o]=setTimeout(async()=>{var m;try{const p=c.slice(1),u=((m=(await ba(p,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:u}))}catch(p){console.error(`User search failed for index ${o}:`,p),s(x=>({...x,[o]:[]}))}finally{r(p=>({...p,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function uT({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var p;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=Xg();h.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 j,y,w,v,C;const g=[...t.approvers],b=((j=g[x])==null?void 0:j.email)!==u;if(g[x]={...g[x],email:u,level:x+1,userId:b||(y=g[x])==null?void 0:y.userId,name:b||(w=g[x])==null?void 0:w.name,department:b||(v=g[x])==null?void 0:v.department,avatar:b||(C=g[x])==null?void 0:C.avatar},s("approvers",g),!u||!u.startsWith("@")||u.length<2){c(x);return}o(x,u,10)},m=async(x,u)=>{var g,f;try{if((g=t.approvers)==null?void 0:g.some((v,C)=>{var A,L;return C!==x&&(v.userId===u.userId||((A=v.email)==null?void 0:A.toLowerCase())===((L=u.email)==null?void 0:L.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((f=t.spectators)==null?void 0:f.some(v=>{var C,A;return v.userId===u.userId||((C=v.email)==null?void 0:C.toLowerCase())===((A=u.email)==null?void 0:A.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 y=await ga({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:y.userId,level:x+1},s("approvers",w),c(x)}catch(b){console.error("Failed to ensure user exists:",b),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(Ht.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(Jt,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"approval-workflow-title",children:"Approval Workflow"}),e.jsx("p",{className:"text-gray-600","data-testid":"approval-workflow-description",children:"Define the approval hierarchy and assign approvers by email ID."})]}),e.jsxs("div",{className:"max-w-4xl mx-auto space-y-8","data-testid":"approval-workflow-content",children:[e.jsxs(q,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(cr,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(ye,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(ee,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(te,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(M,{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(Vo,{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(M,{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(bs,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Maximum ",r.maxApprovalLevels," approver",r.maxApprovalLevels!==1?"s":""," allowed. Each approver will review sequentially."]})]})})]}),e.jsxs(q,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(ps,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(ye,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(ee,{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(ae,{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 j,y;const g=u+1,f=g===(t.approverCount||1),b=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 ${b.email?"border-green-200 bg-green-50":"border-gray-200 bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${b.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:g})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",g]}),f&&e.jsx(ae,{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(te,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),b.email&&b.userId&&e.jsxs(ae,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Oe,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ce,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:b.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]||(((j=i[u])==null?void 0:j.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:(y=i[u])==null?void 0:y.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(te,{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(Ce,{id:`tat-${g}`,type:"number",placeholder:b.tatType==="days"?"7":"24",min:"1",max:b.tatType==="days"?"30":"720",value:b.tat||"",onChange:w=>{const v=[...t.approvers];v[u]={...v[u],tat:parseInt(w.target.value)||"",level:g,tatType:b.tatType||"hours"},s("approvers",v)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(He,{value:b.tatType||"hours",onValueChange:w=>{const v=[...t.approvers];v[u]={...v[u],tatType:w,level:g,tat:""},s("approvers",v)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(Ge,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(We,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"hours",children:"Hours"}),e.jsx(J,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},g)})]})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(_r,{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((f,b)=>{const j=Number(b.tat||0);return(b.tatType||"hours")==="days"?f+j:f+j/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:(p=t.approvers)==null?void 0:p.map((x,u)=>{const g=Number(x.tat||0),b=(x.tatType||"hours")==="days"?g*24:g;return g?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",u+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[b," ",b===1?"hour":"hours"]})]})},u):null})}),(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((f,b)=>{const j=Number(b.tat||0);return(b.tatType||"hours")==="days"?f+j*24:f+j},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 xT({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=h.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=Qg(),p=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},x=async g=>{var f,b;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const j=t.spectators.some(w=>{var v,C;return w.userId===g.userId||((v=w.email)==null?void 0:v.toLowerCase())===((C=g.email)==null?void 0:C.toLowerCase())}),y=(f=t.approvers)==null?void 0:f.some(w=>{var v,C;return w.userId===g.userId||((v=w.email)==null?void 0:v.toLowerCase())===((C=g.email)==null?void 0:C.toLowerCase())});if(j){a({type:"error",email:g.email,message:"This user is already added as a spectator."});return}if(y){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),v={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},C=[...t.spectators,v];s("spectators",C),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 j=t.spectators.some(w=>{var v;return((v=w.email)==null?void 0:v.toLowerCase())===n.toLowerCase()}),y=(b=t.approvers)==null?void 0:b.some(w=>{var v;return((v=w.email)==null?void 0:v.toLowerCase())===n.toLowerCase()});if(j){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(y){a({type:"error",email:n,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}}},u=g=>{const f=t.spectators.filter(b=>b.id!==g);s("spectators",f)};return e.jsxs(Ht.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(St,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"participants-title",children:"Participants & Access"}),e.jsx("p",{className:"text-gray-600","data-testid":"participants-description",children:"Configure additional participants and visibility settings for your request."})]}),e.jsx("div",{className:"max-w-3xl mx-auto space-y-8","data-testid":"participants-content",children:e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:e.jsxs(q,{"data-testid":"participants-spectators-card",children:[e.jsxs(oe,{children:[e.jsxs(de,{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(St,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(ae,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(ye,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(ee,{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(Ce,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>p(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.preventDefault(),await x())},className:"text-sm w-full","data-testid":"participants-spectators-email-input"}),(o||l.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:o?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:l.map(g=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>x(g),"data-testid":`participants-spectators-search-result-${g.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:g.displayName||g.email}),e.jsx("div",{className:"text-xs text-gray-600",children:g.email})]},g.userId))})})]}),e.jsx(M,{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(_r,{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(ls,{className:"h-6 w-6",children:e.jsx(os,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>u(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(jt,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function hT({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:c,onDocumentErrors:d,fileInputRef:m}){const p=f=>{const b=Array.from(f.target.files||[]);if(b.length===0)return;const j=t.maxFileSizeMB*1024*1024,y=[],w=[];b.forEach(v=>{if(v.size>j){y.push({fileName:v.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(v.size/1048576).toFixed(2)}MB`});return}const C=v.name.toLowerCase(),A=C.substring(C.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(A)){y.push({fileName:v.name,reason:`File type "${A}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}w.push(v)}),w.length>0&&i([...a,...w]),y.length>0&&d&&d(y),f.target&&(f.target.value="")},x=f=>{const b=a.filter((j,y)=>y!==f);i(b)},u=f=>{o([...n,f])},g=(f,b=!1)=>{if(b){const j=(f.fileType||f.file_type||"").toLowerCase(),y=(f.originalFileName||f.fileName||"").toLowerCase();return j.includes("image")||j.includes("pdf")||y.endsWith(".jpg")||y.endsWith(".jpeg")||y.endsWith(".png")||y.endsWith(".gif")||y.endsWith(".pdf")}else{const j=(f.type||"").toLowerCase(),y=(f.name||"").toLowerCase();return j.includes("image")||j.includes("pdf")||y.endsWith(".jpg")||y.endsWith(".jpeg")||y.endsWith(".png")||y.endsWith(".gif")||y.endsWith(".pdf")}};return e.jsxs(Ht.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(js,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"documents-title",children:"Documents & Attachments"}),e.jsx("p",{className:"text-gray-600","data-testid":"documents-description",children:"Upload supporting documents, files, and any additional materials for your request."})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"documents-content",children:[e.jsxs(q,{"data-testid":"documents-upload-card",children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Ie,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(ye,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(ee,{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(js,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"click to browse"}),e.jsx("input",{type:"file",multiple:!0,accept:t.allowedFileTypes.map(f=>`.${f}`).join(","),onChange:p,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(M,{variant:"outline",size:"lg",type:"button",onClick:()=>{var f;return(f=m.current)==null?void 0:f.click()},"data-testid":"documents-browse-button",children:[e.jsx(bs,{className:"w-4 h-4 mr-2"}),"Browse Files"]}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Supported formats: ",t.allowedFileTypes.map(f=>f.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(q,{"data-testid":"documents-existing-card",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ae,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(f=>!n.includes(f.documentId||f.document_id||"")).length," file",r.filter(f=>!n.includes(f.documentId||f.document_id||"")).length!==1?"s":""]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(f=>{const b=f.documentId||f.document_id||"";return n.includes(b)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${b}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Ie,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:f.originalFileName||f.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:f.fileSize?(Number(f.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(f,!0)&&e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>c(f,!0),"data-testid":`documents-existing-${b}-preview`,children:e.jsx(St,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>u(b),"data-testid":`documents-existing-${b}-delete`,children:e.jsx(jt,{className:"h-4 w-4 text-red-600"})})]})]},b)})})})]}),a.length>0&&e.jsxs(q,{"data-testid":"documents-new-card",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ae,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((f,b)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${b}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Ie,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:f.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(f.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(f,!1)&&e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>c(f,!1),"data-testid":`documents-new-${b}-preview`,children:e.jsx(St,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>x(b),"data-testid":`documents-new-${b}-remove`,children:e.jsx(jt,{className:"h-4 w-4"})})]})]},b))})})]})]})]})}const pT=t=>{switch(t){case"high":return e.jsx(Ca,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(qt,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ws,{className:"w-4 h-4 text-green-600"});default:return e.jsx(qt,{className:"w-4 h-4 text-gray-600"})}};function gT({formData:t,selectedTemplate:s}){return e.jsxs(Ht.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(Oe,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"review-submit-title",children:"Review & Submit"}),e.jsx("p",{className:"text-gray-600","data-testid":"review-submit-description",children:"Please review all details before submitting your request for approval."})]}),e.jsxs("div",{className:"max-w-5xl mx-auto space-y-8","data-testid":"review-submit-content",children:[e.jsxs(q,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(ch,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(ee,{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(te,{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(ae,{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(te,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[pT(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(te,{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(te,{className:"text-green-900 font-semibold",children:"Request Title"}),e.jsx("p",{className:"text-green-800 font-medium mt-1 text-lg",children:t.title})]})]})]}),e.jsxs(q,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Ie,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(te,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(_s,{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(Ha,{className:"w-4 h-4 text-blue-600"}),e.jsx(te,{className:"font-semibold text-blue-900",children:"Financial Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Amount"}),e.jsxs("p",{className:"font-semibold text-blue-900",children:[t.amount," ",t.currency]})]}),t.costCenter&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Cost Center"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.costCenter})]})]})]})]})]}),e.jsxs(q,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(Jt,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(ye,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(ee,{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(ae,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Email Address"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:(l==null?void 0:l.email)||"Not assigned"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"TAT (Turn Around Time)"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l!=null&&l.tat?`${l.tat} ${l.tatType==="days"?"day":"hour"}${l.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(q,{"data-testid":"review-submit-participants-card",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(St,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(ee,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(te,{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(ae,{variant:"outline",className:"text-xs","data-testid":`review-submit-spectator-${a.id}`,children:[a.name," (",a.email,")"]},a.id))})]})})]}),t.documents.length>0&&e.jsxs(q,{"data-testid":"review-submit-documents-card",children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(js,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(ye,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(ee,{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(Ie,{className:"w-5 h-5 text-gray-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.name}),e.jsx("div",{className:"flex items-center gap-3 text-xs text-gray-500 mt-1",children:e.jsxs("span",{children:[(a.size/(1024*1024)).toFixed(2)," MB"]})})]})]},r))})})]}),e.jsx(q,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Oe,{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 fT({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(M,{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(Cs,{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 bT({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(ll,{mode:"wait",children:t})})})}function jT({modal:t,onClose:s}){return e.jsx(ht,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(ut,{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(_t,{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(Ki,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use"," ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," ","sign to search and select users from the directory for guaranteed results."]})})]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:[t.email&&e.jsxs(e.Fragment,{children:["Failed to validate ",e.jsx("strong",{children:t.email}),"."]}),!t.email&&e.jsx(e.Fragment,{children:"An error occurred during validation."})]}),t.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:t.message})})]})]})})]}),e.jsx(Et,{children:e.jsx(M,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function yT({modal:t,documentPolicy:s,onClose:a}){return e.jsx(ht,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(mt,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(ut,{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(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:t.errors.map((r,n)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3","data-testid":`document-error-${n}`,children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:r.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:r.reason})]},n))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",s.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types:"," ",s.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Et,{children:e.jsx(M,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function vx({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=_a(),i=ys(),l=n.requestId||a||"",o=r&&!!l,{user:c}=cs(),[d,m]=h.useState([]);h.useEffect(()=>{(async()=>{try{const Fe=(await ul()).map(_e=>({id:_e.id,name:_e.name,description:_e.description,category:_e.category,icon:Ie,estimatedTime:_e.estimatedTime,commonApprovers:_e.approvers.map(Xe=>Xe.name),workflowApprovers:_e.approvers,suggestedSLA:_e.suggestedSLA,priority:_e.priority,fields:_e.fields||{}}));m(Fe)}catch(ge){console.error("Failed to fetch admin templates:",ge)}})()},[]);const p=h.useMemo(()=>[...fx,...d],[d]),{formData:x,updateFormData:u,selectedTemplate:g,setSelectedTemplate:f,loadingDraft:b,systemPolicy:j,documentPolicy:y,existingDocuments:w,setExistingDocuments:v}=zA(o,l,p),{currentStep:C,totalSteps:A,stepNames:L,isStepValid:D,nextStep:R,prevStep:N}=HA(o,g,x),[_,S]=h.useState([]),[U,F]=h.useState([]),$=h.useRef(null),{validationModal:P,policyViolationModal:T,documentErrorModal:k,openValidationModal:B,closeValidationModal:I,openPolicyViolationModal:E,closePolicyViolationModal:W,openDocumentErrorModal:V,closeDocumentErrorModal:Y}=WA(),{submitting:Z,savingDraft:O,handleSubmit:z,handleSaveDraft:K}=XA({formData:x,selectedTemplate:g,documents:_,documentsToDelete:U,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:re,setShowTemplateModal:G,previewDocument:se,selectTemplate:ve,handleTemplateSelection:Te,nextStep:Ke,prevStep:Je,handlePreviewDocument:Pe,closePreview:$e}=nT({selectedTemplate:g,setSelectedTemplate:f,updateFormData:u,formData:x,currentStep:C,isStepValid:D,wizardNextStep:R,wizardPrevStep:N,user:c,openValidationModal:B,systemPolicy:j,onPolicyViolation:E,onSubmit:s}),ne=h.useCallback(()=>{if(C===1){i("/dashboard",{replace:!0});return}C===3||C===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Je()},[C,t,i,Je]),he=h.useRef(!0),Ne=h.useRef(!1);h.useEffect(()=>{he.current&&x.documents&&x.documents.length>0&&!Ne.current&&(S(x.documents),Ne.current=!0),he.current=!1},[x.documents]);const Ae=h.useRef(!1),Q=h.useRef(_);h.useEffect(()=>{if(Ae.current){Ae.current=!1,Q.current=_;return}Q.current!==_&&(u("documents",_),Q.current=_)},[_]);const le=()=>{switch(C){case 1:return e.jsx(cT,{templates:fx,selectedTemplate:g,onSelectTemplate:ve,adminTemplates:d});case 2:return e.jsx(mT,{formData:x,selectedTemplate:g,updateFormData:u});case 3:return e.jsx(uT,{formData:x,updateFormData:u,systemPolicy:j,onValidationError:pe=>B(pe.type,pe.email,pe.message),onPolicyViolation:E});case 4:return e.jsx(xT,{formData:x,updateFormData:u,onValidationError:pe=>B(pe.type,pe.email,pe.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(hT,{documentPolicy:y,isEditing:o,documents:_,existingDocuments:w,documentsToDelete:U,onDocumentsChange:S,onExistingDocumentsChange:v,onDocumentsToDeleteChange:F,onPreviewDocument:Pe,onDocumentErrors:pe=>V(pe),fileInputRef:$});case 6:return e.jsx(gT,{formData:x,selectedTemplate:g});default:return null}};return b?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center","data-testid":"create-request-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading draft..."})]})}):e.jsxs("div",{className:"h-full flex flex-col bg-gradient-to-br from-gray-50 to-white","data-testid":"create-request",children:[e.jsx(fT,{isEditing:o,currentStep:C,totalSteps:A,stepNames:L,onBack:ne}),e.jsx(Kg,{currentStep:C,totalSteps:A,stepNames:L}),e.jsx(bT,{children:le()}),e.jsx(oT,{currentStep:C,totalSteps:A,isStepValid:D(),onPrev:Je,onNext:Ke,onSubmit:z,onSaveDraft:K,submitting:Z,savingDraft:O,loadingDraft:b,isEditing:o}),e.jsx(RA,{open:re,onClose:()=>G(!1),onSelectTemplate:Te}),se&&e.jsx(Lr,{fileName:se.fileName,fileType:se.fileType,fileUrl:se.fileUrl,fileSize:se.fileSize,open:!!se,onClose:$e,onDownload:async()=>{if(se.file){const pe=document.createElement("a");pe.href=se.fileUrl,pe.download=se.fileName,document.body.appendChild(pe),pe.click(),document.body.removeChild(pe)}else se.documentId&&await Ls(se.documentId)},attachmentId:se.documentId}),e.jsx(jT,{modal:P,onClose:I}),e.jsx(yT,{modal:k,documentPolicy:y,onClose:Y}),e.jsx(ti,{open:T.open,onClose:W,violations:T.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}function si({className:t,...s}){return e.jsx(Pf,{"data-slot":"tabs",className:Me("flex flex-col gap-2",t),...s})}function ai({className:t,...s}){return e.jsx(Ef,{"data-slot":"tabs-list",className:Me("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function Lt({className:t,...s}){return e.jsx(_f,{"data-slot":"tabs-trigger",className:Me("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 Ot({className:t,...s}){return e.jsx(Mf,{"data-slot":"tabs-content",className:Me("flex-1 outline-none",t),...s})}function Vc(t,s=[],a){const[r,n]=h.useState(null),[i,l]=h.useState(!1),[o,c]=h.useState(!0),[d,m]=h.useState(null),[p,x]=h.useState(null),[u,g]=h.useState(!1),f=(C,A)=>(C||A||"NA").toString().split(" ").map(D=>D[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),b=C=>{const A=(C||"").toUpperCase();return A==="IN_PROGRESS"?"in-review":A==="PENDING"?"pending":A==="APPROVED"?"approved":A==="REJECTED"?"rejected":A==="CLOSED"?"closed":A==="SKIPPED"?"skipped":(C||"").toLowerCase()},j=h.useCallback(async()=>{var C,A,L,D,R,N,_,S,U,F,$,P,T;l(!0);try{const k=await Gs.getWorkflowDetails(t);if(!k){console.warn("[useRequestDetails] No details returned from API");return}const B=k.workflow||{},I=Array.isArray(k.approvals)?k.approvals:[],E=Array.isArray(k.participants)?k.participants:[],W=Array.isArray(k.documents)?k.documents:[],V=k.summary||{},Y=Array.isArray(k.tatAlerts)?k.tatAlerts:[];Y.length>0;const Z=(V==null?void 0:V.currentLevel)||B.currentLevel||1,O=I.map(Q=>{const le=Q.levelNumber||0,pe=(Q.status||"").toString().toUpperCase(),ge=Q.levelId||Q.level_id;let Fe=b(Q.status);le>Z&&pe!=="APPROVED"&&pe!=="REJECTED"?Fe="waiting":le===Z&&pe==="PENDING"&&(Fe="pending");const _e=Y.filter(Xe=>Xe.levelId===ge);return{step:le,levelId:ge,role:Q.levelName||Q.approverName||"Approver",status:Fe,approver:Q.approverName||Q.approverEmail,approverId:Q.approverId||Q.approver_id,approverEmail:Q.approverEmail,tatHours:Number(Q.tatHours||0),elapsedHours:Number(Q.elapsedHours||0),remainingHours:Number(Q.remainingHours||0),tatPercentageUsed:Number(Q.tatPercentageUsed||0),actualHours:Q.levelEndTime&&Q.levelStartTime?Math.max(0,(new Date(Q.levelEndTime).getTime()-new Date(Q.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:Q.comments||void 0,timestamp:Q.actionDate||void 0,levelStartTime:Q.levelStartTime||Q.tatStartTime,tatAlerts:_e,skipReason:Q.skipReason||void 0,isSkipped:pe==="SKIPPED"||Q.isSkipped||!1}}),z=E.filter(Q=>(Q.participantType||Q.participant_type||"").toUpperCase()==="SPECTATOR").map(Q=>({name:Q.userName||Q.user_name||Q.userEmail||Q.user_email,role:"Spectator",email:Q.userEmail||Q.user_email,avatar:f(Q.userName||Q.user_name,Q.userEmail||Q.user_email)})),K=Q=>{var pe,ge;if(!Q)return;const le=E.find(Fe=>Fe.userId===Q||Fe.user_id===Q);return le!=null&&le.userName||le!=null&&le.user_name?le.userName||le.user_name:B.initiatorId===Q?((pe=B.initiator)==null?void 0:pe.displayName)||((ge=B.initiator)==null?void 0:ge.email):Q},re=W.map(Q=>{const le=Number(Q.fileSize||Q.file_size||0),pe=(le/(1024*1024)).toFixed(2)+" MB";return{documentId:Q.documentId||Q.document_id,name:Q.originalFileName||Q.fileName||Q.file_name,fileType:Q.fileType||Q.file_type||"",size:pe,sizeBytes:le,uploadedBy:K(Q.uploadedBy||Q.uploaded_by),uploadedAt:Q.uploadedAt||Q.uploaded_at}}),G=Array.isArray(k.activities)?k.activities.filter(Q=>(Q.type||"").toLowerCase()!=="sla_warning"):[];let se=null;if(B.isPaused||!1)try{se=await Ym(B.requestId)}catch{}let Te=null,Ke=null,Je=null,Pe=null,$e=[];if(B.workflowType==="CLAIM_MANAGEMENT"||B.templateType==="claim-management")try{const Q=await je.get(`/dealer-claims/${B.requestId}`),le=((C=Q.data)==null?void 0:C.data)||Q.data;if(le){Te=le.claimDetails||le.claim_details,Ke=le.proposalDetails||le.proposal_details,Je=le.completionDetails||le.completion_details,Pe=le.internalOrder||le.internal_order||null,$e=le.internalOrders||le.internal_orders||[];const pe=le.budgetTracking||le.budget_tracking||null,ge=le.invoice||null,Fe=le.creditNote||le.credit_note||null,_e=le.completionExpenses||le.completion_expenses||null;Te&&(Te.budgetTracking=pe,Te.invoice=ge,Te.creditNote=Fe,Te.completionExpenses=_e)}else console.warn("[useRequestDetails] No claimData found in response")}catch(Q){console.error("[useRequestDetails] Error fetching claim details:",{error:(Q==null?void 0:Q.message)||Q,status:(A=Q==null?void 0:Q.response)==null?void 0:A.status,statusText:(L=Q==null?void 0:Q.response)==null?void 0:L.statusText,responseData:(D=Q==null?void 0:Q.response)==null?void 0:D.data,requestId:B.requestId})}const ne={...B,id:B.requestNumber||B.requestId,requestId:B.requestId,requestNumber:B.requestNumber,title:B.title,description:B.description,status:b(B.status),priority:(B.priority||"").toString().toLowerCase(),workflowType:B.workflowType||(B.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:O,approvals:I,participants:E,documents:re,spectators:z,summary:V,sla:(V==null?void 0:V.sla)||B.sla||null,initiator:{name:((R=B.initiator)==null?void 0:R.displayName)||((N=B.initiator)==null?void 0:N.email),role:((_=B.initiator)==null?void 0:_.designation)||void 0,department:((S=B.initiator)==null?void 0:S.department)||void 0,email:((U=B.initiator)==null?void 0:U.email)||void 0,phone:((F=B.initiator)==null?void 0:F.phone)||void 0,avatar:f(($=B.initiator)==null?void 0:$.displayName,(P=B.initiator)==null?void 0:P.email)},createdAt:B.createdAt,updatedAt:B.updatedAt,totalSteps:B.totalLevels||1,currentStepRaw:(V==null?void 0:V.currentLevel)||B.currentLevel||1,currentStep:Math.min(Math.max(1,(V==null?void 0:V.currentLevel)||B.currentLevel||1),B.totalLevels||1),auditTrail:G,conclusionRemark:B.conclusionRemark||null,closureDate:B.closureDate||null,pauseInfo:se||null,claimDetails:Te||null,proposalDetails:Ke||null,completionDetails:Je||null,internalOrder:Pe||null,internalOrders:$e||[],budgetTracking:(Te==null?void 0:Te.budgetTracking)||null,invoice:(Te==null?void 0:Te.invoice)||(Te==null?void 0:Te.invoice)||null,creditNote:(Te==null?void 0:Te.creditNote)||null,completionExpenses:(Te==null?void 0:Te.completionExpenses)||null,templateType:B.templateType||B.template_type,form16Submission:k.form16Submission||null};n(ne);const he=(T=a==null?void 0:a.email)==null?void 0:T.toLowerCase(),Ne=I.find(Q=>{const le=(Q.status||"").toString().toUpperCase(),pe=(Q.approverEmail||"").toLowerCase(),ge=Q.levelNumber||0;return(le==="PENDING"||le==="IN_PROGRESS"||le==="PAUSED")&&pe===he&&ge===Z});x(Ne||null);const Ae=a==null?void 0:a.userId;if(Ae){const Q=E.some(le=>(le.participantType||le.participant_type||"").toUpperCase()==="SPECTATOR"&&(le.userId||le.user_id)===Ae);g(Q)}else g(!1)}catch(k){console.error("[useRequestDetails] Error refreshing details:",k),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);h.useEffect(()=>{if(!t){c(!1);return}let C=!0;return c(!0),m(null),(async()=>{var A,L,D,R,N,_,S,U,F,$,P,T,k,B;try{const I=await Gs.getWorkflowDetails(t);if(!C||!I){C&&c(!1);return}const E=I.workflow||{},W=Array.isArray(I.approvals)?I.approvals:[],V=Array.isArray(I.participants)?I.participants:[],Y=Array.isArray(I.documents)?I.documents:[],Z=I.summary||{},O=Array.isArray(I.tatAlerts)?I.tatAlerts:[],z=(E.priority||"").toString().toLowerCase(),K=(Z==null?void 0:Z.currentLevel)||E.currentLevel||1,re=W.map(ge=>{const Fe=ge.levelNumber||0,_e=(ge.status||"").toString().toUpperCase(),Xe=ge.levelId||ge.level_id;let lt=b(ge.status);_e==="PAUSED"?lt="paused":Fe>K&&_e!=="APPROVED"&&_e!=="REJECTED"?lt="waiting":Fe===K&&(_e==="PENDING"||_e==="IN_PROGRESS")&&(lt=_e==="IN_PROGRESS"?"in-review":"pending");const Nt=O.filter(wt=>wt.levelId===Xe);return{step:Fe,levelId:Xe,role:ge.levelName||ge.approverName||"Approver",status:lt,approver:ge.approverName||ge.approverEmail,approverId:ge.approverId||ge.approver_id,approverEmail:ge.approverEmail,tatHours:Number(ge.tatHours||0),elapsedHours:Number(ge.elapsedHours||0),remainingHours:Number(ge.remainingHours||0),tatPercentageUsed:Number(ge.tatPercentageUsed||0),actualHours:ge.elapsedHours!==void 0&&ge.elapsedHours!==null?Number(ge.elapsedHours):void 0,comment:ge.comments||void 0,timestamp:ge.actionDate||void 0,levelStartTime:ge.levelStartTime||ge.tatStartTime,tatAlerts:Nt}}),G=V.filter(ge=>(ge.participantType||"").toUpperCase()==="SPECTATOR").map(ge=>({name:ge.userName||ge.userEmail,role:"Spectator",avatar:f(ge.userName,ge.userEmail)})),se=ge=>{var _e,Xe;if(!ge)return;const Fe=V.find(lt=>lt.userId===ge);return Fe!=null&&Fe.userName?Fe.userName:E.initiatorId===ge?((_e=E.initiator)==null?void 0:_e.displayName)||((Xe=E.initiator)==null?void 0:Xe.email):ge},ve=Y.map(ge=>{const Fe=Number(ge.fileSize||0),_e=(Fe/(1024*1024)).toFixed(2)+" MB";return{documentId:ge.documentId||ge.document_id,name:ge.originalFileName||ge.fileName,fileType:ge.fileType||ge.file_type||"",size:_e,sizeBytes:Fe,uploadedBy:se(ge.uploadedBy),uploadedAt:ge.uploadedAt}}),Te=Array.isArray(I.activities)?I.activities.filter(ge=>(ge.type||"").toLowerCase()!=="sla_warning"):[];let Ke=null;if(E.isPaused||!1)try{Ke=await Ym(E.requestId)}catch{}let Pe=null,$e=null,ne=null,he=null,Ne=[];if(E.workflowType==="CLAIM_MANAGEMENT"||E.templateType==="claim-management")try{const ge=await je.get(`/dealer-claims/${E.requestId}`),Fe=((A=ge.data)==null?void 0:A.data)||ge.data;if(Fe){Pe=Fe.claimDetails||Fe.claim_details,$e=Fe.proposalDetails||Fe.proposal_details,ne=Fe.completionDetails||Fe.completion_details,he=Fe.internalOrder||Fe.internal_order||null,Ne=Fe.internalOrders||Fe.internal_orders||[];const _e=Fe.budgetTracking||Fe.budget_tracking||null,Xe=Fe.invoice||null,lt=Fe.creditNote||Fe.credit_note||null,Nt=Fe.completionExpenses||Fe.completion_expenses||null;Pe&&(Pe.budgetTracking=_e,Pe.invoice=Xe,Pe.creditNote=lt,Pe.completionExpenses=Nt)}}catch(ge){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(ge==null?void 0:ge.message)||ge,status:(L=ge==null?void 0:ge.response)==null?void 0:L.status,requestId:E.requestId})}const Ae={id:E.requestNumber||E.requestId,requestId:E.requestId,title:E.title,description:E.description,priority:z,status:b(E.status),workflowType:E.workflowType||(E.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:Z,initiator:{name:((D=E.initiator)==null?void 0:D.displayName)||((R=E.initiator)==null?void 0:R.email),role:((N=E.initiator)==null?void 0:N.designation)||void 0,department:((_=E.initiator)==null?void 0:_.department)||void 0,email:((S=E.initiator)==null?void 0:S.email)||void 0,phone:((U=E.initiator)==null?void 0:U.phone)||void 0,avatar:f((F=E.initiator)==null?void 0:F.displayName,($=E.initiator)==null?void 0:$.email)},createdAt:E.createdAt,updatedAt:E.updatedAt,totalSteps:E.totalLevels||1,currentStepRaw:(Z==null?void 0:Z.currentLevel)||E.currentLevel||1,currentStep:Math.min(Math.max(1,(Z==null?void 0:Z.currentLevel)||E.currentLevel||1),E.totalLevels||1),approvalFlow:re,approvals:W,documents:ve,spectators:G,auditTrail:Te,conclusionRemark:E.conclusionRemark||null,closureDate:E.closureDate||null,pauseInfo:Ke||null,claimDetails:Pe||null,proposalDetails:$e||null,completionDetails:ne||null,internalOrder:he||null,internalOrders:Ne||[],budgetTracking:(Pe==null?void 0:Pe.budgetTracking)||null,invoice:(Pe==null?void 0:Pe.invoice)||null,creditNote:(Pe==null?void 0:Pe.creditNote)||null,completionExpenses:(Pe==null?void 0:Pe.completionExpenses)||null,templateType:E.templateType||E.template_type,form16Submission:I.form16Submission||null};n(Ae);const Q=(P=a==null?void 0:a.email)==null?void 0:P.toLowerCase(),le=W.find(ge=>{const Fe=(ge.status||"").toString().toUpperCase(),_e=(ge.approverEmail||"").toLowerCase(),Xe=ge.levelNumber||0;return(Fe==="PENDING"||Fe==="IN_PROGRESS"||Fe==="PAUSED")&&_e===Q&&Xe===K});x(le||null);const pe=a==null?void 0:a.userId;if(pe){const ge=V.some(Fe=>(Fe.participantType||"").toUpperCase()==="SPECTATOR"&&Fe.userId===pe);g(ge)}else g(!1)}catch(I){if(console.error("[useRequestDetails] Error loading request details:",I),C){if(((T=I==null?void 0:I.response)==null?void 0:T.status)===403){const E=((B=(k=I==null?void 0:I.response)==null?void 0:k.data)==null?void 0:B.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:E})}n(null)}}finally{C&&c(!1)}})(),()=>{C=!1}},[t,a]);const y=h.useMemo(()=>{if(r)return r;const C=s.find(A=>A.id===t||A.requestNumber===t||A.request_number===t);return C||null},[t,s,r]),w=h.useMemo(()=>{var L,D,R;if(!y||!a)return!1;const C=(L=a==null?void 0:a.email)==null?void 0:L.toLowerCase(),A=(R=(D=y.initiator)==null?void 0:D.email)==null?void 0:R.toLowerCase();return C===A},[y,a]),v=h.useMemo(()=>{var A;if(!y)return[];const C=[];return(A=y.initiator)!=null&&A.email&&C.push({email:y.initiator.email.toLowerCase(),participantType:"INITIATOR",name:y.initiator.name}),y.approvalFlow&&Array.isArray(y.approvalFlow)&&y.approvalFlow.forEach(L=>{L.approverEmail&&C.push({email:L.approverEmail.toLowerCase(),participantType:"APPROVER",name:L.approver})}),y.spectators&&Array.isArray(y.spectators)&&y.spectators.forEach(L=>{L.email&&C.push({email:L.email.toLowerCase(),participantType:"SPECTATOR",name:L.name})}),y.participants&&Array.isArray(y.participants)&&y.participants.forEach(L=>{const D=(L.userEmail||L.email||"").toLowerCase(),R=(L.participantType||L.participant_type||"").toUpperCase(),N=L.userName||L.user_name||L.name;D&&R&&!C.find(_=>_.email===D)&&C.push({email:D,participantType:R,name:N})}),C},[y]);return h.useEffect(()=>{if(!t||!r)return;const C=en();if(!C)return;const A=L=>{((L==null?void 0:L.requestId)===r.requestId||(L==null?void 0:L.requestNumber)===t)&&j()};return C.on("request:updated",A),()=>{C.off("request:updated",A)}},[t,r,j]),{request:y,apiRequest:r,loading:o,refreshing:i,refreshDetails:j,currentApprovalLevel:p,isSpectator:u,isInitiator:w,existingParticipants:v,accessDenied:d}}function Jg(t,s,a,r){const[n,i]=h.useState([]),[l,o]=h.useState(0),[c,d]=h.useState([]);return h.useEffect(()=>{if(!t){console.warn("[useRequestSocket] No requestIdentifier, cannot join socket room");return}let m=!0,p=t;return(async()=>{var f;try{const b=await Gs.getWorkflowDetails(t);(f=b==null?void 0:b.workflow)!=null&&f.requestId&&m&&(p=b.workflow.requestId)}catch(b){console.error("[useRequestSocket] Failed to resolve UUID:",b)}if(!m)return;const x=en();if(!x){console.error("[useRequestSocket] Socket not available");return}const u=r==null?void 0:r.userId,g=()=>{mo(x,p,u)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),Wh(x,p))}})(),()=>{m=!1}},[t,r]),h.useEffect(()=>{!t||!s||(async()=>{try{const m=await Zr(t),p=s.auditTrail||[],x=[...m,...p];x.sort((u,g)=>{const f=new Date(u.createdAt||u.created_at||u.timestamp||0).getTime(),b=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return f-b}),i(x)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),h.useEffect(()=>{if(!t)return;const m=en();if(!m)return;const p=u=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await Zr(t),f=(s==null?void 0:s.auditTrail)||[],b=[...g,...f].sort((j,y)=>{const w=new Date(j.createdAt||j.created_at||j.timestamp||0).getTime(),v=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime();return w-v});i(b)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},x=u=>{const g=u.type==="breach"?"⏰":u.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const f=await Gs.getWorkflowDetails(t);f&&(Array.isArray(f.tatAlerts)&&f.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(f){console.error("[useRequestSocket] Failed to refresh after TAT alert:",f)}})()};return m.on("noteHandler",p),m.on("worknote:new",p),m.on("tat:alert",x),()=>{m.off("noteHandler",p),m.off("worknote:new",p),m.off("tat:alert",x)}},[t,a,s]),h.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function Rn(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}}const vT=["MALWARE_DETECTED","FILE_VALIDATION_FAILED","CONTENT_THREAT_DETECTED","SCAN_UNAVAILABLE","SCAN_ERROR"],NT={MALWARE_DETECTED:"🛑 Malware Detected",FILE_VALIDATION_FAILED:"⛔ File Rejected",CONTENT_THREAT_DETECTED:"⚠️ Malicious Content Detected",SCAN_UNAVAILABLE:"🔒 Security Scan Unavailable",SCAN_ERROR:"❌ Security Scan Error"};function zc(t){var l,o,c,d;const s=(l=t==null?void 0:t.response)==null?void 0:l.data;if(!(s!=null&&s.error))return!1;const a=s.error;if(!vT.includes(a))return!1;const r=NT[a]||"Security Error",n=s.message||"File was blocked by security scan";let i="";return s.details&&((o=s.details.signatures)!=null&&o.length?i=`Virus: ${s.details.signatures.join(", ")}`:(c=s.details.errors)!=null&&c.length?i=s.details.errors[0]||"":(d=s.details.threats)!=null&&d.length&&(i=s.details.threats.map(m=>m.description).join(", "))),X.error(r,{description:i||n,duration:8e3,style:{background:"#fef2f2",border:"1px solid #fca5a5",color:"#991b1b"}}),!0}function Zg(t,s){const[a,r]=h.useState(!1),[n,i]=h.useState(null),[l,o]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=h.useState({show:!1,errors:[]});h.useEffect(()=>{(async()=>{try{const g=await la("DOCUMENT_POLICY"),f={};g.forEach(w=>{f[w.configKey]=w.configValue});const b=parseInt(f.MAX_FILE_SIZE_MB||"10"),y=(f.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(w=>w.trim().toLowerCase());o({maxFileSizeMB:b,allowedFileTypes:y})}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 f=u.name.toLowerCase(),b=f.substring(f.lastIndexOf(".")+1);return l.allowedFileTypes.includes(b)?{valid:!0}:{valid:!1,reason:`File type "${b}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},p=async u=>{var y,w;const g=u.target.files;if(!g||g.length===0)return;const f=Array.from(g),b=[],j=[];if(f.forEach(v=>{const C=m(v);C.valid?j.push(v):b.push({fileName:v.name,reason:C.reason||"Unknown validation error"})}),b.length>0&&d({show:!0,errors:b}),j.length===0){u.target&&(u.target.value="");return}r(!0);try{const v=j[0],C=t==null?void 0:t.requestId;if(!C){X.error("Request ID not found");return}v&&await Rn(v,C,"SUPPORTING"),await s(),j.length{const u=document.createElement("input");u.type="file",u.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),u.onchange=p,u.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}const wT="modulepreload",CT=function(t){return"/"+t},Nx={},Wl=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=CT(c),c in Nx)return;Nx[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const p=document.createElement("link");if(p.rel=d?"stylesheet":wT,d||(p.as="script"),p.crossOrigin="",p.href=c,o&&p.setAttribute("nonce",o),document.head.appendChild(p),d)return new Promise((x,u)=>{p.addEventListener("load",x),p.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 qg(t,s,a,r,n,i,l){const[o,c]=h.useState(""),[d,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(!1),[f,b]=h.useState(0),[j,y]=h.useState(!1),[w,v]=h.useState(!1),[C,A]=h.useState(0),L=async()=>{var S;const N=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),_=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(N||_){c(N||_),g(!!_);return}try{const{getConclusion:U}=await Wl(async()=>{const{getConclusion:$}=await import("./conclusionApi-DRbYq2Mu.js");return{getConclusion:$}},__vite__mapDeps([0,1,2,3,4,5,6,7])),F=await U(t.requestId||s);F&&(F.aiGeneratedRemark||F.finalRemark)&&(c(F.finalRemark||F.aiGeneratedRemark||""),g(!!F.aiGeneratedRemark))}catch(U){((S=U==null?void 0:U.response)==null?void 0:S.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",U)}},D=async()=>{if(!w)try{m(!0),y(!1);const{generateConclusion:N}=await Wl(async()=>{const{generateConclusion:F}=await import("./conclusionApi-DRbYq2Mu.js");return{generateConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7])),_=await N(t.requestId||s),S=f+1;if(b(S),!(_!=null&&_.aiGeneratedRemark)||_.aiGeneratedRemark.toLowerCase().includes("unable to generate")||_.aiGeneratedRemark.toLowerCase().includes("sorry")){const F=C+1;A(F),F>=2?(v(!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((_==null?void 0:_.aiGeneratedRemark)||""),g(!1);return}c(_.aiGeneratedRemark),g(!0),A(0),S>=2&&(v(!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 _=C+1;A(_),g(!1),_>=2?(v(!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)}},R=async()=>{var _,S;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:U}=await Wl(async()=>{const{finalizeConclusion:F}=await import("./conclusionApi-DRbYq2Mu.js");return{finalizeConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await U(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(U){i==null||i({success:!1,title:"Error",message:((S=(_=U.response)==null?void 0:_.data)==null?void 0:S.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{x(!1)}};return h.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 S=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),U=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);S||U?(c(S||U),g(!!U)):L()},[t==null?void 0:t.status,t==null?void 0:t.conclusionRemark,t==null?void 0:t.aiGeneratedConclusion,a,o]),{conclusionRemark:o,setConclusionRemark:c,conclusionLoading:d,conclusionSubmitting:p,aiGenerated:u,handleGenerateConclusion:D,handleFinalizeConclusion:R,generationAttempts:f,generationFailed:j,maxAttemptsReached:w}}function e0(t,s,a){const[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState(!1),[d,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(!1),[f,b]=h.useState(null),[j,y]=h.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:p,setShowSkipApproverModal:x,showActionStatusModal:u,setShowActionStatusModal:g,skipApproverData:f,setSkipApproverData:b,actionStatus:j,setActionStatus:y,handleApproveConfirm:async D=>{var N,_;const R=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!R){alert("Approval level not found");return}await Tn(t,R,D||""),await new Promise(S=>setTimeout(S,500)),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(_=window==null?void 0:window.toast)==null||_.call(window,"Approved successfully")},handleRejectConfirm:async D=>{var N,_;if(!(D!=null&&D.trim())){alert("Comments & remarks are required");return}const R=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!R){alert("Approval level not found");return}await wr(t,R,D.trim(),D.trim()),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(_=window==null?void 0:window.toast)==null||_.call(window,"Rejected successfully")},handleAddApprover:async(D,R,N)=>{var _,S;try{await lp(t,D,R,N),await a(),c(!1),y==null||y({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${R}h TAT`}),g==null||g(!0)}catch(U){throw y==null||y({success:!1,title:"Failed to Add Approver",message:((S=(_=U==null?void 0:U.response)==null?void 0:_.data)==null?void 0:S.error)||"Failed to add approver. Please try again."}),g==null||g(!0),U}},handleSkipApprover:async D=>{var R,N;if(f)try{await Tw(t,f.levelId,D),await a(),x(!1),b(null),y==null||y({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),g==null||g(!0)}catch(_){throw y==null||y({success:!1,title:"Failed to Skip Approver",message:((N=(R=_==null?void 0:_.response)==null?void 0:R.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),_}},handleAddSpectator:async D=>{var R,N;try{await op(t,D),await a(),m(!1),y==null||y({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),g==null||g(!0)}catch(_){throw y==null||y({success:!1,title:"Failed to Add Spectator",message:((N=(R=_==null?void 0:_.response)==null?void 0:R.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),_}}}}function ST({requestId:t,request:s,onRefresh:a}){const[r,n]=h.useState(null),[i,l]=h.useState(!0),[o,c]=h.useState(null),[d,m]=h.useState(!1),[p,x]=h.useState(""),u=s==null?void 0:s.form16Submission,g=!!u,f=!!r&&r.status!=="withdrawn",b=(u==null?void 0:u.tdsAmount)!=null?Number(u.tdsAmount):void 0;h.useEffect(()=>{if(!t){l(!1);return}let v=!1;return(async()=>{try{const C=await co(t);v||n(C?{id:typeof C.id=="number"?C.id:Number(C.id),status:C.status||""}:null)}catch{v||n(null)}finally{v||l(!1)}})(),()=>{v=!0}},[t]);const j=async()=>{if(!(!t||!window.confirm("Cancel this Form 16 submission? The request will be marked as rejected."))){c("cancel");try{await vy(t),X.success("Submission cancelled"),a==null||a()}catch(v){X.error(v instanceof Error?v.message:"Failed to cancel submission")}finally{c(null)}}},y=async()=>{if(!(!t||!window.confirm("Mark this submission as resubmission needed? The dealer will need to resubmit Form 16."))){c("resubmit");try{await Ny(t),X.success("Marked as resubmission needed"),a==null||a()}catch(v){X.error(v instanceof Error?v.message:"Failed to update")}finally{c(null)}}},w=async()=>{const v=parseFloat(p);if(!t||Number.isNaN(v)||v<=0){X.error("Enter a valid amount to generate credit note");return}c("credit");try{await wy(t,v),m(!1),x(""),X.success("Credit note generated (manually approved)");const C=await co(t);n(C?{id:typeof C.id=="number"?C.id:Number(C.id),status:C.status||""}:null),a==null||a()}catch(C){X.error(C instanceof Error?C.message:"Failed to generate credit note")}finally{c(null)}};return i||!g||f?null:e.jsxs(e.Fragment,{children:[e.jsxs(q,{className:"border-blue-200 bg-blue-50/30","data-testid":"form16-quick-actions-card",children:[e.jsxs(oe,{className:"pb-2",children:[e.jsxs(de,{className:"text-sm flex items-center gap-2 text-blue-800",children:[e.jsx(Pt,{className:"w-4 h-4"}),"Form 16 actions"]}),e.jsx(ye,{className:"text-xs text-gray-600",children:"View the document in the Documents tab. Cancel submission, mark resubmission needed, or generate credit note (e.g. when OCR was partial)."})]}),e.jsxs(ee,{className:"space-y-2",children:[e.jsxs(M,{variant:"outline",size:"sm",className:"w-full justify-start border-red-300 text-red-700 hover:bg-red-50",onClick:j,disabled:!!o,children:[o==="cancel"?e.jsx(Qe,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(jt,{className:"w-3 h-3 mr-1"}),"Cancel submission"]}),e.jsxs(M,{variant:"outline",size:"sm",className:"w-full justify-start border-amber-300 text-amber-700 hover:bg-amber-50",onClick:y,disabled:!!o,children:[o==="resubmit"?e.jsx(Qe,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(dh,{className:"w-3 h-3 mr-1"}),"Resubmission needed"]}),e.jsxs(M,{variant:"outline",size:"sm",className:"w-full justify-start border-emerald-300 text-emerald-700 hover:bg-emerald-50",onClick:()=>{x(b!=null?String(b):""),m(!0)},disabled:!!o,children:[o==="credit"?e.jsx(Qe,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(Pt,{className:"w-3 h-3 mr-1"}),"Generate credit note"]})]})]}),e.jsx(ht,{open:d,onOpenChange:m,children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(ut,{children:"Generate credit note (manual)"}),e.jsx(_t,{children:"Enter the amount for the credit note. This will mark the Form 16 as manually approved."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(te,{htmlFor:"form16-cn-amount",children:"Amount (₹)"}),e.jsx(Ce,{id:"form16-cn-amount",type:"number",min:"0",step:"0.01",placeholder:b!=null?String(b):"0",value:p,onChange:v=>x(v.target.value)}),b!=null&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Suggested from submission TDS amount: ₹",b.toLocaleString("en-IN")]})]})}),e.jsxs(Et,{children:[e.jsx(M,{variant:"outline",onClick:()=>m(!1),disabled:!!o,children:"Cancel"}),e.jsxs(M,{onClick:w,disabled:!!o||!p.trim(),children:[o==="credit"?e.jsx(Qe,{className:"w-4 h-4 animate-spin mr-2"}):null,"Generate credit note"]})]})]})})]})}const AT=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 Er({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(Ie,{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 "]}),gs(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&AT(t.fileType)&&s&&e.jsx(M,{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(St,{className:"w-4 h-4"})}),a&&e.jsx(M,{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(Rt,{className:"w-4 h-4"})})]})]})}function TT({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l}){var c,d,m,p;const o=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16";return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[o&&((d=(c=t==null?void 0:t.form16Submission)==null?void 0:c.previousDocuments)==null?void 0:d.length)>0&&e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base text-amber-800",children:[e.jsx(Ie,{className:"w-4 h-4 sm:w-5 sm:h-5 text-amber-600"}),"Previous submission(s) – same quarter"]}),e.jsxs(ye,{className:"text-xs sm:text-sm mt-1",children:["Documents from earlier Form 16A submissions for this request's financial year and quarter only (",(m=t==null?void 0:t.form16Submission)==null?void 0:m.financialYear," ",(p=t==null?void 0:t.form16Submission)==null?void 0:p.quarter,")"]})]}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-4",children:(()=>{const x=new Map;for(const u of t.form16Submission.previousDocuments){const g=u.requestId||u.request_id,f=u.requestNumber||g;x.has(f)||x.set(f,[]),x.get(f).push(u)}return Array.from(x.entries()).map(([u,g])=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600",children:["Request ",u]}),e.jsx("div",{className:"space-y-2 pl-2 border-l-2 border-amber-200",children:g.map((f,b)=>{const j=f.documentId??f.document_id,y=f.originalFileName??f.original_file_name??f.fileName??f.file_name??"Document",w=Number(f.fileSize??f.file_size??0),v=w>0?(w/(1024*1024)).toFixed(2)+" MB":"—";return e.jsx(Er,{document:{documentId:j,name:y,fileType:f.fileType??f.file_type??"",size:v,sizeBytes:w,uploadedBy:f.uploadedBy??f.uploaded_by,uploadedAt:f.uploadedAt??f.uploaded_at},onPreview:C=>i(C),onDownload:l,testId:"form16-previous-document"},j||b)})})]},u))})()})})]}),e.jsxs(q,{children:[e.jsx(oe,{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(de,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ie,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),o?"Current submission":"Request Documents"]}),e.jsx(ye,{className:"text-xs sm:text-sm mt-1",children:o?"Documents for this Form 16A submission":"Documents attached while creating the request"})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsxs(M,{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(js,{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(ee,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((x,u)=>e.jsx(Er,{document:x,onPreview:g=>i(g),onDownload:l,testId:"request-document"},u))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-documents",children:"No documents uploaded yet"})})]}),!o&&e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Hs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(ye,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(ee,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((x,u)=>e.jsx(Er,{document:{documentId:x.attachmentId||"",name:x.name,fileType:x.type||"",size:x.size?`${(x.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:x.size,uploadedBy:x.uploadedBy,uploadedAt:x.uploadedAt},onPreview:g=>i(g),onDownload:async g=>{const{downloadWorkNoteAttachment:f}=require("@/services/workflowApi");await f(g)},testId:"worknote-attachment"},x.attachmentId||u))}):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 kT=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"}}},wx=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending",icon:st,iconColor:"text-yellow-600"};case"paused":return{color:"bg-gray-400 text-gray-100 border-gray-500",label:"paused",icon:es,iconColor:"text-gray-600"};case"in-review":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"in-review",icon:Ut,iconColor:"text-blue-600"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:Oe,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected",icon:At,iconColor:"text-red-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-300",label:"closed",icon:Oe,iconColor:"text-gray-600"};case"skipped":return{color:"bg-orange-100 text-orange-800 border-orange-200",label:"skipped",icon:$t,iconColor:"text-orange-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:es,iconColor:"text-gray-600"}}},RT=t=>{switch(t){case"approval":case"approved":return e.jsx(Oe,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(At,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(Hs,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(Ut,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(Qi,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Ie,{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(Wi,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(es,{className:"w-5 h-5 text-amber-600"});default:return e.jsx($t,{className:"w-5 h-5 text-gray-600"})}};function DT(t){const s=t==null?void 0:t.form16Submission;if(!s)return[];const a=[],r=Array.isArray(s.previousSubmissions)?s.previousSubmissions:[];for(const u of r){const g=u.requestNumber||u.requestId||"",f=u.submittedDate?new Date(u.submittedDate).toISOString():new Date().toISOString();if(a.push({type:"document_added",action:`Previous submission (${g})`,details:"Form 16A certificate was submitted for this FY and quarter.",timestamp:f}),u.creditNoteNumber){const b=u.creditNoteIssueDate?new Date(u.creditNoteIssueDate).toISOString():f;a.push({type:"status_change",action:"Credit note issued",details:`Credit note ${u.creditNoteNumber} issued for previous submission (${g}).`,timestamp:b})}}const n=s.submittedDate||(t==null?void 0:t.submittedDate)||(t==null?void 0:t.createdAt),i=n?new Date(n).toISOString():new Date().toISOString(),l=(s.validationStatus||"").toLowerCase(),o=s.validationNotes||""||"",c=(s.displayStatus||"").toLowerCase(),d=!!(s.ocrExtractedData&&typeof s.ocrExtractedData=="object"&&Object.keys(s.ocrExtractedData).length>0),m=!!s.creditNoteNumber,p=c==="balance mismatch"||l==="failed"&&!m||l==="failed"&&/mismatch|26as|value/i.test(o),x=c==="duplicate"||l==="duplicate";return a.push({type:"document_added",action:"Form 16A uploaded",details:"Form 16A certificate was uploaded and received.",timestamp:i}),a.push({type:"created",action:"OCR extraction",details:d?"Certificate data was extracted from the uploaded PDF.":"OCR extraction was performed on the uploaded document.",timestamp:i}),p?a.push({type:"rejection",action:"26AS matching",details:"Values of Form 16 did not match with 26AS. Please submit Form 16 with correct data.",timestamp:i}):x?a.push({type:"rejection",action:"26AS matching",details:"Duplicate. A submission for this FY and quarter already exists; credit note was issued for the earlier submission.",timestamp:i}):a.push({type:"status_change",action:"26AS matching",details:l==="success"||s.creditNoteNumber?"26AS matching completed. Credit note generated.":"26AS matching was performed.",timestamp:i}),a.sort((u,g)=>new Date(u.timestamp).getTime()-new Date(g.timestamp).getTime())}function FT({request:t}){const s=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",a=s?DT(t):[],r=t.auditTrail&&Array.isArray(t.auditTrail)?t.auditTrail:[],n=a.length>0?[...a,...r].sort((i,l)=>{const o=i.timestamp?new Date(i.timestamp).getTime():0,c=l.timestamp?new Date(l.timestamp).getTime():0;return o-c}):r;return e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx($t,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(ye,{className:"text-xs sm:text-sm",children:s?"Form 16 submission steps and audit trail":"Complete audit trail of all request activities"})]}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-4 sm:space-y-6",children:n.length>0?n.map((i,l)=>e.jsxs("div",{className:"flex items-start gap-4","data-testid":`activity-item-${l}`,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${i.type==="rejection"?"bg-red-50":"bg-gray-100"}`,children:RT(i.type)})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:`rounded-lg border p-4 shadow-sm ${i.type==="rejection"?"bg-red-50/50 border-red-200":"bg-white border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:`font-semibold ${i.type==="rejection"?"text-red-900":"text-gray-900"}`,children:i.action}),e.jsx("span",{className:"text-xs text-gray-500 whitespace-nowrap ml-4",children:gs(i.timestamp)})]}),e.jsx("div",{className:`text-sm leading-relaxed ${i.type==="rejection"?"text-red-800":"text-gray-600"}`,children:e.jsx("p",{className:"whitespace-pre-line break-words",children:i.details})})]})})]},l)):e.jsxs("div",{className:"text-center py-12","data-testid":"no-activity",children:[e.jsx($t,{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 t0({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsx(pt,{children:e.jsxs(ut,{className:"flex items-center gap-2",children:[a?e.jsx(Oe,{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(Oe,{className:"w-8 h-8 text-green-600"})}),e.jsx("p",{className:"text-sm text-gray-700",children:n||"Operation completed successfully!"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-red-100 flex items-center justify-center mb-4",children:e.jsx(At,{className:"w-8 h-8 text-red-600"})}),e.jsx("p",{className:"text-sm text-gray-700",children:n||"Operation failed. Please try again."})]})})}),e.jsx(Et,{children:e.jsx(M,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function s0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=h.useState(""),[l,o]=h.useState(!1),[c,d]=h.useState([]),[m,p]=h.useState(!1),[x,u]=h.useState(null),g=h.useRef(null),f=h.useRef(null),[b,j]=h.useState({open:!1,type:"error",email:"",message:""}),[y,w]=h.useState({open:!1,violations:[]}),[v,C]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});h.useEffect(()=>{t&&(async()=>{var _;try{const S=await la("WORKFLOW_SHARING"),U=await la("TAT_SETTINGS"),F=[...S,...U],$={};F.forEach(P=>{$[P.configKey]=P.configValue}),C({maxApprovalLevels:parseInt($.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt($.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((_=$.ALLOW_ADD_SPECTATOR)==null?void 0:_.toLowerCase())==="true",maxSpectators:parseInt($.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(S){console.error("Failed to load system policy:",S)}})()},[t]);const A=async()=>{var T,k;const N=n.trim().toLowerCase();if(!N){j({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(N)){j({open:!0,type:"error",email:N,message:"Please enter a valid email address"});return}const S=r.find(B=>(B.email||"").toLowerCase()===N);if(S){const B=((T=S.participantType)==null?void 0:T.toUpperCase())||"PARTICIPANT",I=S.name||N;if(B==="INITIATOR"){j({open:!0,type:"error",email:N,message:`${I} is the request initiator and cannot be added as a spectator.`});return}else if(B==="APPROVER"){j({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(B==="SPECTATOR"){j({open:!0,type:"error",email:N,message:`${I} is already a spectator on this request.`});return}else{j({open:!0,type:"error",email:N,message:`${I} is already a participant on this request.`});return}}const U=[];v.allowSpectators||U.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const $=r.filter(B=>(B.participantType||"").toUpperCase()==="SPECTATOR").length;$>=v.maxSpectators&&U.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:$,maxValue:v.maxSpectators});const P=r.length+1;if(P>v.maxParticipants&&U.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:P,maxValue:v.maxParticipants}),U.length>0){w({open:!0,violations:U});return}if(!x||x.email.toLowerCase()!==N)try{const I=((k=(await ba(N,1)).data)==null?void 0:k.data)||[];if(I.length===0){j({open:!0,type:"not-found",email:N,message:""});return}const E=I[0];await ga({userId:E.userId,email:E.email,displayName:E.displayName,firstName:E.firstName,lastName:E.lastName,department:E.department,phone:E.phone,mobilePhone:E.mobilePhone,designation:E.designation,jobTitle:E.jobTitle,manager:E.manager,employeeId:E.employeeId,employeeNumber:E.employeeNumber,secondEmail:E.secondEmail,location:E.location})}catch(B){console.error("Failed to validate spectator:",B),j({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(B){console.error("Failed to add spectator:",B)}finally{o(!1)}},L=()=>{l||(i(""),u(null),d([]),p(!1),s())};h.useEffect(()=>{c.length>0&&f.current&&f.current.scrollTo({top:f.current.scrollHeight,behavior:"smooth"})},[c.length]),h.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([]),p(!1);return}p(!0),g.current=setTimeout(async()=>{var _;try{const S=N.slice(1),F=((_=(await ba(S,10)).data)==null?void 0:_.data)||[];d(F)}catch(S){console.error("Search failed:",S),d([])}finally{p(!1)}},300)},R=async N=>{try{await ga({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([]),p(!1)}catch(_){console.error("Failed to ensure user exists:",_),j({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ht,{open:t,onOpenChange:L,children:[e.jsxs(mt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:L,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:l,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(pt,{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(St,{className:"w-5 h-5 text-purple-600"})}),e.jsx(ut,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:f,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a spectator to this request. They will receive notifications but cannot approve or reject."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(Xi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ce,{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:()=>R(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ls,{className:"h-8 w-8",children:e.jsx(os,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(N.displayName||N.email).split(" ").map(_=>_[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(M,{type:"button",variant:"outline",onClick:L,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(M,{type:"button",onClick:A,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(St,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(ht,{open:b.open,onOpenChange:N=>j(_=>({..._,open:N})),children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(ut,{className:"flex items-center gap-2",children:b.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(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[b.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:b.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Ki,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),b.type==="error"&&e.jsxs(e.Fragment,{children:[b.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:b.email}),"."]}),b.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:b.message})})]})]})})]}),e.jsx(Et,{children:e.jsx(M,{onClick:()=>j(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(ti,{open:y.open,onClose:()=>w({open:!1,violations:[]}),violations:y.violations,policyDetails:{maxApprovalLevels:v.maxApprovalLevels,maxParticipants:v.maxParticipants,allowSpectators:v.allowSpectators,maxSpectators:v.maxSpectators}})]})}function a0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=h.useState(""),[d,m]=h.useState(24),[p,x]=h.useState(null),[u,g]=h.useState(!1),[f,b]=h.useState([]),[j,y]=h.useState(!1),[w,v]=h.useState(null),C=h.useRef(null),A=h.useRef(null),[L,D]=h.useState({open:!1,type:"error",email:"",message:""}),R=n.filter(k=>k&&(k.status==="approved"||k.status==="rejected"||k.status==="skipped")),N=Math.max(1,R.length+1),_=Math.max(1,n.length+1),S=_>=N?Array.from({length:_-N+1},(k,B)=>N+B):[N];h.useEffect(()=>{S.length>0&&p===null&&x(S[0]||null)},[S.length,p]);const U=async()=>{var V,Y;const k=o.trim().toLowerCase();if(!k){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(k)){D({open:!0,type:"error",email:k,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(!p){D({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(p0?Math.max(...n.map(Z=>Z.levelNumber),0):0,E=p>I?p:I+1;if(i&&E>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${p} would result in ${E} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:E,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(Z=>(Z.email||"").toLowerCase()===k);if(W){const Z=((V=W.participantType)==null?void 0:V.toUpperCase())||"PARTICIPANT",O=W.name||k;if(Z==="INITIATOR"){D({open:!0,type:"error",email:k,message:`${O} is the request initiator and cannot be added as an approver.`});return}else if(Z==="APPROVER"){D({open:!0,type:"error",email:k,message:`${O} is already an approver on this request.`});return}else if(Z==="SPECTATOR"){D({open:!0,type:"error",email:k,message:`${O} 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:k,message:`${O} is already a participant on this request.`});return}}if(!w||w.email.toLowerCase()!==k)try{const O=((Y=(await ba(k,1)).data)==null?void 0:Y.data)||[];if(O.length===0){D({open:!0,type:"not-found",email:k,message:""});return}const z=O[0];await ga({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(Z){console.error("Failed to validate approver:",Z),D({open:!0,type:"error",email:k,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(k,d,p),c(""),m(24),x(null),v(null),s()}catch(Z){console.error("Failed to add approver:",Z)}finally{g(!1)}},F=()=>{u||(c(""),m(24),x(null),v(null),b([]),y(!1),s())},$=k=>{const B=k.toLowerCase();return B==="approved"?e.jsx(Oe,{className:"w-4 h-4 text-green-600"}):B==="rejected"?e.jsx(At,{className:"w-4 h-4 text-red-600"}):B==="skipped"?e.jsx(Ze,{className:"w-4 h-4 text-orange-600"}):B==="in-review"||B==="pending"?e.jsx(st,{className:"w-4 h-4 text-blue-600"}):e.jsx(st,{className:"w-4 h-4 text-gray-400"})};h.useEffect(()=>{f.length>0&&A.current&&A.current.scrollTo({top:A.current.scrollHeight,behavior:"smooth"})},[f.length]),h.useEffect(()=>()=>{C.current&&clearTimeout(C.current)},[]);const P=k=>{if(c(k),w&&w.email.toLowerCase()!==k.toLowerCase()&&v(null),C.current&&clearTimeout(C.current),!k||!k.startsWith("@")||k.length<2){b([]),y(!1);return}y(!0),C.current=setTimeout(async()=>{var B;try{const I=k.slice(1),W=((B=(await ba(I,10)).data)==null?void 0:B.data)||[];b(W)}catch(I){console.error("Search failed:",I),b([])}finally{y(!1)}},300)},T=async k=>{try{await ga({userId:k.userId,email:k.email,displayName:k.displayName,firstName:k.firstName,lastName:k.lastName,department:k.department,phone:k.phone,mobilePhone:k.mobilePhone,designation:k.designation,jobTitle:k.jobTitle,manager:k.manager,employeeId:k.employeeId,employeeNumber:k.employeeNumber,secondEmail:k.secondEmail,location:k.location}),c(k.email),v(k),b([]),y(!1)}catch(B){console.error("Failed to ensure user exists:",B),D({open:!0,type:"error",email:k.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ht,{open:t,onOpenChange:F,children:[e.jsxs(mt,{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(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(pt,{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(Jt,{className:"w-5 h-5 text-blue-600"})}),e.jsx(ut,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:A,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(k=>k.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(k=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${k.status==="approved"?"bg-green-100 border border-green-200":k.status==="rejected"?"bg-red-100 border border-red-200":k.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:k.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:k.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[k.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[$(k.status),e.jsx(ae,{variant:"outline",className:`text-xs ${k.status==="approved"?"bg-green-50 text-green-700 border-green-300":k.status==="rejected"?"bg-red-50 text-red-700 border-red-300":k.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:k.status})]})]},k.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(te,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(He,{value:(p==null?void 0:p.toString())||"",onValueChange:k=>x(Number(k)),disabled:u,children:[e.jsx(Ge,{className:"h-11 border-gray-300",children:e.jsx(We,{placeholder:"Select level"})}),e.jsx(Ye,{children:S.map(k=>e.jsx(J,{value:k.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",k]}),k<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",k,")"]})]})},k))})]}),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(te,{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(Ce,{type:"number",min:"1",max:"720",value:d,onChange:k=>m(Number(k.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(Xi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ce,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:k=>P(k.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(j||f.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:j?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):f.length>0?e.jsx("ul",{className:"divide-y",children:f.map(k=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>T(k),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ls,{className:"h-8 w-8",children:e.jsx(os,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(k.displayName||k.email).split(" ").map(B=>B[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:k.displayName||[k.firstName,k.lastName].filter(Boolean).join(" ")||k.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:k.email}),k.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:k.designation})]})]})},k.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(M,{type:"button",variant:"outline",onClick:F,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(M,{type:"button",onClick:U,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!o.trim()||!p||!d,children:[e.jsx(Jt,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${p||"?"}`]})]})]}),e.jsx(ht,{open:L.open,onOpenChange:k=>D(B=>({...B,open:k})),children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(ut,{className:"flex items-center gap-2",children:L.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(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[L.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:L.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(Ki,{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."]})})]}),L.type==="error"&&e.jsxs(e.Fragment,{children:[L.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:L.email}),"."]}),L.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:L.message})})]})]})})]}),e.jsx(Et,{children:e.jsx(M,{onClick:()=>D(k=>({...k,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const IT=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"}},PT=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},ET=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 Ra(s)},_T=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",Cx=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Ie,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(uh,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Ie,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Ie,{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(hi,{className:`${s} text-purple-600`}):e.jsx(Wi,{className:`${s} text-gray-600`})};function r0({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:c=[],onAddApprover:d,maxApprovalLevels:m,onPolicyViolation:p}){const x=_a(),u=t||x.requestId||"",[g,f]=h.useState(""),[b,j]=h.useState(""),[y,w]=h.useState(!1),[v,C]=h.useState([]),[A,L]=h.useState(!1),[D,R]=h.useState([]),[N,_]=h.useState(null),[S,U]=h.useState(null),[F,$]=h.useState(!1),[P,T]=h.useState(!1),[k,B]=h.useState(!1),[I,E]=h.useState({success:!0,title:"",message:""}),W=h.useRef(null),V=h.useRef(null),Y=h.useRef(null),Z=h.useRef(!1),[O,z]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[K,re]=h.useState({open:!1,errors:[]}),G=h.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[se,ve]=h.useState([]),Te=se.filter(ie=>ie.status==="online"),Ke=v.filter(ie=>ie.content.toLowerCase().includes(b.toLowerCase())||ie.user.name.toLowerCase().includes(b.toLowerCase())),Je=h.useMemo(()=>o!==void 0?o:!N||se.length===0?!1:se.some(ie=>{const Re=ie.userId||ie.user_id,ce=(ie.role||"").toString().toUpperCase(),Ve=(ie.participantType||ie.participant_type||"").toString().toUpperCase();return Re===N&&(ce==="SPECTATOR"||Ve==="SPECTATOR")}),[o,N,se]);h.useEffect(()=>{},[se]),h.useEffect(()=>{!u||!N||s||(async()=>{try{const ie=await Zr(u),Re=Array.isArray(ie)?ie.map(ce=>{const Ve=ce.userId||ce.user_id;return{id:ce.noteId||ce.id||String(Math.random()),user:{name:ce.userName||"User",avatar:(ce.userName||"U").slice(0,2).toUpperCase(),role:ce.userRole||"Participant"},content:ce.message||"",timestamp:ce.createdAt||new Date().toISOString(),isCurrentUser:Ve===N,attachments:Array.isArray(ce.attachments)?ce.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}}):[];C(Re)}catch(ie){console.error("[WorkNoteChat] Failed to load messages:",ie)}})()},[u,N,s]);const Pe=h.useMemo(()=>{const ie=[];return v.forEach(Re=>{Re.attachments&&Re.attachments.length>0&&Re.attachments.forEach(ce=>{ie.push({attachmentId:ce.attachmentId||ce.attachment_id,name:ce.fileName||ce.file_name||ce.name||"Untitled",fileName:ce.fileName||ce.file_name||ce.name||"Untitled",size:ce.fileSize||ce.file_size,type:ce.fileType||ce.file_type||ce.type||"file",uploadedBy:Re.user.name,uploadedAt:Re.timestamp,url:ce.storageUrl||ce.storage_url||ce.url||"#"})})}),ie},[v]);h.useEffect(()=>{i&&Pe.length>=0&&i(Pe)},[Pe,i]);const $e=h.useMemo(()=>se.map(ie=>({email:(ie.email||"").toLowerCase(),participantType:ie.role==="Initiator"?"INITIATOR":ie.role==="Approver"?"APPROVER":ie.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:ie.name})),[se]),ne=ie=>{if(!ie)return"Participant";switch(ie.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return ie.charAt(0).toUpperCase()+ie.slice(1).toLowerCase()}},he=()=>{var ie;(ie=W.current)==null||ie.scrollIntoView({behavior:"smooth"})};h.useEffect(()=>{he()},[v]);const Ne=ie=>{switch(ie.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return ie.charAt(0).toUpperCase()+ie.slice(1).toLowerCase()}};h.useEffect(()=>{Z.current||u&&(async()=>{try{const ie=await Es(u),Re=Array.isArray(ie==null?void 0:ie.participants)?ie.participants:[];if(Re.length===0)return;const ce=Re.map(ze=>{const rt=ze.participantType||ze.participant_type||"participant",qe=ze.userId||ze.user_id||"";return{name:ze.userName||ze.user_name||ze.user_email||ze.userEmail||"User",avatar:(ze.userName||ze.user_name||ze.user_email||"U").toString().split(" ").map(ot=>ot[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ne(rt.toString()),status:"offline",email:ze.userEmail||ze.user_email||"",permissions:["read","write","mention"],userId:qe}});Z.current=!0,ve(ce);let Ve=0;const Be=3,tt=()=>{Y.current&&Y.current.connected?(Y.current.emit("request:online-users",{requestId:u}),Ve++,Ve()=>{u&&(Z.current=!1)},[u]),h.useEffect(()=>{const ie=localStorage.getItem("userData");if(ie)try{const Re=JSON.parse(ie),ce=(Re==null?void 0:Re.id)||(Re==null?void 0:Re.userId)||(Re==null?void 0:Re.user_id)||null;_(ce)}catch(Re){console.error("[WorkNoteChat] Failed to parse userData:",Re)}},[]),h.useEffect(()=>{(async()=>{try{const Re=await la("DOCUMENT_POLICY"),ce={};Re.forEach(ze=>{ce[ze.configKey]=ze.configValue});const Ve=parseInt(ce.MAX_FILE_SIZE_MB||"10"),tt=(ce.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(ze=>ze.trim().toLowerCase());z({maxFileSizeMB:Ve,allowedFileTypes:tt})}catch(Re){console.error("Failed to load document policy:",Re)}})()},[]),h.useEffect(()=>{if(!N)return;let ie=u;return(async()=>{var Re;try{const ce=await Es(u);(Re=ce==null?void 0:ce.workflow)!=null&&Re.requestId&&(ie=ce.workflow.requestId)}catch{}try{const ce=en();r?ve(gt=>gt.map(Dt=>Dt.userId===N?{...Dt,status:"online"}:Dt)):(mo(ce,ie,N),ve(gt=>gt.map(Dt=>Dt.userId===N?{...Dt,status:"online"}:Dt)));const Ve=gt=>{const ct=(gt==null?void 0:gt.note)||gt;if(!ct)return;const Dt=ct.noteId||ct.id;C(vs=>{if(vs.some(Ft=>Ft.id===Dt))return vs;const ts=ct.userName||ct.user_name||"User",Sa=ct.userRole||ct.user_role,Ma=ne(Sa),Aa=ct.userId||ct.user_id,Ya={id:Dt||String(Date.now()),user:{name:ts,avatar:ts.split(" ").map(Ft=>Ft[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ma},content:ct.message||"",timestamp:ct.createdAt||new Date().toISOString(),isCurrentUser:Aa===N,attachments:Array.isArray(ct.attachments)?ct.attachments.map(Ft=>({attachmentId:Ft.attachmentId||Ft.attachment_id,name:Ft.fileName||Ft.file_name||Ft.name,fileName:Ft.fileName||Ft.file_name||Ft.name,url:Ft.storageUrl||Ft.storage_url||Ft.url||"#",type:Ft.fileType||Ft.file_type||Ft.type||"file",fileType:Ft.fileType||Ft.file_type||Ft.type||"file",fileSize:Ft.fileSize||Ft.file_size})):void 0};return[...vs,Ya]})},Be=gt=>{ve(ct=>ct.length===0||!ct.find(ts=>ts.userId===gt.userId)?ct:ct.map(ts=>ts.userId===gt.userId?{...ts,status:"online"}:ts))},tt=gt=>{gt.userId!==N&&ve(ct=>ct.length===0||!ct.find(ts=>ts.userId===gt.userId)?ct:ct.map(ts=>ts.userId===gt.userId?{...ts,status:"offline"}:ts))},ze=gt=>{ve(ct=>ct.length===0?ct:ct.map(vs=>{const ts=vs.userId||"";if(ts===N)return{...vs,status:"online"};const Ma=gt.userIds.includes(ts);return{...vs,status:Ma?"online":"offline"}}))},rt=()=>{ve(gt=>gt.map(Dt=>Dt.userId===N?{...Dt,status:"online"}:Dt)),r||mo(ce,ie,N),Z.current&&(ce.emit("request:online-users",{requestId:ie}),setTimeout(()=>ce.emit("request:online-users",{requestId:ie}),300),setTimeout(()=>ce.emit("request:online-users",{requestId:ie}),800))},qe=gt=>{console.error("[WorkNoteChat] ❌ Socket error:",gt)},ot=gt=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",gt),ve(ct=>ct.map(Dt=>Dt.userId===N?Dt:{...Dt,status:"offline"}))},Us=gt=>{gt.includes("presence")||gt.includes("worknote")||gt.includes("request")};ce.on("connect",rt),ce.on("disconnect",ot),ce.on("error",qe),ce.on("worknote:new",Ve),ce.on("presence:join",Be),ce.on("presence:leave",tt),ce.on("presence:online",ze),ce.onAny(Us),Y.current=ce,ce.connected&&Z.current&&(ce.emit("request:online-users",{requestId:ie}),setTimeout(()=>{ce.emit("request:online-users",{requestId:ie})},300),setTimeout(()=>{ce.emit("request:online-users",{requestId:ie})},800),setTimeout(()=>{ce.emit("request:online-users",{requestId:ie})},1500));const rs=()=>{ce.off("connect",rt),ce.off("disconnect",ot),ce.off("error",qe),ce.off("worknote:new",Ve),ce.off("presence:join",Be),ce.off("presence:leave",tt),ce.off("presence:online",ze),ce.offAny(Us),r||Wh(ce,ie),Y.current=null};window.__wn_cleanup=rs}catch{}})(),()=>{var Re;try{(Re=window.__wn_cleanup)==null||Re.call(window)}catch{}}},[u,N,r]);const Ae=async()=>{if(g.trim()||D.length>0){const ie=Nt(g),Re=ie.map(Be=>{const tt=se.find(ze=>ze.name.toLowerCase().includes(Be.toLowerCase()));return tt==null?void 0:tt.userId}).filter(Boolean),ce=D.map(Be=>({name:Be.name,url:URL.createObjectURL(Be),type:Be.type.split("/")[1]||"file"})),Ve={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:ie,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:ce.length>0?ce:void 0,isCurrentUser:!0};if(a)try{await a(g,D)}catch{}else try{await ip(u,{message:g,mentions:Re},D);const Be=await Zr(u),tt=Array.isArray(Be)?Be.map(ze=>{const rt=ze.userId||ze.user_id;return{id:ze.noteId||ze.id||String(Math.random()),user:{name:ze.userName||"User",avatar:(ze.userName||"U").slice(0,2).toUpperCase(),role:ze.userRole||"Participant"},content:ze.message||"",timestamp:ze.createdAt||new Date().toISOString(),isCurrentUser:rt===N,attachments:Array.isArray(ze.attachments)?ze.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}}):[];C(tt)}catch{C(Be=>[...Be,Ve])}f(""),R([])}};h.useEffect(()=>{if(s&&Array.isArray(s))try{const Re=s.filter(ce=>(ce.type||"").toLowerCase()!=="sla_warning").map(ce=>{var Be;if(ce.type||ce.activityType||ce.isSystem)return{id:ce.id||`activity-${ce.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:ce.details||ce.action||ce.content||"",timestamp:ce.timestamp||ce.createdAt||ce.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const tt=ce.userName||ce.user_name||((Be=ce.user)==null?void 0:Be.name)||"User",ze=ce.userRole||ce.user_role,rt=ne(ze),qe=ce.userId||ce.user_id;return{id:ce.noteId||ce.note_id||ce.id||String(Math.random()),user:{name:tt,avatar:tt.split(" ").map(ot=>ot[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:rt},content:ce.message||ce.content||"",timestamp:ce.createdAt||ce.created_at||ce.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(ce.attachments)?ce.attachments.map(ot=>({attachmentId:ot.attachmentId||ot.attachment_id,name:ot.fileName||ot.file_name||ot.name,fileName:ot.fileName||ot.file_name||ot.name,url:ot.storageUrl||ot.storage_url||ot.url||"#",type:ot.fileType||ot.file_type||ot.type||"file",fileType:ot.fileType||ot.file_type||ot.type||"file",fileSize:ot.fileSize||ot.file_size})):void 0,isCurrentUser:qe===N}}}).sort((ce,Ve)=>new Date(ce.timestamp).getTime()-new Date(Ve.timestamp).getTime());C(Re)}catch(ie){console.error("[WorkNoteChat] Error mapping messages:",ie)}else(async()=>{try{const ie=await Zr(u),Re=Array.isArray(ie)?ie.map(ce=>{const Ve=ce.userName||ce.user_name||"User",Be=ce.userRole||ce.user_role,tt=ne(Be),ze=ce.userId||ce.user_id;return{id:ce.noteId||ce.note_id||ce.id||String(Math.random()),user:{name:Ve,avatar:Ve.split(" ").map(rt=>rt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:tt},content:ce.message||"",timestamp:ce.createdAt||ce.created_at||new Date().toISOString(),attachments:Array.isArray(ce.attachments)?ce.attachments.map(rt=>({attachmentId:rt.attachmentId||rt.attachment_id,name:rt.fileName||rt.file_name||rt.name,fileName:rt.fileName||rt.file_name||rt.name,url:rt.storageUrl||rt.storage_url||rt.url||"#",type:rt.fileType||rt.file_type||rt.type||"file",fileType:rt.fileType||rt.file_type||rt.type||"file",fileSize:rt.fileSize||rt.file_size})):void 0,isCurrentUser:ze===N}}):[];C(Re)}catch(ie){console.error("[WorkNoteChat] Error loading work notes:",ie)}})()},[s,u,se]);const Q=ie=>{const Re=O.maxFileSizeMB*1024*1024;if(ie.size>Re)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${O.maxFileSizeMB}MB. Current size: ${(ie.size/(1024*1024)).toFixed(2)}MB`};const ce=ie.name.toLowerCase(),Ve=ce.substring(ce.lastIndexOf(".")+1);return O.allowedFileTypes.includes(Ve)?{valid:!0}:{valid:!1,reason:`File type "${Ve}" is not allowed. Allowed types: ${O.allowedFileTypes.join(", ")}`}},le=ie=>{if(!ie.target.files||ie.target.files.length===0)return;const Re=Array.from(ie.target.files),ce=[],Ve=[];Re.forEach(Be=>{const tt=Q(Be);tt.valid?Ve.push(Be):ce.push({fileName:Be.name,reason:tt.reason||"Unknown validation error"})}),ce.length>0&&re({open:!0,errors:ce}),Ve.length>0&&(R(Be=>[...Be,...Ve]),Ve.length{R(Re=>Re.filter((ce,Ve)=>Ve!==ie)),V.current&&(V.current.value="")},ge=ie=>{f(Re=>Re+ie),w(!1)},Fe=()=>{var ie;(ie=V.current)==null||ie.click()},_e=async ie=>{var Re,ce;try{await op(u,ie);const Ve=await Es(u),Be=Array.isArray(Ve==null?void 0:Ve.participants)?Ve.participants:[];if(Be.length){const tt=Be.map(ze=>{const rt=ze.participantType||ze.participant_type||"participant",qe=ze.userId||ze.user_id||"",ot=ze.userName||ze.user_name||ze.userEmail||ze.user_email||"User",Us=ze.userEmail||ze.user_email||"",rs=ot.split(" ").map(gt=>gt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:ot,avatar:rs,role:Ne(rt),status:"offline",email:Us,lastSeen:void 0,permissions:["read"],userId:qe}});ve(tt),Y.current&&Y.current.connected&&Y.current.emit("request:online-users",{requestId:u})}$(!1),E({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),B(!0)}catch(Ve){throw console.error("Failed to add spectator:",Ve),E({success:!1,title:"Failed to Add Spectator",message:((ce=(Re=Ve==null?void 0:Ve.response)==null?void 0:Re.data)==null?void 0:ce.error)||"Failed to add spectator. Please try again."}),B(!0),Ve}},Xe=async(ie,Re,ce)=>{var Ve,Be;if(d)await d(ie,Re,ce),T(!1);else try{await lp(u,ie,Re,ce);const tt=await Es(u),ze=Array.isArray(tt==null?void 0:tt.participants)?tt.participants:[];if(ze.length){const rt=ze.map(qe=>{const ot=qe.participantType||qe.participant_type||"participant",Us=qe.userId||qe.user_id||"",rs=qe.userName||qe.user_name||qe.userEmail||qe.user_email||"User",gt=qe.userEmail||qe.user_email||"",ct=rs.split(" ").map(Dt=>Dt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:rs,avatar:ct,role:Ne(ot),status:"offline",email:gt,lastSeen:void 0,permissions:["read"],userId:Us}});ve(rt),Y.current&&Y.current.connected&&Y.current.emit("request:online-users",{requestId:u})}T(!1),E({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${ce} with ${Re}h TAT`}),B(!0)}catch(tt){throw console.error("Failed to add approver:",tt),E({success:!1,title:"Failed to Add Approver",message:((Be=(Ve=tt==null?void 0:tt.response)==null?void 0:Ve.data)==null?void 0:Be.error)||"Failed to add approver. Please try again."}),B(!0),tt}},lt=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],Nt=ie=>{const Re=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,ce=[];let Ve;for(;(Ve=Re.exec(ie))!==null;)if(Ve[1]){const Be=Ve.index+Ve[0].length,tt=ie.slice(Be),ze=ie[Be];(tt.startsWith("@")||!ze||/\s|[.,!?;:]|@/.test(ze))&&ce.push(Ve[1].trim())}return ce},wt=ie=>{ie.key==="Enter"&&!ie.shiftKey&&(ie.preventDefault(),Ae())},As=(ie,Re)=>{C(ce=>ce.map(Ve=>{if(Ve.id===ie){const Be=Ve.reactions||[],tt=Be.find(ze=>ze.emoji===Re);if(tt)if(tt.users.includes("You")){if(tt.users=tt.users.filter(ze=>ze!=="You"),tt.users.length===0)return{...Ve,reactions:Be.filter(ze=>ze.emoji!==Re)}}else tt.users.push("You");else Be.push({emoji:Re,users:["You"]});return{...Ve,reactions:Be}}return Ve}))};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(Hs,{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:G.title}),e.jsx(ae,{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:[Te.slice(0,3).map((ie,Re)=>e.jsx(ls,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(os,{className:"bg-blue-500 text-white text-xs font-semibold",children:ie.avatar})},Re)),Te.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:["+",Te.length-3]})]})}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>L(!A),className:"lg:hidden",children:e.jsx(Jt,{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(Ss,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ce,{placeholder:"Search messages...",value:b,onChange:ie=>j(ie.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:[Ke.map(ie=>{const Re=ie.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${ie.isSystem?"justify-center":Re?"justify-end":""}`,children:[!ie.isSystem&&!Re&&e.jsx(ls,{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(os,{className:`text-white font-semibold text-xs sm:text-sm ${ie.user.role==="Initiator"?"bg-green-600":ie.user.role==="Current User"?"bg-blue-500":ie.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:ie.user.avatar})}),e.jsx("div",{className:`${Re?"max-w-[70%]":"flex-1"} min-w-0 ${ie.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:ie.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($t,{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:ie.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:gs(ie.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${Re?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[ie.user.name," ",Re&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(ae,{variant:"outline",className:"text-xs flex-shrink-0",children:ie.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"}),gs(ie.timestamp)]}),ie.isHighPriority&&e.jsxs(ae,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(Cb,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${Re?"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:ET(ie.content)}}),ie.attachments&&ie.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:ie.attachments.map((ce,Ve)=>{const Be=ce.fileSize||ce.file_size,tt=ce.fileName||ce.file_name||ce.name,ze=ce.fileType||ce.file_type||ce.type||"",rt=ce.attachmentId||ce.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(Cx,{type:ze})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs sm:text-sm font-medium text-gray-700 truncate",children:tt}),Be&&e.jsx("p",{className:"text-xs text-gray-500",children:_T(Be)})]}),rt&&(()=>{const qe=(ze||"").toLowerCase();return qe.includes("image")||qe.includes("pdf")||qe.includes("jpg")||qe.includes("jpeg")||qe.includes("png")||qe.includes("gif")})()&&e.jsx(M,{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:qe=>{qe.preventDefault(),qe.stopPropagation();const ot=Fw(rt);U({fileName:tt,fileType:ze,fileUrl:ot,fileSize:Be,attachmentId:rt})},title:"Preview file",children:e.jsx(St,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(M,{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 qe=>{if(qe.preventDefault(),qe.stopPropagation(),!rt){X.error("Cannot download: Attachment ID missing");return}try{await Km(rt)}catch{X.error("Failed to download file")}},title:"Download file",children:e.jsx(Rt,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Ve)})})}),ie.reactions&&ie.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:[ie.reactions.map((ce,Ve)=>e.jsxs("button",{onClick:()=>As(ie.id,ce.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${ce.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:ce.emoji}),e.jsx("span",{className:"text-xs font-medium",children:ce.users.length})]},Ve)),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>w(!y),children:e.jsx(bs,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!ie.isSystem&&Re&&e.jsx(ls,{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(os,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:ie.user.avatar})})]},ie.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:V,onChange:le,className:"hidden",multiple:!0,accept:O.allowedFileTypes.map(ie=>`.${ie}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((ie,Re)=>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(Cx,{type:ie.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:ie.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(ie.size/1024).toFixed(1)," KB"]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>pe(Re),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(jt,{className:"h-3 w-3 text-red-600"})})]},Re))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const ie=g.lastIndexOf("@"),Re=ie>=0;if(!Re)return null;const ce=g.slice(ie+1),Ve=ce.trim(),Be=ce.endsWith(" "),tt=Ve.length>0,ze=Ve.includes(" ")&&!Be,rt=Be&&tt;if(!(Re&&ce.length<=20&&!ze&&!rt))return null;const ot=Ve.toLowerCase(),Us=se.filter(rs=>rs.userId===N?!1:ot?rs.name.toLowerCase().includes(ot):!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:Us.length>0?Us.map((rs,gt)=>e.jsxs("button",{type:"button",onClick:ct=>{ct.preventDefault(),ct.stopPropagation();const Dt=g.lastIndexOf("@"),vs=g.slice(0,Dt);f(vs+"@"+rs.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(ls,{className:"h-10 w-10",children:e.jsx(os,{className:`text-white text-sm font-semibold ${rs.role==="Initiator"?"bg-green-600":rs.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:rs.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:rs.name}),e.jsx("p",{className:"text-xs text-gray-600",children:rs.role})]})]},gt)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:ot?`No participants found matching "${ot}"`:"No other participants available"})})]})})(),e.jsx(is,{placeholder:"Type your message... Use @username to mention someone",value:g,onChange:ie=>f(ie.target.value),onKeyPress:wt,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}),y&&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(M,{variant:"ghost",size:"sm",onClick:()=>w(!1),className:"h-6 w-6 p-0",children:e.jsx(jt,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:lt.map((ie,Re)=>e.jsx("button",{onClick:()=>ge(ie),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:ie,children:ie},Re))})]})]}),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(M,{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:Fe,title:"Attach file",children:e.jsx(Wi,{className:"h-4 w-4"})}),e.jsx(M,{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(!y),title:"Add emoji",children:e.jsx(Sb,{className:"h-4 w-4"})}),e.jsx(M,{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:()=>f(ie=>ie+"@"),title:"Mention someone",children:e.jsx(Xi,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto flex-shrink-0",children:[e.jsxs("span",{className:"text-xs text-gray-500 hidden md:inline whitespace-nowrap",children:[g.length,"/2000"]}),e.jsxs(M,{onClick:Ae,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(mh,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),A&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>L(!1)}),e.jsxs("div",{className:` + `),()=>{b.contains(f)&&b.removeChild(f)}},[s]),e.jsx(YC,{isPresent:s,childRef:i,sizeRef:l,children:h.cloneElement(t,{ref:c})})}const QC=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=cc(XC),m=h.useId();let p=!0,x=h.useMemo(()=>(p=!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&&p&&(x={...x}),h.useMemo(()=>{d.forEach((u,g)=>d.set(g,!1))},[a]),h.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(KC,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(il.Provider,{value:x,children:t})};function XC(){return new Map}function lg(t=!0){const s=h.useContext(il);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=h.useId();h.useEffect(()=>{if(t)return n(i)},[t]);const l=h.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const oi=t=>t.key||"";function ju(t){const s=[];return h.Children.forEach(t,a=>{h.isValidElement(a)&&s.push(a)}),s}const ll=({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]=lg(l),p=h.useMemo(()=>ju(t),[t]),x=l&&!d?[]:p.map(oi),u=h.useRef(!0),g=h.useRef(p),f=cc(()=>new Map),[b,j]=h.useState(p),[y,w]=h.useState(p);gp(()=>{u.current=!1,g.current=p;for(let A=0;A{const L=oi(A),D=l&&!d?!1:p===y||x.includes(L),R=()=>{if(f.has(L))f.set(L,!0);else return;let N=!0;f.forEach(_=>{_||(N=!1)}),N&&(C==null||C(),w(g.current),l&&(m==null||m()),r&&r())};return e.jsx(QC,{isPresent:D,initial:!u.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:D?void 0:R,anchorX:o,children:A},L)})})},og=h.createContext({strict:!1}),yu={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"]},sn={};for(const t in yu)sn[t]={isEnabled:s=>yu[t].some(a=>!!s[a])};function JC(t){for(const s in t)sn[s]={...sn[s],...t[s]}}const ZC=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 Oi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||ZC.has(t)}let cg=t=>!Oi(t);function qC(t){typeof t=="function"&&(cg=s=>s.startsWith("on")?!Oi(s):t(s))}try{qC(require("@emotion/is-prop-valid").default)}catch{}function e2(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(cg(n)||a===!0&&Oi(n)||!s&&!Oi(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const ol=h.createContext({});function cl(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Bn(t){return typeof t=="string"||Array.isArray(t)}const Pc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Ec=["initial",...Pc];function dl(t){return cl(t.animate)||Ec.some(s=>Bn(t[s]))}function dg(t){return!!(dl(t)||t.variants)}function t2(t,s){if(dl(t)){const{initial:a,animate:r}=t;return{initial:a===!1||Bn(a)?a:void 0,animate:Bn(r)?r:void 0}}return t.inherit!==!1?s:{}}function s2(t){const{initial:s,animate:a}=t2(t,h.useContext(ol));return h.useMemo(()=>({initial:s,animate:a}),[vu(s),vu(a)])}function vu(t){return Array.isArray(t)?t.join(" "):t}const Vn={};function a2(t){for(const s in t)Vn[s]=t[s],bc(s)&&(Vn[s].isCSSVariable=!0)}function mg(t,{layout:s,layoutId:a}){return hn.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!Vn[t]||t==="opacity")}const r2={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},n2=xn.length;function i2(t,s,a){let r="",n=!0;for(let i=0;i({style:{},transform:{},transformOrigin:{},vars:{}});function ug(t,s,a){for(const r in s)!$s(s[r])&&!mg(r,a)&&(t[r]=s[r])}function l2({transformTemplate:t},s){return h.useMemo(()=>{const a=Mc();return _c(a,s,t),Object.assign({},a.vars,a.style)},[s])}function o2(t,s){const a=t.style||{},r={};return ug(r,a,t),Object.assign(r,l2(t,s)),r}function c2(t,s){const a={},r=o2(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 d2={offset:"stroke-dashoffset",array:"stroke-dasharray"},m2={offset:"strokeDashoffset",array:"strokeDasharray"};function u2(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?d2:m2;t[i.offset]=nt.transform(-r);const l=nt.transform(s),o=nt.transform(a);t[i.array]=`${l} ${o}`}function xg(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(_c(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:p,style:x}=t;p.transform&&(x.transform=p.transform,delete p.transform),(x.transform||p.transformOrigin)&&(x.transformOrigin=p.transformOrigin??"50% 50%",delete p.transformOrigin),x.transform&&(x.transformBox=(m==null?void 0:m.transformBox)??"fill-box",delete p.transformBox),s!==void 0&&(p.x=s),a!==void 0&&(p.y=a),r!==void 0&&(p.scale=r),n!==void 0&&u2(p,n,i,l,!1)}const hg=()=>({...Mc(),attrs:{}}),pg=t=>typeof t=="string"&&t.toLowerCase()==="svg";function x2(t,s,a,r){const n=h.useMemo(()=>{const i=hg();return xg(i,s,pg(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};ug(i,t.style,t),n.style={...i,...n.style}}return n}const h2=["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 Lc(t){return typeof t!="string"||t.includes("-")?!1:!!(h2.indexOf(t)>-1||/[A-Z]/u.test(t))}function p2(t,s,a,{latestValues:r},n,i=!1){const o=(Lc(t)?x2:c2)(s,r,n,t),c=e2(s,typeof t=="string",i),d=t!==h.Fragment?{...c,...o,ref:a}:{},{children:m}=s,p=h.useMemo(()=>$s(m)?m.get():m,[m]);return h.createElement(t,{...d,children:p})}function Nu(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function Oc(t,s,a,r){if(typeof s=="function"){const[n,i]=Nu(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]=Nu(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Ni(t){return $s(t)?t.get():t}function g2({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:f2(a,r,n,t),renderState:s()}}function f2(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=Ni(i[x]);let{initial:l,animate:o}=t;const c=dl(t),d=dg(t);s&&d&&!c&&t.inherit!==!1&&(l===void 0&&(l=s.initial),o===void 0&&(o=s.animate));let m=a?a.initial===!1:!1;m=m||l===!1;const p=m?o:l;if(p&&typeof p!="boolean"&&!cl(p)){const x=Array.isArray(p)?p:[p];for(let u=0;u(s,a)=>{const r=h.useContext(ol),n=h.useContext(il),i=()=>g2(t,s,r,n);return a?i():cc(i)};function $c(t,s,a){var i;const{style:r}=t,n={};for(const l in r)($s(r[l])||s.style&&$s(s.style[l])||mg(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const b2=gg({scrapeMotionValuesFromProps:$c,createRenderState:Mc});function fg(t,s,a){const r=$c(t,s,a);for(const n in t)if($s(t[n])||$s(s[n])){const i=xn.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const j2=gg({scrapeMotionValuesFromProps:fg,createRenderState:hg}),y2=Symbol.for("motionComponentSymbol");function Hr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function v2(t,s,a){return h.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):Hr(a)&&(a.current=r))},[s])}const Uc=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),N2="framerAppearId",bg="data-"+Uc(N2),jg=h.createContext({});function w2(t,s,a,r,n){var f,b;const{visualElement:i}=h.useContext(ol),l=h.useContext(og),o=h.useContext(il),c=h.useContext(Ic).reducedMotion,d=h.useRef(null);r=r||l.renderer,!d.current&&r&&(d.current=r(t,{visualState:s,parent:i,props:a,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:c}));const m=d.current,p=h.useContext(jg);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&C2(d.current,a,n,p);const x=h.useRef(!1);h.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const u=a[bg],g=h.useRef(!!u&&!((f=window.MotionHandoffIsComplete)!=null&&f.call(window,u))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,u)));return gp(()=>{m&&(x.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),h.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var j;(j=window.MotionHandoffMarkAsComplete)==null||j.call(window,u)}),g.current=!1),m.enteringChildren=void 0)}),m}function C2(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:yg(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&Hr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function yg(t){if(t)return t.options.allowProjection!==!1?t.projection:yg(t.parent)}function Ml(t,{forwardMotionProps:s=!1}={},a,r){a&&JC(a);const n=Lc(t)?j2:b2;function i(o,c){let d;const m={...h.useContext(Ic),...o,layoutId:S2(o)},{isStatic:p}=m,x=s2(o),u=n(o,p);if(!p&&dc){A2();const g=T2(m);d=g.MeasureLayout,x.visualElement=w2(t,u,m,r,g.ProjectionNode)}return e.jsxs(ol.Provider,{value:x,children:[d&&x.visualElement?e.jsx(d,{visualElement:x.visualElement,...m}):null,p2(t,o,v2(u,x.visualElement,c),u,p,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=h.forwardRef(i);return l[y2]=t,l}function S2({layoutId:t}){const s=h.useContext(oc).id;return s&&t!==void 0?s+"-"+t:t}function A2(t,s){h.useContext(og).strict}function T2(t){const{drag:s,layout:a}=sn;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 k2(t,s){if(typeof Proxy>"u")return Ml;const a=new Map,r=(i,l)=>Ml(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,Ml(l,void 0,t,s)),a.get(l))})}function vg({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function R2({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function D2(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 Ll(t){return t===void 0||t===1}function So({scale:t,scaleX:s,scaleY:a}){return!Ll(t)||!Ll(s)||!Ll(a)}function Cr(t){return So(t)||Ng(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Ng(t){return wu(t.x)||wu(t.y)}function wu(t){return t&&t!=="0%"}function $i(t,s,a){const r=t-a,n=s*r;return a+n}function Cu(t,s,a,r,n){return n!==void 0&&(t=$i(t,n,r)),$i(t,a,r)+s}function Ao(t,s=0,a=1,r,n){t.min=Cu(t.min,s,a,r,n),t.max=Cu(t.max,s,a,r,n)}function wg(t,{x:s,y:a}){Ao(t.x,s.translate,s.scale,s.originPoint),Ao(t.y,a.translate,a.scale,a.originPoint)}const Su=.999999999999,Au=1.0000000000001;function F2(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,l;for(let o=0;oSu&&(s.x=1),s.ySu&&(s.y=1)}function Wr(t,s){t.min=t.min+s,t.max=t.max+s}function Tu(t,s,a,r,n=.5){const i=as(t.min,t.max,n);Ao(t,s,a,i,r)}function Gr(t,s){Tu(t.x,s.x,s.scaleX,s.scale,s.originX),Tu(t.y,s.y,s.scaleY,s.scale,s.originY)}function Cg(t,s){return vg(D2(t.getBoundingClientRect(),s))}function I2(t,s,a){const r=Cg(t,a),{scroll:n}=s;return n&&(Wr(r.x,n.offset.x),Wr(r.y,n.offset.y)),r}const ku=()=>({translate:0,scale:1,origin:0,originPoint:0}),Yr=()=>({x:ku(),y:ku()}),Ru=()=>({min:0,max:0}),ds=()=>({x:Ru(),y:Ru()}),To={current:null},Sg={current:!1};function P2(){if(Sg.current=!0,!!dc)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>To.current=t.matches;t.addEventListener("change",s),s()}else To.current=!1}const E2=new WeakMap;function _2(t,s,a){for(const r in s){const n=s[r],i=a[r];if($s(n))t.addValue(r,n);else if($s(i))t.addValue(r,tn(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,tn(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Du=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class M2{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=Tc,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=Zs.now();this.renderScheduledAtthis.bindToMotionValue(n,r)),Sg.current||P2(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:To.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),ur(this.notifyUpdate),ur(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=hn.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&Zt.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 sn){const a=sn[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):ds()}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=tn(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"&&(fp(r)||jp(r))?r=parseFloat(r):!HC(r)&&xr.test(a)&&(r=eg(s,a)),this.setBaseTarget(s,$s(r)?r.get():r)),$s(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=Oc(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&&!$s(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 pc),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){Dc.render(this.render)}}class Ag extends M2{constructor(){super(...arguments),this.KeyframeResolver=IC}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;$s(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function Tg(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 L2(t){return window.getComputedStyle(t)}class O2 extends Ag{constructor(){super(...arguments),this.type="html",this.renderInstance=Tg}readValueFromInstance(s,a){var r;if(hn.has(a))return(r=this.projection)!=null&&r.isProjecting?bo(a):J1(s,a);{const n=L2(s),i=(bc(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return Cg(s,a)}build(s,a,r){_c(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return $c(s,a,r)}}const kg=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 $2(t,s,a,r){Tg(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(kg.has(n)?n:Uc(n),s.attrs[n])}class U2 extends Ag{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ds}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(hn.has(a)){const r=qp(a);return r&&r.default||0}return a=kg.has(a)?a:Uc(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return fg(s,a,r)}build(s,a,r){xg(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){$2(s,a,r,n)}mount(s){this.isSVGTag=pg(s.tagName),super.mount(s)}}const B2=(t,s)=>Lc(t)?new U2(s):new O2(s,{allowProjection:t!==h.Fragment});function qr(t,s,a){const r=t.getProps();return Oc(r,s,a!==void 0?a:r.custom,t)}const ko=t=>Array.isArray(t);function V2(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,tn(a))}function z2(t){return ko(t)?t[t.length-1]||0:t}function H2(t,s){const a=qr(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=z2(i[l]);V2(t,l,o)}}function W2(t){return!!($s(t)&&t.add)}function Ro(t,s){const a=t.getValue("willChange");if(W2(a))return a.add(s);if(!a&&Ga.WillChange){const r=new Ga.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function Rg(t){return t.props[bg]}const G2=t=>t!==null;function Y2(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(G2),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const K2={type:"spring",stiffness:500,damping:25,restSpeed:10},Q2=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),X2={type:"keyframes",duration:.8},J2={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Z2=(t,{keyframes:s})=>s.length>2?X2:hn.has(t)?t.startsWith("scale")?Q2(s[1]):K2:J2;function q2({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 Bc=(t,s,a,r={},n,i)=>l=>{const o=kc(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-Da(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};q2(o)||Object.assign(m,Z2(t,m)),m.duration&&(m.duration=Da(m.duration)),m.repeatDelay&&(m.repeatDelay=Da(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let p=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(wo(m),m.delay===0&&(p=!0)),(Ga.instantAnimations||Ga.skipAnimations)&&(p=!0,wo(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,p&&!i&&s.get()!==void 0){const x=Y2(m.keyframes,o);if(x!==void 0){Zt.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new Ac(m):new yC(m)};function eS({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Dg(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in o){const p=t.getValue(m,t.latestValues[m]??null),x=o[m];if(x===void 0||d&&eS(d,m))continue;const u={delay:a,...kc(i||{},m)},g=p.get();if(g!==void 0&&!p.isAnimating&&!Array.isArray(x)&&x===g&&!u.velocity)continue;let f=!1;if(window.MotionHandoffAnimation){const j=Rg(t);if(j){const y=window.MotionHandoffAnimation(j,m,Zt);y!==null&&(u.startTime=y,f=!0)}}Ro(t,m),p.start(Bc(m,p,x,t.shouldReduceMotion&&Xp.has(m)?{type:!1}:u,t,f));const b=p.animation;b&&c.push(b)}return l&&Promise.all(c).then(()=>{Zt.update(()=>{l&&H2(t,l)})}),c}function Fg(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 Do(t,s,a={}){var c;const r=qr(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(Dg(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:p,staggerDirection:x}=n;return tS(t,s,d,m,p,x,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[d,m]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function tS(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(Do(c,s,{...l,delay:a+(typeof r=="function"?0:r)+Fg(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function sS(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>Do(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=Do(t,s,a);else{const n=typeof s=="function"?qr(t,s,a.custom):s;r=Promise.all(Dg(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function Ig(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})=>sS(t,a,r)))}function lS(t){let s=iS(t),a=Fu(),r=!0;const n=c=>(d,m)=>{var x;const p=qr(t,m,c==="exit"?(x=t.presenceContext)==null?void 0:x.custom:void 0);if(p){const{transition:u,transitionEnd:g,...f}=p;d={...d,...f,...g}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=Pg(t.parent)||{},p=[],x=new Set;let u={},g=1/0;for(let b=0;bg&&v,R=!1;const N=Array.isArray(w)?w:[w];let _=N.reduce(n(j),{});C===!1&&(_={});const{prevResolvedValues:S={}}=y,U={...S,..._},F=T=>{D=!0,x.has(T)&&(R=!0,x.delete(T)),y.needsAnimating[T]=!0;const k=t.getValue(T);k&&(k.liveStyle=!1)};for(const T in U){const k=_[T],B=S[T];if(u.hasOwnProperty(T))continue;let I=!1;ko(k)&&ko(B)?I=!Ig(k,B):I=k!==B,I?k!=null?F(T):x.add(T):k!==void 0&&x.has(T)?F(T):y.protectedKeys[T]=!0}y.prevProp=w,y.prevResolvedValues=_,y.isActive&&(u={...u,..._}),r&&t.blockInitialAnimation&&(D=!1);const $=A&&L;D&&(!$||R)&&p.push(...N.map(T=>{const k={type:j};if(typeof T=="string"&&r&&!$&&t.manuallyAnimateOnMount&&t.parent){const{parent:B}=t,I=qr(B,T);if(B.enteringChildren&&I){const{delayChildren:E}=I.transition||{};k.delay=Fg(B.enteringChildren,t,E)}}return{animation:T,options:k}}))}if(x.size){const b={};if(typeof d.initial!="boolean"){const j=qr(t,Array.isArray(d.initial)?d.initial[0]:d.initial);j&&j.transition&&(b.transition=j.transition)}x.forEach(j=>{const y=t.getBaseTarget(j),w=t.getValue(j);w&&(w.liveStyle=!0),b[j]=y??null}),p.push({animation:b})}let f=!!p.length;return r&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(f=!1),r=!1,f?s(p):Promise.resolve()}function o(c,d){var p;if(a[c].isActive===d)return Promise.resolve();(p=t.variantChildren)==null||p.forEach(x=>{var 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=Fu()}}}function oS(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!Ig(s,t):!1}function yr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Fu(){return{animate:yr(!0),whileInView:yr(),whileHover:yr(),whileTap:yr(),whileDrag:yr(),whileFocus:yr(),exit:yr()}}class hr{constructor(s){this.isMounted=!1,this.node=s}update(){}}class cS extends hr{constructor(s){super(s),s.animationState||(s.animationState=lS(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();cl(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 dS=0;class mS extends hr{constructor(){super(...arguments),this.id=dS++}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 uS={animation:{Feature:cS},exit:{Feature:mS}};function zn(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function ei(t){return{point:{x:t.pageX,y:t.pageY}}}const xS=t=>s=>Fc(s)&&t(s,ei(s));function Pn(t,s,a,r){return zn(t,s,xS(a),r)}const Eg=1e-4,hS=1-Eg,pS=1+Eg,_g=.01,gS=0-_g,fS=0+_g;function zs(t){return t.max-t.min}function bS(t,s,a){return Math.abs(t-s)<=a}function Iu(t,s,a,r=.5){t.origin=r,t.originPoint=as(s.min,s.max,t.origin),t.scale=zs(a)/zs(s),t.translate=as(a.min,a.max,t.origin)-t.originPoint,(t.scale>=hS&&t.scale<=pS||isNaN(t.scale))&&(t.scale=1),(t.translate>=gS&&t.translate<=fS||isNaN(t.translate))&&(t.translate=0)}function En(t,s,a,r){Iu(t.x,s.x,a.x,r?r.originX:void 0),Iu(t.y,s.y,a.y,r?r.originY:void 0)}function Pu(t,s,a){t.min=a.min+s.min,t.max=t.min+zs(s)}function jS(t,s,a){Pu(t.x,s.x,a.x),Pu(t.y,s.y,a.y)}function Eu(t,s,a){t.min=s.min-a.min,t.max=t.min+zs(s)}function _n(t,s,a){Eu(t.x,s.x,a.x),Eu(t.y,s.y,a.y)}function xa(t){return[t("x"),t("y")]}const Mg=({current:t})=>t?t.ownerDocument.defaultView:null,_u=(t,s)=>Math.abs(t-s);function yS(t,s){const a=_u(t.x,s.x),r=_u(t.y,s.y);return Math.sqrt(a**2+r**2)}class Lg{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=$l(this.lastMoveEventInfo,this.history),u=this.startEvent!==null,g=yS(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!u&&!g)return;const{point:f}=x,{timestamp:b}=Ps;this.history.push({...f,timestamp:b});const{onStart:j,onMove:y}=this.handlers;u||(j&&j(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),y&&y(this.lastMoveEvent,x)},this.handlePointerMove=(x,u)=>{this.lastMoveEvent=x,this.lastMoveEventInfo=Ol(u,this.transformPagePoint),Zt.update(this.updatePoint,!0)},this.handlePointerUp=(x,u)=>{this.end();const{onEnd:g,onSessionEnd:f,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const j=$l(x.type==="pointercancel"?this.lastMoveEventInfo:Ol(u,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,j),f&&f(x,j)},!Fc(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=ei(s),c=Ol(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=Ps;this.history=[{...d,timestamp:m}];const{onSessionStart:p}=a;p&&p(s,$l(c,this.history)),this.removeListeners=Jn(Pn(this.contextWindow,"pointermove",this.handlePointerMove),Pn(this.contextWindow,"pointerup",this.handlePointerUp),Pn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),ur(this.updatePoint)}}function Ol(t,s){return s?{point:s(t.point)}:t}function Mu(t,s){return{x:t.x-s.x,y:t.y-s.y}}function $l({point:t},s){return{point:t,delta:Mu(t,Og(s)),offset:Mu(t,vS(s)),velocity:NS(s,.1)}}function vS(t){return t[0]}function Og(t){return t[t.length-1]}function NS(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=Og(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>Da(s)));)a--;if(!r)return{x:0,y:0};const i=ha(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 wS(t,{min:s,max:a},r){return s!==void 0&&ta&&(t=r?as(a,t,r.max):Math.min(t,a)),t}function Lu(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 CS(t,{top:s,left:a,bottom:r,right:n}){return{x:Lu(t.x,a,n),y:Lu(t.y,s,r)}}function Ou(t,s){let a=s.min-t.min,r=s.max-t.max;return s.max-s.minr?a=On(s.min,s.max-r,t.min):r>n&&(a=On(t.min,t.max-n,s.min)),Wa(0,1,a)}function TS(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 Fo=.35;function kS(t=Fo){return t===!1?t=0:t===!0&&(t=Fo),{x:$u(t,"left","right"),y:$u(t,"top","bottom")}}function $u(t,s,a){return{min:Uu(t,s),max:Uu(t,a)}}function Uu(t,s){return typeof t=="number"?t:t[s]||0}const RS=new WeakMap;class DS{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=ds(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:a=!1,distanceThreshold:r}={}){const{presenceContext:n}=this.visualElement;if(n&&n.isPresent===!1)return;const i=p=>{const{dragSnapToOrigin:x}=this.getProps();x?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(ei(p).point)},l=(p,x)=>{const{drag:u,dragPropagation:g,onDragStart:f}=this.getProps();if(u&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=MC(u),!this.openDragLock))return;this.latestPointerEvent=p,this.latestPanInfo=x,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),xa(j=>{let y=this.getAxisMotionValue(j).get()||0;if(Fa.test(y)){const{projection:w}=this.visualElement;if(w&&w.layout){const v=w.layout.layoutBox[j];v&&(y=zs(v)*(parseFloat(y)/100))}}this.originPoint[j]=y}),f&&Zt.postRender(()=>f(p,x)),Ro(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},o=(p,x)=>{this.latestPointerEvent=p,this.latestPanInfo=x;const{dragPropagation:u,dragDirectionLock:g,onDirectionLock:f,onDrag:b}=this.getProps();if(!u&&!this.openDragLock)return;const{offset:j}=x;if(g&&this.currentDirection===null){this.currentDirection=FS(j),this.currentDirection!==null&&f&&f(this.currentDirection);return}this.updateAxis("x",x.point,j),this.updateAxis("y",x.point,j),this.visualElement.render(),b&&b(p,x)},c=(p,x)=>{this.latestPointerEvent=p,this.latestPanInfo=x,this.stop(p,x),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>xa(p=>{var x;return this.getAnimationState(p)==="paused"&&((x=this.getAxisMotionValue(p).animation)==null?void 0:x.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new Lg(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:Mg(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&&Zt.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||!ci(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=wS(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&&Hr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=CS(r.layoutBox,s):this.constraints=!1,this.elastic=kS(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&xa(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=TS(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!Hr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=I2(r,n.root,this.visualElement.getTransformPagePoint());let l=SS(n.layout.layoutBox,i);if(a){const o=a(R2(l));this.hasMutatedConstraints=!!o,o&&(l=vg(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=xa(m=>{if(!ci(m,a,this.currentDirection))return;let p=c&&c[m]||{};l&&(p={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,...p};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return Ro(this.visualElement,s),r.start(Bc(s,r,0,a,this.visualElement,!1))}stopAnimation(){xa(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){xa(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){xa(a=>{const{drag:r}=this.getProps();if(!ci(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]-as(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!Hr(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};xa(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=AS({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(),xa(l=>{if(!ci(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(as(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;RS.set(this.visualElement,this);const s=this.visualElement.current,a=Pn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();Hr(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()),Zt.read(r);const l=zn(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(xa(m=>{const p=this.getAxisMotionValue(m);p&&(this.originPoint[m]+=c[m].translate,p.set(p.get()+c[m].translate))}),this.visualElement.render())});return()=>{l(),a(),i(),o&&o()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:l=Fo,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function ci(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function FS(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class IS extends hr{constructor(s){super(s),this.removeGroupControls=pa,this.removeListeners=pa,this.controls=new DS(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||pa}unmount(){this.removeGroupControls(),this.removeListeners()}}const Bu=t=>(s,a)=>{t&&Zt.postRender(()=>t(s,a))};class PS extends hr{constructor(){super(...arguments),this.removePointerDownListener=pa}onPointerDown(s){this.session=new Lg(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Mg(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Bu(s),onStart:Bu(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&Zt.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=Pn(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 wi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Vu(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const vn={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(nt.test(t))t=parseFloat(t);else return t;const a=Vu(t,s.target.x),r=Vu(t,s.target.y);return`${a}% ${r}%`}},ES={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=xr.parse(t);if(n.length>5)return r;const i=xr.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=as(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 Ul=!1;class _S extends h.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;a2(MS),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),Ul&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),wi.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,Ul=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||Zt.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Dc.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;Ul=!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 $g(t){const[s,a]=lg(),r=h.useContext(oc);return e.jsx(_S,{...t,layoutGroup:r,switchLayoutGroup:h.useContext(jg),isPresent:s,safeToRemove:a})}const MS={borderRadius:{...vn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:vn,borderTopRightRadius:vn,borderBottomLeftRadius:vn,borderBottomRightRadius:vn,boxShadow:ES};function LS(t,s,a){const r=$s(t)?t:tn(t);return r.start(Bc("",r,s,a)),r.animation}const OS=(t,s)=>t.depth-s.depth;class $S{constructor(){this.children=[],this.isDirty=!1}add(s){mc(this.children,s),this.isDirty=!0}remove(s){uc(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(OS),this.isDirty=!1,this.children.forEach(s)}}function US(t,s){const a=Zs.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(ur(r),t(i-s))};return Zt.setup(r,!0),()=>ur(r)}const Ug=["TopLeft","TopRight","BottomLeft","BottomRight"],BS=Ug.length,zu=t=>typeof t=="string"?parseFloat(t):t,Hu=t=>typeof t=="number"||nt.test(t);function VS(t,s,a,r,n,i){n?(t.opacity=as(0,a.opacity??1,zS(r)),t.opacityExit=as(s.opacity??1,0,HS(r))):i&&(t.opacity=as(s.opacity??1,a.opacity??1,r));for(let l=0;lrs?1:a(On(t,s,r))}function Gu(t,s){t.min=s.min,t.max=s.max}function ua(t,s){Gu(t.x,s.x),Gu(t.y,s.y)}function Yu(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function Ku(t,s,a,r,n){return t-=s,t=$i(t,1/a,r),n!==void 0&&(t=$i(t,1/n,r)),t}function WS(t,s=0,a=1,r=.5,n,i=t,l=t){if(Fa.test(s)&&(s=parseFloat(s),s=as(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=as(i.min,i.max,r);t===i&&(o-=s),t.min=Ku(t.min,s,a,o,n),t.max=Ku(t.max,s,a,o,n)}function Qu(t,s,[a,r,n],i,l){WS(t,s[a],s[r],s[n],s.scale,i,l)}const GS=["x","scaleX","originX"],YS=["y","scaleY","originY"];function Xu(t,s,a,r){Qu(t.x,s,GS,a?a.x:void 0,r?r.x:void 0),Qu(t.y,s,YS,a?a.y:void 0,r?r.y:void 0)}function Ju(t){return t.translate===0&&t.scale===1}function Vg(t){return Ju(t.x)&&Ju(t.y)}function Zu(t,s){return t.min===s.min&&t.max===s.max}function KS(t,s){return Zu(t.x,s.x)&&Zu(t.y,s.y)}function qu(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function zg(t,s){return qu(t.x,s.x)&&qu(t.y,s.y)}function ex(t){return zs(t.x)/zs(t.y)}function tx(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class QS{constructor(){this.members=[]}add(s){mc(this.members,s),s.scheduleRender()}remove(s){if(uc(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 XS(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,l=(a==null?void 0:a.z)||0;if((n||i||l)&&(r=`translate3d(${n}px, ${i}px, ${l}px) `),(s.x!==1||s.y!==1)&&(r+=`scale(${1/s.x}, ${1/s.y}) `),a){const{transformPerspective:d,rotate:m,rotateX:p,rotateY:x,skewX:u,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),p&&(r+=`rotateX(${p}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 Bl=["","X","Y","Z"],JS=1e3;let ZS=0;function Vl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Hg(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=Rg(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",Zt,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Hg(r)}function Wg({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=ZS++,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(tA),this.nodes.forEach(nA),this.nodes.forEach(iA),this.nodes.forEach(sA)},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;Zt.read(()=>{p=window.innerWidth}),t(l,()=>{const u=window.innerWidth;u!==p&&(p=u,this.root.updateBlockedByResize=!0,m&&m(),m=US(x,250),wi.hasAnimatedSinceResize&&(wi.hasAnimatedSinceResize=!1,this.nodes.forEach(rx)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:p,hasRelativeLayoutChanged:x,layout:u})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||mA,{onLayoutAnimationStart:f,onLayoutAnimationComplete:b}=d.getProps(),j=!this.targetLayout||!zg(this.targetLayout,u),y=!p&&x;if(this.options.layoutRoot||this.resumeFrom||y||p&&(j||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...kc(g,"layout"),onPlay:f,onComplete:b};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(m,y)}else p||rx(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(),ur(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(lA),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&&Hg(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&&!zs(this.snapshot.measuredBox.x)&&!zs(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 C=v/1e3;nx(p.x,l.x,C),nx(p.y,l.y,C),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(_n(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),cA(this.relativeTarget,this.relativeTargetOrigin,x,C),w&&KS(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=ds()),ua(w,this.relativeTarget)),f&&(this.animationValues=m,VS(m,d,this.latestValues,C,y,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=C},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&&(ur(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Zt.update(()=>{wi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=tn(0)),this.currentAnimation=LS(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(JS),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&&Gg(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||ds();const p=zs(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+p;const x=zs(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+x}ua(o,c),Gr(o,m),En(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new QS),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&&Vl("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(sx),this.root.sharedNodes.clear()}}}function qS(t){t.updateLayout()}function eA(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"?xa(p=>{const x=l?s.measuredBox[p]:s.layoutBox[p],u=zs(x);x.min=r[p].min,x.max=x.min+u}):Gg(i,s.layoutBox,r)&&xa(p=>{const x=l?s.measuredBox[p]:s.layoutBox[p],u=zs(r[p]);x.max=x.min+u,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[p].max=t.relativeTarget[p].min+u)});const o=Yr();En(o,r,s.layoutBox);const c=Yr();l?En(c,t.applyTransform(n,!0),s.measuredBox):En(c,r,s.layoutBox);const d=!Vg(o);let m=!1;if(!t.resumeFrom){const p=t.getClosestProjectingParent();if(p&&!p.resumeFrom){const{snapshot:x,layout:u}=p;if(x&&u){const g=ds();_n(g,s.layoutBox,x.layoutBox);const f=ds();_n(f,r,u.layoutBox),zg(g,f)||(m=!0),p.options.layoutRoot&&(t.relativeTarget=f,t.relativeTargetOrigin=g,t.relativeParent=p)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function tA(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 sA(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function aA(t){t.clearSnapshot()}function sx(t){t.clearMeasurements()}function ax(t){t.isLayoutDirty=!1}function rA(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function rx(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function nA(t){t.resolveTargetDelta()}function iA(t){t.calcProjection()}function lA(t){t.resetSkewAndRotation()}function oA(t){t.removeLeadSnapshot()}function nx(t,s,a){t.translate=as(s.translate,0,a),t.scale=as(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function ix(t,s,a,r){t.min=as(s.min,a.min,r),t.max=as(s.max,a.max,r)}function cA(t,s,a,r){ix(t.x,s.x,a.x,r),ix(t.y,s.y,a.y,r)}function dA(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const mA={duration:.45,ease:[.4,0,.1,1]},lx=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),ox=lx("applewebkit/")&&!lx("chrome/")?Math.round:pa;function cx(t){t.min=ox(t.min),t.max=ox(t.max)}function uA(t){cx(t.x),cx(t.y)}function Gg(t,s,a){return t==="position"||t==="preserve-aspect"&&!bS(ex(s),ex(a),.2)}function xA(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const hA=Wg({attachResizeListener:(t,s)=>zn(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),zl={current:void 0},Yg=Wg({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!zl.current){const t=new hA({});t.mount(window),t.setOptions({layoutScroll:!0}),zl.current=t}return zl.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),pA={pan:{Feature:PS},drag:{Feature:IS,ProjectionNode:Yg,MeasureLayout:$g}};function dx(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&&Zt.postRender(()=>i(s,ei(s)))}class gA extends hr{mount(){const{current:s}=this.node;s&&(this.unmount=LC(s,(a,r)=>(dx(this.node,r,"Start"),n=>dx(this.node,n,"End"))))}unmount(){}}class fA extends hr{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=Jn(zn(this.node.current,"focus",()=>this.onFocus()),zn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function mx(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&&Zt.postRender(()=>i(s,ei(s)))}class bA extends hr{mount(){const{current:s}=this.node;s&&(this.unmount=BC(s,(a,r)=>(mx(this.node,r,"Start"),(n,{success:i})=>mx(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Io=new WeakMap,Hl=new WeakMap,jA=t=>{const s=Io.get(t.target);s&&s(t)},yA=t=>{t.forEach(jA)};function vA({root:t,...s}){const a=t||document;Hl.has(a)||Hl.set(a,{});const r=Hl.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(yA,{root:t,...s})),r[n]}function NA(t,s,a){const r=vA(s);return Io.set(t,a),r.observe(t),()=>{Io.delete(t),r.unobserve(t)}}const wA={some:0,all:1};class CA extends hr{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:wA[n]},o=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:p}=this.node.getProps(),x=d?m:p;x&&x(c)};return NA(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(SA(s,a))&&this.startObserver()}unmount(){}}function SA({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const AA={inView:{Feature:CA},tap:{Feature:bA},focus:{Feature:fA},hover:{Feature:gA}},TA={layout:{ProjectionNode:Yg,MeasureLayout:$g}},kA={...uS,...AA,...pA,...TA},Ht=k2(kA,B2),Nn=[{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:Pt,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:lh,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 RA({open:t,onClose:s,onSelectTemplate:a}){var d,m,p;const[r,n]=h.useState(null),[i,l]=h.useState(!1);h.useEffect(()=>{const x=at.getUserData();l((x==null?void 0:x.jobTitle)==="Dealer")},[]);const o=x=>{if(i)return;const u=Nn.find(g=>g.id===x);u!=null&&u.disabled||n(x)},c=()=>{r&&(a(r),s())};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{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(ut,{className:"sr-only",children:"Select a Template"}),e.jsx(_t,{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(Cs,{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(Ht.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(Yi,{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:Nn.map((x,u)=>{const g=x.icon,f=r===x.id,b=i||x.disabled;return e.jsx(Ht.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:u*.1},whileHover:b?{}:{scale:1.03},whileTap:b?{}:{scale:.98},children:e.jsxs(q,{className:`h-full transition-all duration-300 border-2 ${b?"opacity-50 cursor-not-allowed border-gray-200":f?"cursor-pointer border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"cursor-pointer border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>o(x.id),children:[e.jsxs(oe,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl bg-gradient-to-br ${x.color} flex items-center justify-center shadow-md`,children:e.jsx(g,{className:"w-7 h-7 text-white"})}),f&&e.jsx(Ht.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(za,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(de,{className:"text-xl mb-2",children:x.name}),e.jsx(ye,{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(ee,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(ae,{variant:"secondary",className:"text-xs",children:x.category})}),e.jsx(Qt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(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(qt,{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((j,y)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(Oe,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:j})]},y)),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(Ht.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(M,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(M,{onClick:c,disabled:!r||i||((d=Nn.find(x=>x.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=Nn.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(fs,{className:"w-4 h-4"})]})]}),e.jsx(ll,{children:r&&e.jsx(Ht.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},className:"mt-6 text-center",children:e.jsxs("p",{className:"text-sm text-gray-600",children:["Selected: ",e.jsx("span",{className:"font-semibold text-blue-600",children:(p=Nn.find(x=>x.id===r))==null?void 0:p.name})]})})})]})})]})})}function Lr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=h.useState(100),[m,p]=h.useState(0),[x,u]=h.useState(null),[g,f]=h.useState(!1),[b,j]=h.useState(null),y=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),w=s.toLowerCase().includes("pdf"),v=y||w;h.useEffect(()=>{if(!l||!v||!a){u(null);return}return(async()=>{f(!0),j(null);try{let S=a;a.startsWith("/")&&!a.startsWith("//")&&(S=`${window.location.origin}${a}`);const F=await fetch(S,{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 P=window.URL.createObjectURL($);u(P)}catch(N){console.error("Failed to load file for preview:",N),j(N instanceof Error?N.message:"Failed to load file for preview")}finally{f(!1)}})(),()=>{x&&(window.URL.revokeObjectURL(x),u(null))}},[l,a,v,w]);const C=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},A=()=>d(R=>Math.min(R+25,200)),L=()=>d(R=>Math.max(R-25,50)),D=()=>p(R=>(R+90)%360);return e.jsx(ht,{open:l,onOpenChange:o,children:e.jsx(mt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(pt,{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(St,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ut,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`• ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[y&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(M,{variant:"ghost",size:"sm",onClick:L,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(vb,{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(M,{variant:"ghost",size:"sm",onClick:A,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(Nb,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:D,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(oh,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(M,{variant:"outline",size:"sm",onClick:C,className:"gap-2 h-9",children:[e.jsx(Rt,{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(Qe,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):b?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(jt,{className:"w-10 h-10 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Failed"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:b}),i&&n&&e.jsxs(M,{onClick:C,className:"gap-2",children:[e.jsx(Rt,{className:"h-4 w-4"}),"Download ",t]})]}):v&&x?e.jsxs(e.Fragment,{children:[y&&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:()=>{j("Failed to load PDF preview")}})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(St,{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(M,{onClick:C,className:"gap-2",children:[e.jsx(Rt,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function ti({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following policy violations were detected:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:a.map((n,i)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:n.type}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:n.message}),n.currentValue!==void 0&&n.maxValue!==void 0&&e.jsxs("p",{className:"text-xs text-red-600 mt-1 font-semibold",children:["Current: ",n.currentValue," / Maximum: ",n.maxValue]})]},i))}),r&&e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"System Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[r.maxApprovalLevels!==void 0&&e.jsxs("li",{children:["Maximum approval levels: ",r.maxApprovalLevels]}),r.maxParticipants!==void 0&&e.jsxs("li",{children:["Maximum participants per request: ",r.maxParticipants]}),r.allowSpectators!==void 0&&e.jsxs("li",{children:["Allow adding spectators: ",r.allowSpectators?"Yes":"No"]}),r.maxSpectators!==void 0&&e.jsxs("li",{children:["Maximum spectators per request: ",r.maxSpectators]})]})]})]})})]}),e.jsx(Et,{children:e.jsx(M,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const la=async t=>{const s=t?{category:t}:{};return(await je.get("/users/configurations",{params:s})).data.data},ml=async t=>{const s=t?{category:t}:{};return(await je.get("/admin/configurations",{params:s})).data.data},Vs=async(t,s)=>{await je.put(`/admin/configurations/${t}`,{configValue:s})},DA=async t=>{await je.post(`/admin/configurations/${t}/reset`)},FA=async()=>{const t=await je.get("/admin/form16-config");return t.data.data??t.data},IA=async t=>{await je.put("/admin/form16-config",t)},PA=async t=>{const s=t?{year:t}:{};return(await je.get("/admin/holidays",{params:s})).data.data},EA=async t=>(await je.post("/admin/holidays",t)).data.data,_A=async(t,s)=>(await je.put(`/admin/holidays/${t}`,s)).data.data,MA=async t=>{await je.delete(`/admin/holidays/${t}`)},LA=async()=>(await je.get("/config/activity-types")).data.data,OA=async t=>{const s={activeOnly:t.toString()};return(await je.get("/admin/activity-types",{params:s})).data.data},$A=async t=>(await je.post("/admin/activity-types",t)).data.data,UA=async(t,s)=>(await je.put(`/admin/activity-types/${t}`,s)).data.data,BA=async t=>{await je.delete(`/admin/activity-types/${t}`)},VA={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 zA(t,s,a){const[r,n]=h.useState(VA),[i,l]=h.useState(null),[o,c]=h.useState(t),[d,m]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[p,x]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[u,g]=h.useState([]);return h.useEffect(()=>{(async()=>{var j;try{const y=await la("DOCUMENT_POLICY"),w={};y.forEach(_=>{w[_.configKey]=_.configValue});const v=parseInt(w.MAX_FILE_SIZE_MB||"10"),A=(w.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(_=>_.trim().toLowerCase());x({maxFileSizeMB:v,allowedFileTypes:A});const L=await la("SYSTEM_SETTINGS"),D=await la("WORKFLOW_SHARING"),R=[...L,...D],N={};R.forEach(_=>{N[_.configKey]=_.configValue}),m({maxApprovalLevels:parseInt(N.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(N.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((j=N.ALLOW_ADD_SPECTATOR)==null?void 0:j.toLowerCase())==="true",maxSpectators:parseInt(N.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(y){console.error("Failed to load policies:",y)}})()},[]),h.useEffect(()=>{if(!t||!s)return;let b=!0;return(async()=>{try{c(!0);const j=await Es(s);if(!b||!j)return;const y=j.workflow||{},w=Array.isArray(j.approvals)?j.approvals:[],v=Array.isArray(j.participants)?j.participants:[],C=Array.isArray(j.documents)?j.documents.filter(S=>!S.isDeleted):[];g(C);const A=(y.priority||"").toString().toLowerCase(),L={standard:"standard",express:"express"},D=y.templateType==="TEMPLATE"?"existing-template":"custom",R=a.find(S=>S.id===D)||a[0]||null;l(R);const N=w.sort((S,U)=>(S.levelNumber||0)-(U.levelNumber||0)).map(S=>{const U=Number(S.tatHours||24),F=Math.floor(U/24),$=U%24;return{id:S.approverId||`temp-${S.levelNumber}`,name:S.approverName||S.approverEmail||"",email:S.approverEmail||"",role:S.levelName||`Level ${S.levelNumber}`,department:"",avatar:(S.approverName||S.approverEmail||"XX").substring(0,2).toUpperCase(),level:S.levelNumber||1,canClose:!1,tat:F>0?F:$,tatType:F>0?"days":"hours",userId:S.approverId}}),_=v.filter(S=>(S.participantType||S.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(S.userEmail||S.user_email||S.email):!1).map((S,U)=>{const F=S.userId||S.user_id||S.id,$=S.userName||S.user_name||S.name||"",P=S.userEmail||S.user_email||S.email||"",k=($||P||"XX").split(" ").map(B=>B[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:F||`spectator-${s}-${U}-${Date.now()}`,userId:F,name:$||P||"Spectator",email:P,role:"Spectator",department:S.department||"",avatar:k,level:1,canClose:!1}});n(S=>({...S,template:D,title:y.title||"",description:y.description||"",priority:L[A]||"standard",approvers:N,approverCount:N.length||1,spectators:_,maxLevel:Math.max(...N.map(U=>U.level||1),1)}))}catch(j){console.error("Failed to load draft:",j)}finally{b&&c(!1)}})(),()=>{b=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(b,j)=>{n(y=>({...y,[b]:j}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:d,documentPolicy:p,existingDocuments:u,setExistingDocuments:g}}const ux=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function HA(t,s,a){const[r,n]=h.useState(t?2:1),i=ux.length,l=p=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p),o=()=>{switch(r){case 1:return s!==null;case 2:return a.title.trim()!==""&&a.description.trim()!==""&&a.priority!=="";case 3:return(a.approverCount||1)>0&&a.approvers.length===(a.approverCount||1)&&a.approvers.every(p=>{if(!p||!p.email||!l(p.email))return!1;if(!p.userId)return!0;const x=p.tatType||"hours";return x==="hours"?p.tat&&p.tat>0&&p.tat<=720:x==="days"?p.tat&&p.tat>0&&p.tat<=30:!1});case 4:return!0;case 5:return!0;case 6:return!0;default:return!1}};return{currentStep:r,setCurrentStep:n,totalSteps:i,stepNames:ux,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:p=>{p>=1&&p<=i&&n(p)},validateEmail:l}}function WA(){const[t,s]=h.useState({open:!1,type:"error",email:"",message:""}),[a,r]=h.useState({open:!1,violations:[]}),[n,i]=h.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 GA(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function YA(t,s,a){var n;const r=GA(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 KA(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return YA(a,n,n===s)})}function xx(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 hx(t,s,a,r=!1){const n=KA(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 QA(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 px(t,s){return{id:(await ic(t,s||[],"SUPPORTING")).id}}async function gx(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await Pw(t,s,a||[],r):await Iw(t,s)}function XA({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=h.useState(!1),[m,p]=h.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var f,b;if(c||m)return;const g=QA(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const j=hx(t,n,r,!1);await gx(l,j,a,r),X.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 j=xx(t,s,n,!1),y=await px(j,a);X.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been created and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:y.id,template:s})}}catch(j){console.error("Failed to submit workflow:",j),X.error("Failed to Submit Request",{description:((b=(f=j==null?void 0:j.response)==null?void 0:f.data)==null?void 0:b.message)||(j==null?void 0:j.message)||"An error occurred while submitting the request.",duration:5e3}),d(!1)}},handleSaveDraft:async()=>{var g,f;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||m)){p(!0);try{if(i&&l){const b=hx(t,n,r,!0);await gx(l,b,a,r),X.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const b=xx(t,s,n,!0),j=await px(b,a);X.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:j.id,template:s})}}catch(b){console.error("Failed to save draft:",b),X.error("Failed to Save Draft",{description:((f=(g=b==null?void 0:b.response)==null?void 0:g.data)==null?void 0:f.message)||(b==null?void 0:b.message)||"An error occurred while saving the draft.",duration:5e3}),p(!1)}}}}}async function ba(t,s=10,a="default"){return await je.get("/users/search",{params:{q:t,limit:s,source:a}})}async function ga(t){var a;const s=await je.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function JA(t,s){return await je.post("/admin/users/assign-role",{email:t,role:s})}async function ZA(t,s){return await je.put(`/admin/users/${t}/role`,{role:s})}async function qA(t,s=1,a=10){return await je.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function eT(){return await je.get("/admin/users/role-statistics")}async function tT(t){var a;const s=await je.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function sT(){var s,a;return((a=(s=(await je.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const sa={searchUsers:ba,getUserById:tT,ensureUserExists:ga,assignRole:JA,updateUserRole:ZA,getUsersByRole:qA,getRoleStatistics:eT,getAllUsers:sT};async function aT(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 ba(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 ga({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 rT(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 R=new Date;R.setDate(R.getDate()+D.suggestedSLA),a("slaEndDate",R),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"){f(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&p){const _=r.approverCount||1;if(_>m.maxApprovalLevels){p([{type:"Maximum Approval Levels Exceeded",message:`The request has ${_} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:_,maxValue:m.maxApprovalLevels}]);return}}const R=((D=c==null?void 0:c.email)==null?void 0:D.toLowerCase())||"",N=await rT(r.approvers,R);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,R)=>{if(R){const N=D.documentId||D.document_id||"";j({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:mn(N),fileSize:Number(D.fileSize||D.file_size||0),documentId:N})}else{const N=URL.createObjectURL(D);j({fileName:D.name,fileType:D.type||"application/octet-stream",fileUrl:N,fileSize:D.size,file:D})}},closePreview:()=>{b!=null&&b.fileUrl&&(b!=null&&b.file)&&URL.revokeObjectURL(b.fileUrl),j(null)}}}const fx=[{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:Ki,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:Ie,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let Pr=null;const bx=()=>Pr,iT=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 Pr&&Pr.push(r),r},ul=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 Pr=a,a},lT=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 Pr&&(Pr=Pr.map(i=>i.id===t?n:i)),n};function Kg({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 oT({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(M,{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(Cs,{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(M,{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(Qe,{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(M,{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(Qe,{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(ch,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(M,{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(fs,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const jx=t=>{switch(t){case"high":return e.jsx(Ca,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(qt,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ws,{className:"w-4 h-4 text-green-600"});default:return e.jsx(qt,{className:"w-4 h-4 text-gray-600"})}};function cT({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=h.useState("main"),l=ys(),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(Ht.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(M,{variant:"ghost",className:"gap-2",onClick:()=>i("main"),children:[e.jsx(Cs,{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(wb,{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(Ht.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${m.id}`,children:e.jsxs(q,{className:`h-full transition-all duration-300 border-2 ${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(oe,{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(Ht.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(za,{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(de,{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(ae,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),jx(m.priority)]})]})]}),e.jsxs(ee,{className:"pt-0 space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed line-clamp-2","data-testid":`template-card-${m.id}-description`,children:m.description}),!x&&e.jsxs(e.Fragment,{children:[e.jsx(Qt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-estimated-time`,children:[e.jsx(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(Jt,{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(ll,{children:s&&e.jsx(Ht.div,{initial:{opacity:0,y:20,height:0},animate:{opacity:1,y:0,height:"auto"},exit:{opacity:0,y:-20,height:0},transition:{duration:.3},className:"w-full max-w-6xl","data-testid":"template-details-card",children:e.jsxs(q,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(_r,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(ee,{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(te,{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(te,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[jx(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(te,{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(te,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((d=s.commonApprovers)==null?void 0:d.length)>0?s.commonApprovers.map((m,p)=>e.jsx(ae,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${p}`,children:m},`${s.id}-approver-${p}-${m}`)):e.jsx("span",{className:"text-sm text-gray-500 italic",children:"No specific approvers defined"})})]})]})]})})})]})}function Ce({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:Me("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 dT({className:t,...s}){return e.jsx(Df,{"data-slot":"radio-group",className:Me("grid gap-3",t),...s})}function yx({className:t,...s}){return e.jsx(Ff,{"data-slot":"radio-group-item",className:Me("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(If,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(Bo,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function mT({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(Ht.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(Ie,{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(te,{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(Ce,{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(te,{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(Xn,{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(te,{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(dT,{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(yx,{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(Gi,{className:"w-4 h-4 text-red-600"}),e.jsx(te,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(ae,{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(yx,{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(te,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(ae,{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(te,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(Ce,{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(te,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(He,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Ge,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(We,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"USD",children:"USD ($)"}),e.jsx(J,{value:"EUR",children:"EUR (€)"}),e.jsx(J,{value:"GBP",children:"GBP (£)"}),e.jsx(J,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(te,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(Ce,{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(te,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(Ce,{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(te,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(Ce,{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 Qg(){const[t,s]=h.useState([]),[a,r]=h.useState(!1),n=h.useRef(null);return{searchResults:t,searchLoading:a,searchUsersDebounced:async(c,d=10)=>{if(n.current&&clearTimeout(n.current),!c||!c.startsWith("@")||c.length<2){s([]),r(!1);return}r(!0),n.current=setTimeout(async()=>{var m;try{const p=c.slice(1),u=((m=(await ba(p,d)).data)==null?void 0:m.data)||[];s(u)}catch(p){console.error("User search failed:",p),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await ga({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 Xg(){const[t,s]=h.useState({}),[a,r]=h.useState({}),n=h.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(o,c,d=10)=>{if(n.current[o]&&clearTimeout(n.current[o]),!c||!c.startsWith("@")||c.length<2){s(m=>({...m,[o]:[]})),r(m=>({...m,[o]:!1}));return}r(m=>({...m,[o]:!0})),n.current[o]=setTimeout(async()=>{var m;try{const p=c.slice(1),u=((m=(await ba(p,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:u}))}catch(p){console.error(`User search failed for index ${o}:`,p),s(x=>({...x,[o]:[]}))}finally{r(p=>({...p,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function uT({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var p;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=Xg();h.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 j,y,w,v,C;const g=[...t.approvers],b=((j=g[x])==null?void 0:j.email)!==u;if(g[x]={...g[x],email:u,level:x+1,userId:b||(y=g[x])==null?void 0:y.userId,name:b||(w=g[x])==null?void 0:w.name,department:b||(v=g[x])==null?void 0:v.department,avatar:b||(C=g[x])==null?void 0:C.avatar},s("approvers",g),!u||!u.startsWith("@")||u.length<2){c(x);return}o(x,u,10)},m=async(x,u)=>{var g,f;try{if((g=t.approvers)==null?void 0:g.some((v,C)=>{var A,L;return C!==x&&(v.userId===u.userId||((A=v.email)==null?void 0:A.toLowerCase())===((L=u.email)==null?void 0:L.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((f=t.spectators)==null?void 0:f.some(v=>{var C,A;return v.userId===u.userId||((C=v.email)==null?void 0:C.toLowerCase())===((A=u.email)==null?void 0:A.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 y=await ga({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:y.userId,level:x+1},s("approvers",w),c(x)}catch(b){console.error("Failed to ensure user exists:",b),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(Ht.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(Jt,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"approval-workflow-title",children:"Approval Workflow"}),e.jsx("p",{className:"text-gray-600","data-testid":"approval-workflow-description",children:"Define the approval hierarchy and assign approvers by email ID."})]}),e.jsxs("div",{className:"max-w-4xl mx-auto space-y-8","data-testid":"approval-workflow-content",children:[e.jsxs(q,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(cr,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(ye,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(ee,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(te,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(M,{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(Vo,{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(M,{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(bs,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Maximum ",r.maxApprovalLevels," approver",r.maxApprovalLevels!==1?"s":""," allowed. Each approver will review sequentially."]})]})})]}),e.jsxs(q,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(ps,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs(ye,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(ee,{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(ae,{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 j,y;const g=u+1,f=g===(t.approverCount||1),b=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 ${b.email?"border-green-200 bg-green-50":"border-gray-200 bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${b.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:g})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",g]}),f&&e.jsx(ae,{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(te,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),b.email&&b.userId&&e.jsxs(ae,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Oe,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ce,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:b.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]||(((j=i[u])==null?void 0:j.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:(y=i[u])==null?void 0:y.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(te,{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(Ce,{id:`tat-${g}`,type:"number",placeholder:b.tatType==="days"?"7":"24",min:"1",max:b.tatType==="days"?"30":"720",value:b.tat||"",onChange:w=>{const v=[...t.approvers];v[u]={...v[u],tat:parseInt(w.target.value)||"",level:g,tatType:b.tatType||"hours"},s("approvers",v)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(He,{value:b.tatType||"hours",onValueChange:w=>{const v=[...t.approvers];v[u]={...v[u],tatType:w,level:g,tat:""},s("approvers",v)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(Ge,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(We,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"hours",children:"Hours"}),e.jsx(J,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},g)})]})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(_r,{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((f,b)=>{const j=Number(b.tat||0);return(b.tatType||"hours")==="days"?f+j:f+j/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:(p=t.approvers)==null?void 0:p.map((x,u)=>{const g=Number(x.tat||0),b=(x.tatType||"hours")==="days"?g*24:g;return g?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",u+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[b," ",b===1?"hour":"hours"]})]})},u):null})}),(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((f,b)=>{const j=Number(b.tat||0);return(b.tatType||"hours")==="days"?f+j*24:f+j},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 xT({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=h.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=Qg(),p=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},x=async g=>{var f,b;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const j=t.spectators.some(w=>{var v,C;return w.userId===g.userId||((v=w.email)==null?void 0:v.toLowerCase())===((C=g.email)==null?void 0:C.toLowerCase())}),y=(f=t.approvers)==null?void 0:f.some(w=>{var v,C;return w.userId===g.userId||((v=w.email)==null?void 0:v.toLowerCase())===((C=g.email)==null?void 0:C.toLowerCase())});if(j){a({type:"error",email:g.email,message:"This user is already added as a spectator."});return}if(y){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),v={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},C=[...t.spectators,v];s("spectators",C),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 j=t.spectators.some(w=>{var v;return((v=w.email)==null?void 0:v.toLowerCase())===n.toLowerCase()}),y=(b=t.approvers)==null?void 0:b.some(w=>{var v;return((v=w.email)==null?void 0:v.toLowerCase())===n.toLowerCase()});if(j){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(y){a({type:"error",email:n,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}}},u=g=>{const f=t.spectators.filter(b=>b.id!==g);s("spectators",f)};return e.jsxs(Ht.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(St,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"participants-title",children:"Participants & Access"}),e.jsx("p",{className:"text-gray-600","data-testid":"participants-description",children:"Configure additional participants and visibility settings for your request."})]}),e.jsx("div",{className:"max-w-3xl mx-auto space-y-8","data-testid":"participants-content",children:e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:e.jsxs(q,{"data-testid":"participants-spectators-card",children:[e.jsxs(oe,{children:[e.jsxs(de,{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(St,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(ae,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(ye,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(ee,{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(Ce,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>p(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.preventDefault(),await x())},className:"text-sm w-full","data-testid":"participants-spectators-email-input"}),(o||l.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:o?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:l.map(g=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>x(g),"data-testid":`participants-spectators-search-result-${g.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:g.displayName||g.email}),e.jsx("div",{className:"text-xs text-gray-600",children:g.email})]},g.userId))})})]}),e.jsx(M,{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(_r,{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(ls,{className:"h-6 w-6",children:e.jsx(os,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>u(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(jt,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function hT({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:c,onDocumentErrors:d,fileInputRef:m}){const p=f=>{const b=Array.from(f.target.files||[]);if(b.length===0)return;const j=t.maxFileSizeMB*1024*1024,y=[],w=[];b.forEach(v=>{if(v.size>j){y.push({fileName:v.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(v.size/1048576).toFixed(2)}MB`});return}const C=v.name.toLowerCase(),A=C.substring(C.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(A)){y.push({fileName:v.name,reason:`File type "${A}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}w.push(v)}),w.length>0&&i([...a,...w]),y.length>0&&d&&d(y),f.target&&(f.target.value="")},x=f=>{const b=a.filter((j,y)=>y!==f);i(b)},u=f=>{o([...n,f])},g=(f,b=!1)=>{if(b){const j=(f.fileType||f.file_type||"").toLowerCase(),y=(f.originalFileName||f.fileName||"").toLowerCase();return j.includes("image")||j.includes("pdf")||y.endsWith(".jpg")||y.endsWith(".jpeg")||y.endsWith(".png")||y.endsWith(".gif")||y.endsWith(".pdf")}else{const j=(f.type||"").toLowerCase(),y=(f.name||"").toLowerCase();return j.includes("image")||j.includes("pdf")||y.endsWith(".jpg")||y.endsWith(".jpeg")||y.endsWith(".png")||y.endsWith(".gif")||y.endsWith(".pdf")}};return e.jsxs(Ht.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(js,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"documents-title",children:"Documents & Attachments"}),e.jsx("p",{className:"text-gray-600","data-testid":"documents-description",children:"Upload supporting documents, files, and any additional materials for your request."})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"documents-content",children:[e.jsxs(q,{"data-testid":"documents-upload-card",children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Ie,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs(ye,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(ee,{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(js,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"click to browse"}),e.jsx("input",{type:"file",multiple:!0,accept:t.allowedFileTypes.map(f=>`.${f}`).join(","),onChange:p,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(M,{variant:"outline",size:"lg",type:"button",onClick:()=>{var f;return(f=m.current)==null?void 0:f.click()},"data-testid":"documents-browse-button",children:[e.jsx(bs,{className:"w-4 h-4 mr-2"}),"Browse Files"]}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Supported formats: ",t.allowedFileTypes.map(f=>f.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(q,{"data-testid":"documents-existing-card",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ae,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(f=>!n.includes(f.documentId||f.document_id||"")).length," file",r.filter(f=>!n.includes(f.documentId||f.document_id||"")).length!==1?"s":""]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(f=>{const b=f.documentId||f.document_id||"";return n.includes(b)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${b}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Ie,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:f.originalFileName||f.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:f.fileSize?(Number(f.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(f,!0)&&e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>c(f,!0),"data-testid":`documents-existing-${b}-preview`,children:e.jsx(St,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>u(b),"data-testid":`documents-existing-${b}-delete`,children:e.jsx(jt,{className:"h-4 w-4 text-red-600"})})]})]},b)})})})]}),a.length>0&&e.jsxs(q,{"data-testid":"documents-new-card",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ae,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((f,b)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${b}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Ie,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:f.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(f.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(f,!1)&&e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>c(f,!1),"data-testid":`documents-new-${b}-preview`,children:e.jsx(St,{className:"h-4 w-4"})}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>x(b),"data-testid":`documents-new-${b}-remove`,children:e.jsx(jt,{className:"h-4 w-4"})})]})]},b))})})]})]})]})}const pT=t=>{switch(t){case"high":return e.jsx(Ca,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(qt,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Ws,{className:"w-4 h-4 text-green-600"});default:return e.jsx(qt,{className:"w-4 h-4 text-gray-600"})}};function gT({formData:t,selectedTemplate:s}){return e.jsxs(Ht.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(Oe,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"review-submit-title",children:"Review & Submit"}),e.jsx("p",{className:"text-gray-600","data-testid":"review-submit-description",children:"Please review all details before submitting your request for approval."})]}),e.jsxs("div",{className:"max-w-5xl mx-auto space-y-8","data-testid":"review-submit-content",children:[e.jsxs(q,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(ch,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(ee,{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(te,{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(ae,{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(te,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[pT(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(te,{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(te,{className:"text-green-900 font-semibold",children:"Request Title"}),e.jsx("p",{className:"text-green-800 font-medium mt-1 text-lg",children:t.title})]})]})]}),e.jsxs(q,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Ie,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(te,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(_s,{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(Ha,{className:"w-4 h-4 text-blue-600"}),e.jsx(te,{className:"font-semibold text-blue-900",children:"Financial Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Amount"}),e.jsxs("p",{className:"font-semibold text-blue-900",children:[t.amount," ",t.currency]})]}),t.costCenter&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Cost Center"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.costCenter})]})]})]})]})]}),e.jsxs(q,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(Jt,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx(ye,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(ee,{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(ae,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Email Address"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:(l==null?void 0:l.email)||"Not assigned"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"TAT (Turn Around Time)"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l!=null&&l.tat?`${l.tat} ${l.tatType==="days"?"day":"hour"}${l.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(q,{"data-testid":"review-submit-participants-card",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(St,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(ee,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(te,{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(ae,{variant:"outline",className:"text-xs","data-testid":`review-submit-spectator-${a.id}`,children:[a.name," (",a.email,")"]},a.id))})]})})]}),t.documents.length>0&&e.jsxs(q,{"data-testid":"review-submit-documents-card",children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(js,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(ye,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(ee,{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(Ie,{className:"w-5 h-5 text-gray-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.name}),e.jsx("div",{className:"flex items-center gap-3 text-xs text-gray-500 mt-1",children:e.jsxs("span",{children:[(a.size/(1024*1024)).toFixed(2)," MB"]})})]})]},r))})})]}),e.jsx(q,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Oe,{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 fT({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(M,{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(Cs,{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 bT({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(ll,{mode:"wait",children:t})})})}function jT({modal:t,onClose:s}){return e.jsx(ht,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(ut,{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(_t,{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(Ki,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use"," ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," ","sign to search and select users from the directory for guaranteed results."]})})]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:[t.email&&e.jsxs(e.Fragment,{children:["Failed to validate ",e.jsx("strong",{children:t.email}),"."]}),!t.email&&e.jsx(e.Fragment,{children:"An error occurred during validation."})]}),t.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:t.message})})]})]})})]}),e.jsx(Et,{children:e.jsx(M,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function yT({modal:t,documentPolicy:s,onClose:a}){return e.jsx(ht,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(mt,{className:"sm:max-w-lg",children:[e.jsxs(pt,{children:[e.jsxs(ut,{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(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:t.errors.map((r,n)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3","data-testid":`document-error-${n}`,children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:r.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:r.reason})]},n))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",s.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types:"," ",s.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Et,{children:e.jsx(M,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function vx({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=_a(),i=ys(),l=n.requestId||a||"",o=r&&!!l,{user:c}=cs(),[d,m]=h.useState([]);h.useEffect(()=>{(async()=>{try{const Fe=(await ul()).map(_e=>({id:_e.id,name:_e.name,description:_e.description,category:_e.category,icon:Ie,estimatedTime:_e.estimatedTime,commonApprovers:_e.approvers.map(Xe=>Xe.name),workflowApprovers:_e.approvers,suggestedSLA:_e.suggestedSLA,priority:_e.priority,fields:_e.fields||{}}));m(Fe)}catch(ge){console.error("Failed to fetch admin templates:",ge)}})()},[]);const p=h.useMemo(()=>[...fx,...d],[d]),{formData:x,updateFormData:u,selectedTemplate:g,setSelectedTemplate:f,loadingDraft:b,systemPolicy:j,documentPolicy:y,existingDocuments:w,setExistingDocuments:v}=zA(o,l,p),{currentStep:C,totalSteps:A,stepNames:L,isStepValid:D,nextStep:R,prevStep:N}=HA(o,g,x),[_,S]=h.useState([]),[U,F]=h.useState([]),$=h.useRef(null),{validationModal:P,policyViolationModal:T,documentErrorModal:k,openValidationModal:B,closeValidationModal:I,openPolicyViolationModal:E,closePolicyViolationModal:W,openDocumentErrorModal:V,closeDocumentErrorModal:Y}=WA(),{submitting:Z,savingDraft:O,handleSubmit:z,handleSaveDraft:K}=XA({formData:x,selectedTemplate:g,documents:_,documentsToDelete:U,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:re,setShowTemplateModal:G,previewDocument:se,selectTemplate:ve,handleTemplateSelection:Te,nextStep:Ke,prevStep:Je,handlePreviewDocument:Pe,closePreview:$e}=nT({selectedTemplate:g,setSelectedTemplate:f,updateFormData:u,formData:x,currentStep:C,isStepValid:D,wizardNextStep:R,wizardPrevStep:N,user:c,openValidationModal:B,systemPolicy:j,onPolicyViolation:E,onSubmit:s}),ne=h.useCallback(()=>{if(C===1){i("/dashboard",{replace:!0});return}C===3||C===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Je()},[C,t,i,Je]),he=h.useRef(!0),Ne=h.useRef(!1);h.useEffect(()=>{he.current&&x.documents&&x.documents.length>0&&!Ne.current&&(S(x.documents),Ne.current=!0),he.current=!1},[x.documents]);const Ae=h.useRef(!1),Q=h.useRef(_);h.useEffect(()=>{if(Ae.current){Ae.current=!1,Q.current=_;return}Q.current!==_&&(u("documents",_),Q.current=_)},[_]);const le=()=>{switch(C){case 1:return e.jsx(cT,{templates:fx,selectedTemplate:g,onSelectTemplate:ve,adminTemplates:d});case 2:return e.jsx(mT,{formData:x,selectedTemplate:g,updateFormData:u});case 3:return e.jsx(uT,{formData:x,updateFormData:u,systemPolicy:j,onValidationError:pe=>B(pe.type,pe.email,pe.message),onPolicyViolation:E});case 4:return e.jsx(xT,{formData:x,updateFormData:u,onValidationError:pe=>B(pe.type,pe.email,pe.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(hT,{documentPolicy:y,isEditing:o,documents:_,existingDocuments:w,documentsToDelete:U,onDocumentsChange:S,onExistingDocumentsChange:v,onDocumentsToDeleteChange:F,onPreviewDocument:Pe,onDocumentErrors:pe=>V(pe),fileInputRef:$});case 6:return e.jsx(gT,{formData:x,selectedTemplate:g});default:return null}};return b?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center","data-testid":"create-request-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading draft..."})]})}):e.jsxs("div",{className:"h-full flex flex-col bg-gradient-to-br from-gray-50 to-white","data-testid":"create-request",children:[e.jsx(fT,{isEditing:o,currentStep:C,totalSteps:A,stepNames:L,onBack:ne}),e.jsx(Kg,{currentStep:C,totalSteps:A,stepNames:L}),e.jsx(bT,{children:le()}),e.jsx(oT,{currentStep:C,totalSteps:A,isStepValid:D(),onPrev:Je,onNext:Ke,onSubmit:z,onSaveDraft:K,submitting:Z,savingDraft:O,loadingDraft:b,isEditing:o}),e.jsx(RA,{open:re,onClose:()=>G(!1),onSelectTemplate:Te}),se&&e.jsx(Lr,{fileName:se.fileName,fileType:se.fileType,fileUrl:se.fileUrl,fileSize:se.fileSize,open:!!se,onClose:$e,onDownload:async()=>{if(se.file){const pe=document.createElement("a");pe.href=se.fileUrl,pe.download=se.fileName,document.body.appendChild(pe),pe.click(),document.body.removeChild(pe)}else se.documentId&&await Ls(se.documentId)},attachmentId:se.documentId}),e.jsx(jT,{modal:P,onClose:I}),e.jsx(yT,{modal:k,documentPolicy:y,onClose:Y}),e.jsx(ti,{open:T.open,onClose:W,violations:T.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}function si({className:t,...s}){return e.jsx(Pf,{"data-slot":"tabs",className:Me("flex flex-col gap-2",t),...s})}function ai({className:t,...s}){return e.jsx(Ef,{"data-slot":"tabs-list",className:Me("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function Lt({className:t,...s}){return e.jsx(_f,{"data-slot":"tabs-trigger",className:Me("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 Ot({className:t,...s}){return e.jsx(Mf,{"data-slot":"tabs-content",className:Me("flex-1 outline-none",t),...s})}function Vc(t,s=[],a){const[r,n]=h.useState(null),[i,l]=h.useState(!1),[o,c]=h.useState(!0),[d,m]=h.useState(null),[p,x]=h.useState(null),[u,g]=h.useState(!1),f=(C,A)=>(C||A||"NA").toString().split(" ").map(D=>D[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),b=C=>{const A=(C||"").toUpperCase();return A==="IN_PROGRESS"?"in-review":A==="PENDING"?"pending":A==="APPROVED"?"approved":A==="REJECTED"?"rejected":A==="CLOSED"?"closed":A==="SKIPPED"?"skipped":(C||"").toLowerCase()},j=h.useCallback(async()=>{var C,A,L,D,R,N,_,S,U,F,$,P,T;l(!0);try{const k=await Gs.getWorkflowDetails(t);if(!k){console.warn("[useRequestDetails] No details returned from API");return}const B=k.workflow||{},I=Array.isArray(k.approvals)?k.approvals:[],E=Array.isArray(k.participants)?k.participants:[],W=Array.isArray(k.documents)?k.documents:[],V=k.summary||{},Y=Array.isArray(k.tatAlerts)?k.tatAlerts:[];Y.length>0;const Z=(V==null?void 0:V.currentLevel)||B.currentLevel||1,O=I.map(Q=>{const le=Q.levelNumber||0,pe=(Q.status||"").toString().toUpperCase(),ge=Q.levelId||Q.level_id;let Fe=b(Q.status);le>Z&&pe!=="APPROVED"&&pe!=="REJECTED"?Fe="waiting":le===Z&&pe==="PENDING"&&(Fe="pending");const _e=Y.filter(Xe=>Xe.levelId===ge);return{step:le,levelId:ge,role:Q.levelName||Q.approverName||"Approver",status:Fe,approver:Q.approverName||Q.approverEmail,approverId:Q.approverId||Q.approver_id,approverEmail:Q.approverEmail,tatHours:Number(Q.tatHours||0),elapsedHours:Number(Q.elapsedHours||0),remainingHours:Number(Q.remainingHours||0),tatPercentageUsed:Number(Q.tatPercentageUsed||0),actualHours:Q.levelEndTime&&Q.levelStartTime?Math.max(0,(new Date(Q.levelEndTime).getTime()-new Date(Q.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:Q.comments||void 0,timestamp:Q.actionDate||void 0,levelStartTime:Q.levelStartTime||Q.tatStartTime,tatAlerts:_e,skipReason:Q.skipReason||void 0,isSkipped:pe==="SKIPPED"||Q.isSkipped||!1}}),z=E.filter(Q=>(Q.participantType||Q.participant_type||"").toUpperCase()==="SPECTATOR").map(Q=>({name:Q.userName||Q.user_name||Q.userEmail||Q.user_email,role:"Spectator",email:Q.userEmail||Q.user_email,avatar:f(Q.userName||Q.user_name,Q.userEmail||Q.user_email)})),K=Q=>{var pe,ge;if(!Q)return;const le=E.find(Fe=>Fe.userId===Q||Fe.user_id===Q);return le!=null&&le.userName||le!=null&&le.user_name?le.userName||le.user_name:B.initiatorId===Q?((pe=B.initiator)==null?void 0:pe.displayName)||((ge=B.initiator)==null?void 0:ge.email):Q},re=W.map(Q=>{const le=Number(Q.fileSize||Q.file_size||0),pe=(le/(1024*1024)).toFixed(2)+" MB";return{documentId:Q.documentId||Q.document_id,name:Q.originalFileName||Q.fileName||Q.file_name,fileType:Q.fileType||Q.file_type||"",size:pe,sizeBytes:le,uploadedBy:K(Q.uploadedBy||Q.uploaded_by),uploadedAt:Q.uploadedAt||Q.uploaded_at}}),G=Array.isArray(k.activities)?k.activities.filter(Q=>(Q.type||"").toLowerCase()!=="sla_warning"):[];let se=null;if(B.isPaused||!1)try{se=await Ym(B.requestId)}catch{}let Te=null,Ke=null,Je=null,Pe=null,$e=[];if(B.workflowType==="CLAIM_MANAGEMENT"||B.templateType==="claim-management")try{const Q=await je.get(`/dealer-claims/${B.requestId}`),le=((C=Q.data)==null?void 0:C.data)||Q.data;if(le){Te=le.claimDetails||le.claim_details,Ke=le.proposalDetails||le.proposal_details,Je=le.completionDetails||le.completion_details,Pe=le.internalOrder||le.internal_order||null,$e=le.internalOrders||le.internal_orders||[];const pe=le.budgetTracking||le.budget_tracking||null,ge=le.invoice||null,Fe=le.creditNote||le.credit_note||null,_e=le.completionExpenses||le.completion_expenses||null;Te&&(Te.budgetTracking=pe,Te.invoice=ge,Te.creditNote=Fe,Te.completionExpenses=_e)}else console.warn("[useRequestDetails] No claimData found in response")}catch(Q){console.error("[useRequestDetails] Error fetching claim details:",{error:(Q==null?void 0:Q.message)||Q,status:(A=Q==null?void 0:Q.response)==null?void 0:A.status,statusText:(L=Q==null?void 0:Q.response)==null?void 0:L.statusText,responseData:(D=Q==null?void 0:Q.response)==null?void 0:D.data,requestId:B.requestId})}const ne={...B,id:B.requestNumber||B.requestId,requestId:B.requestId,requestNumber:B.requestNumber,title:B.title,description:B.description,status:b(B.status),priority:(B.priority||"").toString().toLowerCase(),workflowType:B.workflowType||(B.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:O,approvals:I,participants:E,documents:re,spectators:z,summary:V,sla:(V==null?void 0:V.sla)||B.sla||null,initiator:{name:((R=B.initiator)==null?void 0:R.displayName)||((N=B.initiator)==null?void 0:N.email),role:((_=B.initiator)==null?void 0:_.designation)||void 0,department:((S=B.initiator)==null?void 0:S.department)||void 0,email:((U=B.initiator)==null?void 0:U.email)||void 0,phone:((F=B.initiator)==null?void 0:F.phone)||void 0,avatar:f(($=B.initiator)==null?void 0:$.displayName,(P=B.initiator)==null?void 0:P.email)},createdAt:B.createdAt,updatedAt:B.updatedAt,totalSteps:B.totalLevels||1,currentStepRaw:(V==null?void 0:V.currentLevel)||B.currentLevel||1,currentStep:Math.min(Math.max(1,(V==null?void 0:V.currentLevel)||B.currentLevel||1),B.totalLevels||1),auditTrail:G,conclusionRemark:B.conclusionRemark||null,closureDate:B.closureDate||null,pauseInfo:se||null,claimDetails:Te||null,proposalDetails:Ke||null,completionDetails:Je||null,internalOrder:Pe||null,internalOrders:$e||[],budgetTracking:(Te==null?void 0:Te.budgetTracking)||null,invoice:(Te==null?void 0:Te.invoice)||(Te==null?void 0:Te.invoice)||null,creditNote:(Te==null?void 0:Te.creditNote)||null,completionExpenses:(Te==null?void 0:Te.completionExpenses)||null,templateType:B.templateType||B.template_type,form16Submission:k.form16Submission||null};n(ne);const he=(T=a==null?void 0:a.email)==null?void 0:T.toLowerCase(),Ne=I.find(Q=>{const le=(Q.status||"").toString().toUpperCase(),pe=(Q.approverEmail||"").toLowerCase(),ge=Q.levelNumber||0;return(le==="PENDING"||le==="IN_PROGRESS"||le==="PAUSED")&&pe===he&&ge===Z});x(Ne||null);const Ae=a==null?void 0:a.userId;if(Ae){const Q=E.some(le=>(le.participantType||le.participant_type||"").toUpperCase()==="SPECTATOR"&&(le.userId||le.user_id)===Ae);g(Q)}else g(!1)}catch(k){console.error("[useRequestDetails] Error refreshing details:",k),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);h.useEffect(()=>{if(!t){c(!1);return}let C=!0;return c(!0),m(null),(async()=>{var A,L,D,R,N,_,S,U,F,$,P,T,k,B;try{const I=await Gs.getWorkflowDetails(t);if(!C||!I){C&&c(!1);return}const E=I.workflow||{},W=Array.isArray(I.approvals)?I.approvals:[],V=Array.isArray(I.participants)?I.participants:[],Y=Array.isArray(I.documents)?I.documents:[],Z=I.summary||{},O=Array.isArray(I.tatAlerts)?I.tatAlerts:[],z=(E.priority||"").toString().toLowerCase(),K=(Z==null?void 0:Z.currentLevel)||E.currentLevel||1,re=W.map(ge=>{const Fe=ge.levelNumber||0,_e=(ge.status||"").toString().toUpperCase(),Xe=ge.levelId||ge.level_id;let lt=b(ge.status);_e==="PAUSED"?lt="paused":Fe>K&&_e!=="APPROVED"&&_e!=="REJECTED"?lt="waiting":Fe===K&&(_e==="PENDING"||_e==="IN_PROGRESS")&&(lt=_e==="IN_PROGRESS"?"in-review":"pending");const Nt=O.filter(wt=>wt.levelId===Xe);return{step:Fe,levelId:Xe,role:ge.levelName||ge.approverName||"Approver",status:lt,approver:ge.approverName||ge.approverEmail,approverId:ge.approverId||ge.approver_id,approverEmail:ge.approverEmail,tatHours:Number(ge.tatHours||0),elapsedHours:Number(ge.elapsedHours||0),remainingHours:Number(ge.remainingHours||0),tatPercentageUsed:Number(ge.tatPercentageUsed||0),actualHours:ge.elapsedHours!==void 0&&ge.elapsedHours!==null?Number(ge.elapsedHours):void 0,comment:ge.comments||void 0,timestamp:ge.actionDate||void 0,levelStartTime:ge.levelStartTime||ge.tatStartTime,tatAlerts:Nt}}),G=V.filter(ge=>(ge.participantType||"").toUpperCase()==="SPECTATOR").map(ge=>({name:ge.userName||ge.userEmail,role:"Spectator",avatar:f(ge.userName,ge.userEmail)})),se=ge=>{var _e,Xe;if(!ge)return;const Fe=V.find(lt=>lt.userId===ge);return Fe!=null&&Fe.userName?Fe.userName:E.initiatorId===ge?((_e=E.initiator)==null?void 0:_e.displayName)||((Xe=E.initiator)==null?void 0:Xe.email):ge},ve=Y.map(ge=>{const Fe=Number(ge.fileSize||0),_e=(Fe/(1024*1024)).toFixed(2)+" MB";return{documentId:ge.documentId||ge.document_id,name:ge.originalFileName||ge.fileName,fileType:ge.fileType||ge.file_type||"",size:_e,sizeBytes:Fe,uploadedBy:se(ge.uploadedBy),uploadedAt:ge.uploadedAt}}),Te=Array.isArray(I.activities)?I.activities.filter(ge=>(ge.type||"").toLowerCase()!=="sla_warning"):[];let Ke=null;if(E.isPaused||!1)try{Ke=await Ym(E.requestId)}catch{}let Pe=null,$e=null,ne=null,he=null,Ne=[];if(E.workflowType==="CLAIM_MANAGEMENT"||E.templateType==="claim-management")try{const ge=await je.get(`/dealer-claims/${E.requestId}`),Fe=((A=ge.data)==null?void 0:A.data)||ge.data;if(Fe){Pe=Fe.claimDetails||Fe.claim_details,$e=Fe.proposalDetails||Fe.proposal_details,ne=Fe.completionDetails||Fe.completion_details,he=Fe.internalOrder||Fe.internal_order||null,Ne=Fe.internalOrders||Fe.internal_orders||[];const _e=Fe.budgetTracking||Fe.budget_tracking||null,Xe=Fe.invoice||null,lt=Fe.creditNote||Fe.credit_note||null,Nt=Fe.completionExpenses||Fe.completion_expenses||null;Pe&&(Pe.budgetTracking=_e,Pe.invoice=Xe,Pe.creditNote=lt,Pe.completionExpenses=Nt)}}catch(ge){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(ge==null?void 0:ge.message)||ge,status:(L=ge==null?void 0:ge.response)==null?void 0:L.status,requestId:E.requestId})}const Ae={id:E.requestNumber||E.requestId,requestId:E.requestId,title:E.title,description:E.description,priority:z,status:b(E.status),workflowType:E.workflowType||(E.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:Z,initiator:{name:((D=E.initiator)==null?void 0:D.displayName)||((R=E.initiator)==null?void 0:R.email),role:((N=E.initiator)==null?void 0:N.designation)||void 0,department:((_=E.initiator)==null?void 0:_.department)||void 0,email:((S=E.initiator)==null?void 0:S.email)||void 0,phone:((U=E.initiator)==null?void 0:U.phone)||void 0,avatar:f((F=E.initiator)==null?void 0:F.displayName,($=E.initiator)==null?void 0:$.email)},createdAt:E.createdAt,updatedAt:E.updatedAt,totalSteps:E.totalLevels||1,currentStepRaw:(Z==null?void 0:Z.currentLevel)||E.currentLevel||1,currentStep:Math.min(Math.max(1,(Z==null?void 0:Z.currentLevel)||E.currentLevel||1),E.totalLevels||1),approvalFlow:re,approvals:W,documents:ve,spectators:G,auditTrail:Te,conclusionRemark:E.conclusionRemark||null,closureDate:E.closureDate||null,pauseInfo:Ke||null,claimDetails:Pe||null,proposalDetails:$e||null,completionDetails:ne||null,internalOrder:he||null,internalOrders:Ne||[],budgetTracking:(Pe==null?void 0:Pe.budgetTracking)||null,invoice:(Pe==null?void 0:Pe.invoice)||null,creditNote:(Pe==null?void 0:Pe.creditNote)||null,completionExpenses:(Pe==null?void 0:Pe.completionExpenses)||null,templateType:E.templateType||E.template_type,form16Submission:I.form16Submission||null};n(Ae);const Q=(P=a==null?void 0:a.email)==null?void 0:P.toLowerCase(),le=W.find(ge=>{const Fe=(ge.status||"").toString().toUpperCase(),_e=(ge.approverEmail||"").toLowerCase(),Xe=ge.levelNumber||0;return(Fe==="PENDING"||Fe==="IN_PROGRESS"||Fe==="PAUSED")&&_e===Q&&Xe===K});x(le||null);const pe=a==null?void 0:a.userId;if(pe){const ge=V.some(Fe=>(Fe.participantType||"").toUpperCase()==="SPECTATOR"&&Fe.userId===pe);g(ge)}else g(!1)}catch(I){if(console.error("[useRequestDetails] Error loading request details:",I),C){if(((T=I==null?void 0:I.response)==null?void 0:T.status)===403){const E=((B=(k=I==null?void 0:I.response)==null?void 0:k.data)==null?void 0:B.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:E})}n(null)}}finally{C&&c(!1)}})(),()=>{C=!1}},[t,a]);const y=h.useMemo(()=>{if(r)return r;const C=s.find(A=>A.id===t||A.requestNumber===t||A.request_number===t);return C||null},[t,s,r]),w=h.useMemo(()=>{var L,D,R;if(!y||!a)return!1;const C=(L=a==null?void 0:a.email)==null?void 0:L.toLowerCase(),A=(R=(D=y.initiator)==null?void 0:D.email)==null?void 0:R.toLowerCase();return C===A},[y,a]),v=h.useMemo(()=>{var A;if(!y)return[];const C=[];return(A=y.initiator)!=null&&A.email&&C.push({email:y.initiator.email.toLowerCase(),participantType:"INITIATOR",name:y.initiator.name}),y.approvalFlow&&Array.isArray(y.approvalFlow)&&y.approvalFlow.forEach(L=>{L.approverEmail&&C.push({email:L.approverEmail.toLowerCase(),participantType:"APPROVER",name:L.approver})}),y.spectators&&Array.isArray(y.spectators)&&y.spectators.forEach(L=>{L.email&&C.push({email:L.email.toLowerCase(),participantType:"SPECTATOR",name:L.name})}),y.participants&&Array.isArray(y.participants)&&y.participants.forEach(L=>{const D=(L.userEmail||L.email||"").toLowerCase(),R=(L.participantType||L.participant_type||"").toUpperCase(),N=L.userName||L.user_name||L.name;D&&R&&!C.find(_=>_.email===D)&&C.push({email:D,participantType:R,name:N})}),C},[y]);return h.useEffect(()=>{if(!t||!r)return;const C=en();if(!C)return;const A=L=>{((L==null?void 0:L.requestId)===r.requestId||(L==null?void 0:L.requestNumber)===t)&&j()};return C.on("request:updated",A),()=>{C.off("request:updated",A)}},[t,r,j]),{request:y,apiRequest:r,loading:o,refreshing:i,refreshDetails:j,currentApprovalLevel:p,isSpectator:u,isInitiator:w,existingParticipants:v,accessDenied:d}}function Jg(t,s,a,r){const[n,i]=h.useState([]),[l,o]=h.useState(0),[c,d]=h.useState([]);return h.useEffect(()=>{if(!t){console.warn("[useRequestSocket] No requestIdentifier, cannot join socket room");return}let m=!0,p=t;return(async()=>{var f;try{const b=await Gs.getWorkflowDetails(t);(f=b==null?void 0:b.workflow)!=null&&f.requestId&&m&&(p=b.workflow.requestId)}catch(b){console.error("[useRequestSocket] Failed to resolve UUID:",b)}if(!m)return;const x=en();if(!x){console.error("[useRequestSocket] Socket not available");return}const u=r==null?void 0:r.userId,g=()=>{mo(x,p,u)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),Wh(x,p))}})(),()=>{m=!1}},[t,r]),h.useEffect(()=>{!t||!s||(async()=>{try{const m=await Zr(t),p=s.auditTrail||[],x=[...m,...p];x.sort((u,g)=>{const f=new Date(u.createdAt||u.created_at||u.timestamp||0).getTime(),b=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return f-b}),i(x)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),h.useEffect(()=>{if(!t)return;const m=en();if(!m)return;const p=u=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await Zr(t),f=(s==null?void 0:s.auditTrail)||[],b=[...g,...f].sort((j,y)=>{const w=new Date(j.createdAt||j.created_at||j.timestamp||0).getTime(),v=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime();return w-v});i(b)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},x=u=>{const g=u.type==="breach"?"⏰":u.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const f=await Gs.getWorkflowDetails(t);f&&(Array.isArray(f.tatAlerts)&&f.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(f){console.error("[useRequestSocket] Failed to refresh after TAT alert:",f)}})()};return m.on("noteHandler",p),m.on("worknote:new",p),m.on("tat:alert",x),()=>{m.off("noteHandler",p),m.off("worknote:new",p),m.off("tat:alert",x)}},[t,a,s]),h.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function Rn(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}}const vT=["MALWARE_DETECTED","FILE_VALIDATION_FAILED","CONTENT_THREAT_DETECTED","SCAN_UNAVAILABLE","SCAN_ERROR"],NT={MALWARE_DETECTED:"🛑 Malware Detected",FILE_VALIDATION_FAILED:"⛔ File Rejected",CONTENT_THREAT_DETECTED:"⚠️ Malicious Content Detected",SCAN_UNAVAILABLE:"🔒 Security Scan Unavailable",SCAN_ERROR:"❌ Security Scan Error"};function zc(t){var l,o,c,d;const s=(l=t==null?void 0:t.response)==null?void 0:l.data;if(!(s!=null&&s.error))return!1;const a=s.error;if(!vT.includes(a))return!1;const r=NT[a]||"Security Error",n=s.message||"File was blocked by security scan";let i="";return s.details&&((o=s.details.signatures)!=null&&o.length?i=`Virus: ${s.details.signatures.join(", ")}`:(c=s.details.errors)!=null&&c.length?i=s.details.errors[0]||"":(d=s.details.threats)!=null&&d.length&&(i=s.details.threats.map(m=>m.description).join(", "))),X.error(r,{description:i||n,duration:8e3,style:{background:"#fef2f2",border:"1px solid #fca5a5",color:"#991b1b"}}),!0}function Zg(t,s){const[a,r]=h.useState(!1),[n,i]=h.useState(null),[l,o]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=h.useState({show:!1,errors:[]});h.useEffect(()=>{(async()=>{try{const g=await la("DOCUMENT_POLICY"),f={};g.forEach(w=>{f[w.configKey]=w.configValue});const b=parseInt(f.MAX_FILE_SIZE_MB||"10"),y=(f.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(w=>w.trim().toLowerCase());o({maxFileSizeMB:b,allowedFileTypes:y})}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 f=u.name.toLowerCase(),b=f.substring(f.lastIndexOf(".")+1);return l.allowedFileTypes.includes(b)?{valid:!0}:{valid:!1,reason:`File type "${b}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},p=async u=>{var y,w;const g=u.target.files;if(!g||g.length===0)return;const f=Array.from(g),b=[],j=[];if(f.forEach(v=>{const C=m(v);C.valid?j.push(v):b.push({fileName:v.name,reason:C.reason||"Unknown validation error"})}),b.length>0&&d({show:!0,errors:b}),j.length===0){u.target&&(u.target.value="");return}r(!0);try{const v=j[0],C=t==null?void 0:t.requestId;if(!C){X.error("Request ID not found");return}v&&await Rn(v,C,"SUPPORTING"),await s(),j.length{const u=document.createElement("input");u.type="file",u.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),u.onchange=p,u.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}const wT="modulepreload",CT=function(t){return"/"+t},Nx={},Wl=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=CT(c),c in Nx)return;Nx[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const p=document.createElement("link");if(p.rel=d?"stylesheet":wT,d||(p.as="script"),p.crossOrigin="",p.href=c,o&&p.setAttribute("nonce",o),document.head.appendChild(p),d)return new Promise((x,u)=>{p.addEventListener("load",x),p.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 qg(t,s,a,r,n,i,l){const[o,c]=h.useState(""),[d,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(!1),[f,b]=h.useState(0),[j,y]=h.useState(!1),[w,v]=h.useState(!1),[C,A]=h.useState(0),L=async()=>{var S;const N=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),_=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(N||_){c(N||_),g(!!_);return}try{const{getConclusion:U}=await Wl(async()=>{const{getConclusion:$}=await import("./conclusionApi-CeVXrM6b.js");return{getConclusion:$}},__vite__mapDeps([0,1,2,3,4,5,6,7])),F=await U(t.requestId||s);F&&(F.aiGeneratedRemark||F.finalRemark)&&(c(F.finalRemark||F.aiGeneratedRemark||""),g(!!F.aiGeneratedRemark))}catch(U){((S=U==null?void 0:U.response)==null?void 0:S.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",U)}},D=async()=>{if(!w)try{m(!0),y(!1);const{generateConclusion:N}=await Wl(async()=>{const{generateConclusion:F}=await import("./conclusionApi-CeVXrM6b.js");return{generateConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7])),_=await N(t.requestId||s),S=f+1;if(b(S),!(_!=null&&_.aiGeneratedRemark)||_.aiGeneratedRemark.toLowerCase().includes("unable to generate")||_.aiGeneratedRemark.toLowerCase().includes("sorry")){const F=C+1;A(F),F>=2?(v(!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((_==null?void 0:_.aiGeneratedRemark)||""),g(!1);return}c(_.aiGeneratedRemark),g(!0),A(0),S>=2&&(v(!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 _=C+1;A(_),g(!1),_>=2?(v(!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)}},R=async()=>{var _,S;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:U}=await Wl(async()=>{const{finalizeConclusion:F}=await import("./conclusionApi-CeVXrM6b.js");return{finalizeConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await U(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(U){i==null||i({success:!1,title:"Error",message:((S=(_=U.response)==null?void 0:_.data)==null?void 0:S.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{x(!1)}};return h.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 S=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),U=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);S||U?(c(S||U),g(!!U)):L()},[t==null?void 0:t.status,t==null?void 0:t.conclusionRemark,t==null?void 0:t.aiGeneratedConclusion,a,o]),{conclusionRemark:o,setConclusionRemark:c,conclusionLoading:d,conclusionSubmitting:p,aiGenerated:u,handleGenerateConclusion:D,handleFinalizeConclusion:R,generationAttempts:f,generationFailed:j,maxAttemptsReached:w}}function e0(t,s,a){const[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState(!1),[d,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(!1),[f,b]=h.useState(null),[j,y]=h.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:p,setShowSkipApproverModal:x,showActionStatusModal:u,setShowActionStatusModal:g,skipApproverData:f,setSkipApproverData:b,actionStatus:j,setActionStatus:y,handleApproveConfirm:async D=>{var N,_;const R=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!R){alert("Approval level not found");return}await Tn(t,R,D||""),await new Promise(S=>setTimeout(S,500)),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(_=window==null?void 0:window.toast)==null||_.call(window,"Approved successfully")},handleRejectConfirm:async D=>{var N,_;if(!(D!=null&&D.trim())){alert("Comments & remarks are required");return}const R=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!R){alert("Approval level not found");return}await wr(t,R,D.trim(),D.trim()),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(_=window==null?void 0:window.toast)==null||_.call(window,"Rejected successfully")},handleAddApprover:async(D,R,N)=>{var _,S;try{await lp(t,D,R,N),await a(),c(!1),y==null||y({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${R}h TAT`}),g==null||g(!0)}catch(U){throw y==null||y({success:!1,title:"Failed to Add Approver",message:((S=(_=U==null?void 0:U.response)==null?void 0:_.data)==null?void 0:S.error)||"Failed to add approver. Please try again."}),g==null||g(!0),U}},handleSkipApprover:async D=>{var R,N;if(f)try{await Tw(t,f.levelId,D),await a(),x(!1),b(null),y==null||y({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),g==null||g(!0)}catch(_){throw y==null||y({success:!1,title:"Failed to Skip Approver",message:((N=(R=_==null?void 0:_.response)==null?void 0:R.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),_}},handleAddSpectator:async D=>{var R,N;try{await op(t,D),await a(),m(!1),y==null||y({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),g==null||g(!0)}catch(_){throw y==null||y({success:!1,title:"Failed to Add Spectator",message:((N=(R=_==null?void 0:_.response)==null?void 0:R.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),_}}}}function ST({requestId:t,request:s,onRefresh:a}){const[r,n]=h.useState(null),[i,l]=h.useState(!0),[o,c]=h.useState(null),[d,m]=h.useState(!1),[p,x]=h.useState(""),u=s==null?void 0:s.form16Submission,g=!!u,f=!!r&&r.status!=="withdrawn",b=(u==null?void 0:u.tdsAmount)!=null?Number(u.tdsAmount):void 0;h.useEffect(()=>{if(!t){l(!1);return}let v=!1;return(async()=>{try{const C=await co(t);v||n(C?{id:typeof C.id=="number"?C.id:Number(C.id),status:C.status||""}:null)}catch{v||n(null)}finally{v||l(!1)}})(),()=>{v=!0}},[t]);const j=async()=>{if(!(!t||!window.confirm("Cancel this Form 16 submission? The request will be marked as rejected."))){c("cancel");try{await vy(t),X.success("Submission cancelled"),a==null||a()}catch(v){X.error(v instanceof Error?v.message:"Failed to cancel submission")}finally{c(null)}}},y=async()=>{if(!(!t||!window.confirm("Mark this submission as resubmission needed? The dealer will need to resubmit Form 16."))){c("resubmit");try{await Ny(t),X.success("Marked as resubmission needed"),a==null||a()}catch(v){X.error(v instanceof Error?v.message:"Failed to update")}finally{c(null)}}},w=async()=>{const v=parseFloat(p);if(!t||Number.isNaN(v)||v<=0){X.error("Enter a valid amount to generate credit note");return}c("credit");try{await wy(t,v),m(!1),x(""),X.success("Credit note generated (manually approved)");const C=await co(t);n(C?{id:typeof C.id=="number"?C.id:Number(C.id),status:C.status||""}:null),a==null||a()}catch(C){X.error(C instanceof Error?C.message:"Failed to generate credit note")}finally{c(null)}};return i||!g||f?null:e.jsxs(e.Fragment,{children:[e.jsxs(q,{className:"border-blue-200 bg-blue-50/30","data-testid":"form16-quick-actions-card",children:[e.jsxs(oe,{className:"pb-2",children:[e.jsxs(de,{className:"text-sm flex items-center gap-2 text-blue-800",children:[e.jsx(Pt,{className:"w-4 h-4"}),"Form 16 actions"]}),e.jsx(ye,{className:"text-xs text-gray-600",children:"View the document in the Documents tab. Cancel submission, mark resubmission needed, or generate credit note (e.g. when OCR was partial)."})]}),e.jsxs(ee,{className:"space-y-2",children:[e.jsxs(M,{variant:"outline",size:"sm",className:"w-full justify-start border-red-300 text-red-700 hover:bg-red-50",onClick:j,disabled:!!o,children:[o==="cancel"?e.jsx(Qe,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(jt,{className:"w-3 h-3 mr-1"}),"Cancel submission"]}),e.jsxs(M,{variant:"outline",size:"sm",className:"w-full justify-start border-amber-300 text-amber-700 hover:bg-amber-50",onClick:y,disabled:!!o,children:[o==="resubmit"?e.jsx(Qe,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(dh,{className:"w-3 h-3 mr-1"}),"Resubmission needed"]}),e.jsxs(M,{variant:"outline",size:"sm",className:"w-full justify-start border-emerald-300 text-emerald-700 hover:bg-emerald-50",onClick:()=>{x(b!=null?String(b):""),m(!0)},disabled:!!o,children:[o==="credit"?e.jsx(Qe,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(Pt,{className:"w-3 h-3 mr-1"}),"Generate credit note"]})]})]}),e.jsx(ht,{open:d,onOpenChange:m,children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(ut,{children:"Generate credit note (manual)"}),e.jsx(_t,{children:"Enter the amount for the credit note. This will mark the Form 16 as manually approved."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(te,{htmlFor:"form16-cn-amount",children:"Amount (₹)"}),e.jsx(Ce,{id:"form16-cn-amount",type:"number",min:"0",step:"0.01",placeholder:b!=null?String(b):"0",value:p,onChange:v=>x(v.target.value)}),b!=null&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Suggested from submission TDS amount: ₹",b.toLocaleString("en-IN")]})]})}),e.jsxs(Et,{children:[e.jsx(M,{variant:"outline",onClick:()=>m(!1),disabled:!!o,children:"Cancel"}),e.jsxs(M,{onClick:w,disabled:!!o||!p.trim(),children:[o==="credit"?e.jsx(Qe,{className:"w-4 h-4 animate-spin mr-2"}):null,"Generate credit note"]})]})]})})]})}const AT=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 Er({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(Ie,{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 "]}),gs(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&AT(t.fileType)&&s&&e.jsx(M,{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(St,{className:"w-4 h-4"})}),a&&e.jsx(M,{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(Rt,{className:"w-4 h-4"})})]})]})}function TT({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l}){var c,d,m,p;const o=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16";return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[o&&((d=(c=t==null?void 0:t.form16Submission)==null?void 0:c.previousDocuments)==null?void 0:d.length)>0&&e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base text-amber-800",children:[e.jsx(Ie,{className:"w-4 h-4 sm:w-5 sm:h-5 text-amber-600"}),"Previous submission(s) – same quarter"]}),e.jsxs(ye,{className:"text-xs sm:text-sm mt-1",children:["Documents from earlier Form 16A submissions for this request's financial year and quarter only (",(m=t==null?void 0:t.form16Submission)==null?void 0:m.financialYear," ",(p=t==null?void 0:t.form16Submission)==null?void 0:p.quarter,")"]})]}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-4",children:(()=>{const x=new Map;for(const u of t.form16Submission.previousDocuments){const g=u.requestId||u.request_id,f=u.requestNumber||g;x.has(f)||x.set(f,[]),x.get(f).push(u)}return Array.from(x.entries()).map(([u,g])=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600",children:["Request ",u]}),e.jsx("div",{className:"space-y-2 pl-2 border-l-2 border-amber-200",children:g.map((f,b)=>{const j=f.documentId??f.document_id,y=f.originalFileName??f.original_file_name??f.fileName??f.file_name??"Document",w=Number(f.fileSize??f.file_size??0),v=w>0?(w/(1024*1024)).toFixed(2)+" MB":"—";return e.jsx(Er,{document:{documentId:j,name:y,fileType:f.fileType??f.file_type??"",size:v,sizeBytes:w,uploadedBy:f.uploadedBy??f.uploaded_by,uploadedAt:f.uploadedAt??f.uploaded_at},onPreview:C=>i(C),onDownload:l,testId:"form16-previous-document"},j||b)})})]},u))})()})})]}),e.jsxs(q,{children:[e.jsx(oe,{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(de,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Ie,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),o?"Current submission":"Request Documents"]}),e.jsx(ye,{className:"text-xs sm:text-sm mt-1",children:o?"Documents for this Form 16A submission":"Documents attached while creating the request"})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsxs(M,{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(js,{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(ee,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((x,u)=>e.jsx(Er,{document:x,onPreview:g=>i(g),onDownload:l,testId:"request-document"},u))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-documents",children:"No documents uploaded yet"})})]}),!o&&e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Hs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx(ye,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(ee,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((x,u)=>e.jsx(Er,{document:{documentId:x.attachmentId||"",name:x.name,fileType:x.type||"",size:x.size?`${(x.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:x.size,uploadedBy:x.uploadedBy,uploadedAt:x.uploadedAt},onPreview:g=>i(g),onDownload:async g=>{const{downloadWorkNoteAttachment:f}=require("@/services/workflowApi");await f(g)},testId:"worknote-attachment"},x.attachmentId||u))}):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 kT=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"}}},wx=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending",icon:st,iconColor:"text-yellow-600"};case"paused":return{color:"bg-gray-400 text-gray-100 border-gray-500",label:"paused",icon:es,iconColor:"text-gray-600"};case"in-review":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"in-review",icon:Ut,iconColor:"text-blue-600"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:Oe,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected",icon:At,iconColor:"text-red-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-300",label:"closed",icon:Oe,iconColor:"text-gray-600"};case"skipped":return{color:"bg-orange-100 text-orange-800 border-orange-200",label:"skipped",icon:$t,iconColor:"text-orange-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:es,iconColor:"text-gray-600"}}},RT=t=>{switch(t){case"approval":case"approved":return e.jsx(Oe,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(At,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(Hs,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(Ut,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(Qi,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Ie,{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(Wi,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(es,{className:"w-5 h-5 text-amber-600"});default:return e.jsx($t,{className:"w-5 h-5 text-gray-600"})}};function DT(t){const s=t==null?void 0:t.form16Submission;if(!s)return[];const a=[],r=Array.isArray(s.previousSubmissions)?s.previousSubmissions:[];for(const u of r){const g=u.requestNumber||u.requestId||"",f=u.submittedDate?new Date(u.submittedDate).toISOString():new Date().toISOString();if(a.push({type:"document_added",action:`Previous submission (${g})`,details:"Form 16A certificate was submitted for this FY and quarter.",timestamp:f}),u.creditNoteNumber){const b=u.creditNoteIssueDate?new Date(u.creditNoteIssueDate).toISOString():f;a.push({type:"status_change",action:"Credit note issued",details:`Credit note ${u.creditNoteNumber} issued for previous submission (${g}).`,timestamp:b})}}const n=s.submittedDate||(t==null?void 0:t.submittedDate)||(t==null?void 0:t.createdAt),i=n?new Date(n).toISOString():new Date().toISOString(),l=(s.validationStatus||"").toLowerCase(),o=s.validationNotes||""||"",c=(s.displayStatus||"").toLowerCase(),d=!!(s.ocrExtractedData&&typeof s.ocrExtractedData=="object"&&Object.keys(s.ocrExtractedData).length>0),m=!!s.creditNoteNumber,p=c==="balance mismatch"||l==="failed"&&!m||l==="failed"&&/mismatch|26as|value/i.test(o),x=c==="duplicate"||l==="duplicate";return a.push({type:"document_added",action:"Form 16A uploaded",details:"Form 16A certificate was uploaded and received.",timestamp:i}),a.push({type:"created",action:"OCR extraction",details:d?"Certificate data was extracted from the uploaded PDF.":"OCR extraction was performed on the uploaded document.",timestamp:i}),p?a.push({type:"rejection",action:"26AS matching",details:"Values of Form 16 did not match with 26AS. Please submit Form 16 with correct data.",timestamp:i}):x?a.push({type:"rejection",action:"26AS matching",details:"Duplicate. A submission for this FY and quarter already exists; credit note was issued for the earlier submission.",timestamp:i}):a.push({type:"status_change",action:"26AS matching",details:l==="success"||s.creditNoteNumber?"26AS matching completed. Credit note generated.":"26AS matching was performed.",timestamp:i}),a.sort((u,g)=>new Date(u.timestamp).getTime()-new Date(g.timestamp).getTime())}function FT({request:t}){const s=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",a=s?DT(t):[],r=t.auditTrail&&Array.isArray(t.auditTrail)?t.auditTrail:[],n=a.length>0?[...a,...r].sort((i,l)=>{const o=i.timestamp?new Date(i.timestamp).getTime():0,c=l.timestamp?new Date(l.timestamp).getTime():0;return o-c}):r;return e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx($t,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(ye,{className:"text-xs sm:text-sm",children:s?"Form 16 submission steps and audit trail":"Complete audit trail of all request activities"})]}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-4 sm:space-y-6",children:n.length>0?n.map((i,l)=>e.jsxs("div",{className:"flex items-start gap-4","data-testid":`activity-item-${l}`,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${i.type==="rejection"?"bg-red-50":"bg-gray-100"}`,children:RT(i.type)})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:`rounded-lg border p-4 shadow-sm ${i.type==="rejection"?"bg-red-50/50 border-red-200":"bg-white border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:`font-semibold ${i.type==="rejection"?"text-red-900":"text-gray-900"}`,children:i.action}),e.jsx("span",{className:"text-xs text-gray-500 whitespace-nowrap ml-4",children:gs(i.timestamp)})]}),e.jsx("div",{className:`text-sm leading-relaxed ${i.type==="rejection"?"text-red-800":"text-gray-600"}`,children:e.jsx("p",{className:"whitespace-pre-line break-words",children:i.details})})]})})]},l)):e.jsxs("div",{className:"text-center py-12","data-testid":"no-activity",children:[e.jsx($t,{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 t0({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsx(pt,{children:e.jsxs(ut,{className:"flex items-center gap-2",children:[a?e.jsx(Oe,{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(Oe,{className:"w-8 h-8 text-green-600"})}),e.jsx("p",{className:"text-sm text-gray-700",children:n||"Operation completed successfully!"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-red-100 flex items-center justify-center mb-4",children:e.jsx(At,{className:"w-8 h-8 text-red-600"})}),e.jsx("p",{className:"text-sm text-gray-700",children:n||"Operation failed. Please try again."})]})})}),e.jsx(Et,{children:e.jsx(M,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function s0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=h.useState(""),[l,o]=h.useState(!1),[c,d]=h.useState([]),[m,p]=h.useState(!1),[x,u]=h.useState(null),g=h.useRef(null),f=h.useRef(null),[b,j]=h.useState({open:!1,type:"error",email:"",message:""}),[y,w]=h.useState({open:!1,violations:[]}),[v,C]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});h.useEffect(()=>{t&&(async()=>{var _;try{const S=await la("WORKFLOW_SHARING"),U=await la("TAT_SETTINGS"),F=[...S,...U],$={};F.forEach(P=>{$[P.configKey]=P.configValue}),C({maxApprovalLevels:parseInt($.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt($.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((_=$.ALLOW_ADD_SPECTATOR)==null?void 0:_.toLowerCase())==="true",maxSpectators:parseInt($.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(S){console.error("Failed to load system policy:",S)}})()},[t]);const A=async()=>{var T,k;const N=n.trim().toLowerCase();if(!N){j({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(N)){j({open:!0,type:"error",email:N,message:"Please enter a valid email address"});return}const S=r.find(B=>(B.email||"").toLowerCase()===N);if(S){const B=((T=S.participantType)==null?void 0:T.toUpperCase())||"PARTICIPANT",I=S.name||N;if(B==="INITIATOR"){j({open:!0,type:"error",email:N,message:`${I} is the request initiator and cannot be added as a spectator.`});return}else if(B==="APPROVER"){j({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(B==="SPECTATOR"){j({open:!0,type:"error",email:N,message:`${I} is already a spectator on this request.`});return}else{j({open:!0,type:"error",email:N,message:`${I} is already a participant on this request.`});return}}const U=[];v.allowSpectators||U.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const $=r.filter(B=>(B.participantType||"").toUpperCase()==="SPECTATOR").length;$>=v.maxSpectators&&U.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:$,maxValue:v.maxSpectators});const P=r.length+1;if(P>v.maxParticipants&&U.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:P,maxValue:v.maxParticipants}),U.length>0){w({open:!0,violations:U});return}if(!x||x.email.toLowerCase()!==N)try{const I=((k=(await ba(N,1)).data)==null?void 0:k.data)||[];if(I.length===0){j({open:!0,type:"not-found",email:N,message:""});return}const E=I[0];await ga({userId:E.userId,email:E.email,displayName:E.displayName,firstName:E.firstName,lastName:E.lastName,department:E.department,phone:E.phone,mobilePhone:E.mobilePhone,designation:E.designation,jobTitle:E.jobTitle,manager:E.manager,employeeId:E.employeeId,employeeNumber:E.employeeNumber,secondEmail:E.secondEmail,location:E.location})}catch(B){console.error("Failed to validate spectator:",B),j({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(B){console.error("Failed to add spectator:",B)}finally{o(!1)}},L=()=>{l||(i(""),u(null),d([]),p(!1),s())};h.useEffect(()=>{c.length>0&&f.current&&f.current.scrollTo({top:f.current.scrollHeight,behavior:"smooth"})},[c.length]),h.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([]),p(!1);return}p(!0),g.current=setTimeout(async()=>{var _;try{const S=N.slice(1),F=((_=(await ba(S,10)).data)==null?void 0:_.data)||[];d(F)}catch(S){console.error("Search failed:",S),d([])}finally{p(!1)}},300)},R=async N=>{try{await ga({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([]),p(!1)}catch(_){console.error("Failed to ensure user exists:",_),j({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ht,{open:t,onOpenChange:L,children:[e.jsxs(mt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:L,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:l,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(pt,{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(St,{className:"w-5 h-5 text-purple-600"})}),e.jsx(ut,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:f,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a spectator to this request. They will receive notifications but cannot approve or reject."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(Xi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ce,{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:()=>R(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ls,{className:"h-8 w-8",children:e.jsx(os,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(N.displayName||N.email).split(" ").map(_=>_[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(M,{type:"button",variant:"outline",onClick:L,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(M,{type:"button",onClick:A,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(St,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(ht,{open:b.open,onOpenChange:N=>j(_=>({..._,open:N})),children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(ut,{className:"flex items-center gap-2",children:b.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(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[b.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:b.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Ki,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),b.type==="error"&&e.jsxs(e.Fragment,{children:[b.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:b.email}),"."]}),b.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:b.message})})]})]})})]}),e.jsx(Et,{children:e.jsx(M,{onClick:()=>j(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(ti,{open:y.open,onClose:()=>w({open:!1,violations:[]}),violations:y.violations,policyDetails:{maxApprovalLevels:v.maxApprovalLevels,maxParticipants:v.maxParticipants,allowSpectators:v.allowSpectators,maxSpectators:v.maxSpectators}})]})}function a0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=h.useState(""),[d,m]=h.useState(24),[p,x]=h.useState(null),[u,g]=h.useState(!1),[f,b]=h.useState([]),[j,y]=h.useState(!1),[w,v]=h.useState(null),C=h.useRef(null),A=h.useRef(null),[L,D]=h.useState({open:!1,type:"error",email:"",message:""}),R=n.filter(k=>k&&(k.status==="approved"||k.status==="rejected"||k.status==="skipped")),N=Math.max(1,R.length+1),_=Math.max(1,n.length+1),S=_>=N?Array.from({length:_-N+1},(k,B)=>N+B):[N];h.useEffect(()=>{S.length>0&&p===null&&x(S[0]||null)},[S.length,p]);const U=async()=>{var V,Y;const k=o.trim().toLowerCase();if(!k){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(k)){D({open:!0,type:"error",email:k,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(!p){D({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(p0?Math.max(...n.map(Z=>Z.levelNumber),0):0,E=p>I?p:I+1;if(i&&E>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${p} would result in ${E} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:E,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(Z=>(Z.email||"").toLowerCase()===k);if(W){const Z=((V=W.participantType)==null?void 0:V.toUpperCase())||"PARTICIPANT",O=W.name||k;if(Z==="INITIATOR"){D({open:!0,type:"error",email:k,message:`${O} is the request initiator and cannot be added as an approver.`});return}else if(Z==="APPROVER"){D({open:!0,type:"error",email:k,message:`${O} is already an approver on this request.`});return}else if(Z==="SPECTATOR"){D({open:!0,type:"error",email:k,message:`${O} 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:k,message:`${O} is already a participant on this request.`});return}}if(!w||w.email.toLowerCase()!==k)try{const O=((Y=(await ba(k,1)).data)==null?void 0:Y.data)||[];if(O.length===0){D({open:!0,type:"not-found",email:k,message:""});return}const z=O[0];await ga({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(Z){console.error("Failed to validate approver:",Z),D({open:!0,type:"error",email:k,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(k,d,p),c(""),m(24),x(null),v(null),s()}catch(Z){console.error("Failed to add approver:",Z)}finally{g(!1)}},F=()=>{u||(c(""),m(24),x(null),v(null),b([]),y(!1),s())},$=k=>{const B=k.toLowerCase();return B==="approved"?e.jsx(Oe,{className:"w-4 h-4 text-green-600"}):B==="rejected"?e.jsx(At,{className:"w-4 h-4 text-red-600"}):B==="skipped"?e.jsx(Ze,{className:"w-4 h-4 text-orange-600"}):B==="in-review"||B==="pending"?e.jsx(st,{className:"w-4 h-4 text-blue-600"}):e.jsx(st,{className:"w-4 h-4 text-gray-400"})};h.useEffect(()=>{f.length>0&&A.current&&A.current.scrollTo({top:A.current.scrollHeight,behavior:"smooth"})},[f.length]),h.useEffect(()=>()=>{C.current&&clearTimeout(C.current)},[]);const P=k=>{if(c(k),w&&w.email.toLowerCase()!==k.toLowerCase()&&v(null),C.current&&clearTimeout(C.current),!k||!k.startsWith("@")||k.length<2){b([]),y(!1);return}y(!0),C.current=setTimeout(async()=>{var B;try{const I=k.slice(1),W=((B=(await ba(I,10)).data)==null?void 0:B.data)||[];b(W)}catch(I){console.error("Search failed:",I),b([])}finally{y(!1)}},300)},T=async k=>{try{await ga({userId:k.userId,email:k.email,displayName:k.displayName,firstName:k.firstName,lastName:k.lastName,department:k.department,phone:k.phone,mobilePhone:k.mobilePhone,designation:k.designation,jobTitle:k.jobTitle,manager:k.manager,employeeId:k.employeeId,employeeNumber:k.employeeNumber,secondEmail:k.secondEmail,location:k.location}),c(k.email),v(k),b([]),y(!1)}catch(B){console.error("Failed to ensure user exists:",B),D({open:!0,type:"error",email:k.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(ht,{open:t,onOpenChange:F,children:[e.jsxs(mt,{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(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(pt,{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(Jt,{className:"w-5 h-5 text-blue-600"})}),e.jsx(ut,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:A,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(k=>k.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(k=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${k.status==="approved"?"bg-green-100 border border-green-200":k.status==="rejected"?"bg-red-100 border border-red-200":k.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:k.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:k.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[k.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[$(k.status),e.jsx(ae,{variant:"outline",className:`text-xs ${k.status==="approved"?"bg-green-50 text-green-700 border-green-300":k.status==="rejected"?"bg-red-50 text-red-700 border-red-300":k.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:k.status})]})]},k.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(te,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(He,{value:(p==null?void 0:p.toString())||"",onValueChange:k=>x(Number(k)),disabled:u,children:[e.jsx(Ge,{className:"h-11 border-gray-300",children:e.jsx(We,{placeholder:"Select level"})}),e.jsx(Ye,{children:S.map(k=>e.jsx(J,{value:k.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",k]}),k<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",k,")"]})]})},k))})]}),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(te,{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(Ce,{type:"number",min:"1",max:"720",value:d,onChange:k=>m(Number(k.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(Xi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ce,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:k=>P(k.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(j||f.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:j?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):f.length>0?e.jsx("ul",{className:"divide-y",children:f.map(k=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>T(k),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ls,{className:"h-8 w-8",children:e.jsx(os,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(k.displayName||k.email).split(" ").map(B=>B[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:k.displayName||[k.firstName,k.lastName].filter(Boolean).join(" ")||k.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:k.email}),k.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:k.designation})]})]})},k.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(M,{type:"button",variant:"outline",onClick:F,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(M,{type:"button",onClick:U,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!o.trim()||!p||!d,children:[e.jsx(Jt,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${p||"?"}`]})]})]}),e.jsx(ht,{open:L.open,onOpenChange:k=>D(B=>({...B,open:k})),children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsx(ut,{className:"flex items-center gap-2",children:L.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(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[L.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:L.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(Ki,{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."]})})]}),L.type==="error"&&e.jsxs(e.Fragment,{children:[L.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:L.email}),"."]}),L.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:L.message})})]})]})})]}),e.jsx(Et,{children:e.jsx(M,{onClick:()=>D(k=>({...k,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const IT=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"}},PT=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},ET=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 Ra(s)},_T=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",Cx=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Ie,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(uh,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Ie,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Ie,{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(hi,{className:`${s} text-purple-600`}):e.jsx(Wi,{className:`${s} text-gray-600`})};function r0({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:c=[],onAddApprover:d,maxApprovalLevels:m,onPolicyViolation:p}){const x=_a(),u=t||x.requestId||"",[g,f]=h.useState(""),[b,j]=h.useState(""),[y,w]=h.useState(!1),[v,C]=h.useState([]),[A,L]=h.useState(!1),[D,R]=h.useState([]),[N,_]=h.useState(null),[S,U]=h.useState(null),[F,$]=h.useState(!1),[P,T]=h.useState(!1),[k,B]=h.useState(!1),[I,E]=h.useState({success:!0,title:"",message:""}),W=h.useRef(null),V=h.useRef(null),Y=h.useRef(null),Z=h.useRef(!1),[O,z]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[K,re]=h.useState({open:!1,errors:[]}),G=h.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[se,ve]=h.useState([]),Te=se.filter(ie=>ie.status==="online"),Ke=v.filter(ie=>ie.content.toLowerCase().includes(b.toLowerCase())||ie.user.name.toLowerCase().includes(b.toLowerCase())),Je=h.useMemo(()=>o!==void 0?o:!N||se.length===0?!1:se.some(ie=>{const Re=ie.userId||ie.user_id,ce=(ie.role||"").toString().toUpperCase(),Ve=(ie.participantType||ie.participant_type||"").toString().toUpperCase();return Re===N&&(ce==="SPECTATOR"||Ve==="SPECTATOR")}),[o,N,se]);h.useEffect(()=>{},[se]),h.useEffect(()=>{!u||!N||s||(async()=>{try{const ie=await Zr(u),Re=Array.isArray(ie)?ie.map(ce=>{const Ve=ce.userId||ce.user_id;return{id:ce.noteId||ce.id||String(Math.random()),user:{name:ce.userName||"User",avatar:(ce.userName||"U").slice(0,2).toUpperCase(),role:ce.userRole||"Participant"},content:ce.message||"",timestamp:ce.createdAt||new Date().toISOString(),isCurrentUser:Ve===N,attachments:Array.isArray(ce.attachments)?ce.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}}):[];C(Re)}catch(ie){console.error("[WorkNoteChat] Failed to load messages:",ie)}})()},[u,N,s]);const Pe=h.useMemo(()=>{const ie=[];return v.forEach(Re=>{Re.attachments&&Re.attachments.length>0&&Re.attachments.forEach(ce=>{ie.push({attachmentId:ce.attachmentId||ce.attachment_id,name:ce.fileName||ce.file_name||ce.name||"Untitled",fileName:ce.fileName||ce.file_name||ce.name||"Untitled",size:ce.fileSize||ce.file_size,type:ce.fileType||ce.file_type||ce.type||"file",uploadedBy:Re.user.name,uploadedAt:Re.timestamp,url:ce.storageUrl||ce.storage_url||ce.url||"#"})})}),ie},[v]);h.useEffect(()=>{i&&Pe.length>=0&&i(Pe)},[Pe,i]);const $e=h.useMemo(()=>se.map(ie=>({email:(ie.email||"").toLowerCase(),participantType:ie.role==="Initiator"?"INITIATOR":ie.role==="Approver"?"APPROVER":ie.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:ie.name})),[se]),ne=ie=>{if(!ie)return"Participant";switch(ie.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return ie.charAt(0).toUpperCase()+ie.slice(1).toLowerCase()}},he=()=>{var ie;(ie=W.current)==null||ie.scrollIntoView({behavior:"smooth"})};h.useEffect(()=>{he()},[v]);const Ne=ie=>{switch(ie.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return ie.charAt(0).toUpperCase()+ie.slice(1).toLowerCase()}};h.useEffect(()=>{Z.current||u&&(async()=>{try{const ie=await Es(u),Re=Array.isArray(ie==null?void 0:ie.participants)?ie.participants:[];if(Re.length===0)return;const ce=Re.map(ze=>{const rt=ze.participantType||ze.participant_type||"participant",qe=ze.userId||ze.user_id||"";return{name:ze.userName||ze.user_name||ze.user_email||ze.userEmail||"User",avatar:(ze.userName||ze.user_name||ze.user_email||"U").toString().split(" ").map(ot=>ot[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ne(rt.toString()),status:"offline",email:ze.userEmail||ze.user_email||"",permissions:["read","write","mention"],userId:qe}});Z.current=!0,ve(ce);let Ve=0;const Be=3,tt=()=>{Y.current&&Y.current.connected?(Y.current.emit("request:online-users",{requestId:u}),Ve++,Ve()=>{u&&(Z.current=!1)},[u]),h.useEffect(()=>{const ie=localStorage.getItem("userData");if(ie)try{const Re=JSON.parse(ie),ce=(Re==null?void 0:Re.id)||(Re==null?void 0:Re.userId)||(Re==null?void 0:Re.user_id)||null;_(ce)}catch(Re){console.error("[WorkNoteChat] Failed to parse userData:",Re)}},[]),h.useEffect(()=>{(async()=>{try{const Re=await la("DOCUMENT_POLICY"),ce={};Re.forEach(ze=>{ce[ze.configKey]=ze.configValue});const Ve=parseInt(ce.MAX_FILE_SIZE_MB||"10"),tt=(ce.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(ze=>ze.trim().toLowerCase());z({maxFileSizeMB:Ve,allowedFileTypes:tt})}catch(Re){console.error("Failed to load document policy:",Re)}})()},[]),h.useEffect(()=>{if(!N)return;let ie=u;return(async()=>{var Re;try{const ce=await Es(u);(Re=ce==null?void 0:ce.workflow)!=null&&Re.requestId&&(ie=ce.workflow.requestId)}catch{}try{const ce=en();r?ve(gt=>gt.map(Dt=>Dt.userId===N?{...Dt,status:"online"}:Dt)):(mo(ce,ie,N),ve(gt=>gt.map(Dt=>Dt.userId===N?{...Dt,status:"online"}:Dt)));const Ve=gt=>{const ct=(gt==null?void 0:gt.note)||gt;if(!ct)return;const Dt=ct.noteId||ct.id;C(vs=>{if(vs.some(Ft=>Ft.id===Dt))return vs;const ts=ct.userName||ct.user_name||"User",Sa=ct.userRole||ct.user_role,Ma=ne(Sa),Aa=ct.userId||ct.user_id,Ya={id:Dt||String(Date.now()),user:{name:ts,avatar:ts.split(" ").map(Ft=>Ft[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ma},content:ct.message||"",timestamp:ct.createdAt||new Date().toISOString(),isCurrentUser:Aa===N,attachments:Array.isArray(ct.attachments)?ct.attachments.map(Ft=>({attachmentId:Ft.attachmentId||Ft.attachment_id,name:Ft.fileName||Ft.file_name||Ft.name,fileName:Ft.fileName||Ft.file_name||Ft.name,url:Ft.storageUrl||Ft.storage_url||Ft.url||"#",type:Ft.fileType||Ft.file_type||Ft.type||"file",fileType:Ft.fileType||Ft.file_type||Ft.type||"file",fileSize:Ft.fileSize||Ft.file_size})):void 0};return[...vs,Ya]})},Be=gt=>{ve(ct=>ct.length===0||!ct.find(ts=>ts.userId===gt.userId)?ct:ct.map(ts=>ts.userId===gt.userId?{...ts,status:"online"}:ts))},tt=gt=>{gt.userId!==N&&ve(ct=>ct.length===0||!ct.find(ts=>ts.userId===gt.userId)?ct:ct.map(ts=>ts.userId===gt.userId?{...ts,status:"offline"}:ts))},ze=gt=>{ve(ct=>ct.length===0?ct:ct.map(vs=>{const ts=vs.userId||"";if(ts===N)return{...vs,status:"online"};const Ma=gt.userIds.includes(ts);return{...vs,status:Ma?"online":"offline"}}))},rt=()=>{ve(gt=>gt.map(Dt=>Dt.userId===N?{...Dt,status:"online"}:Dt)),r||mo(ce,ie,N),Z.current&&(ce.emit("request:online-users",{requestId:ie}),setTimeout(()=>ce.emit("request:online-users",{requestId:ie}),300),setTimeout(()=>ce.emit("request:online-users",{requestId:ie}),800))},qe=gt=>{console.error("[WorkNoteChat] ❌ Socket error:",gt)},ot=gt=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",gt),ve(ct=>ct.map(Dt=>Dt.userId===N?Dt:{...Dt,status:"offline"}))},Us=gt=>{gt.includes("presence")||gt.includes("worknote")||gt.includes("request")};ce.on("connect",rt),ce.on("disconnect",ot),ce.on("error",qe),ce.on("worknote:new",Ve),ce.on("presence:join",Be),ce.on("presence:leave",tt),ce.on("presence:online",ze),ce.onAny(Us),Y.current=ce,ce.connected&&Z.current&&(ce.emit("request:online-users",{requestId:ie}),setTimeout(()=>{ce.emit("request:online-users",{requestId:ie})},300),setTimeout(()=>{ce.emit("request:online-users",{requestId:ie})},800),setTimeout(()=>{ce.emit("request:online-users",{requestId:ie})},1500));const rs=()=>{ce.off("connect",rt),ce.off("disconnect",ot),ce.off("error",qe),ce.off("worknote:new",Ve),ce.off("presence:join",Be),ce.off("presence:leave",tt),ce.off("presence:online",ze),ce.offAny(Us),r||Wh(ce,ie),Y.current=null};window.__wn_cleanup=rs}catch{}})(),()=>{var Re;try{(Re=window.__wn_cleanup)==null||Re.call(window)}catch{}}},[u,N,r]);const Ae=async()=>{if(g.trim()||D.length>0){const ie=Nt(g),Re=ie.map(Be=>{const tt=se.find(ze=>ze.name.toLowerCase().includes(Be.toLowerCase()));return tt==null?void 0:tt.userId}).filter(Boolean),ce=D.map(Be=>({name:Be.name,url:URL.createObjectURL(Be),type:Be.type.split("/")[1]||"file"})),Ve={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:ie,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:ce.length>0?ce:void 0,isCurrentUser:!0};if(a)try{await a(g,D)}catch{}else try{await ip(u,{message:g,mentions:Re},D);const Be=await Zr(u),tt=Array.isArray(Be)?Be.map(ze=>{const rt=ze.userId||ze.user_id;return{id:ze.noteId||ze.id||String(Math.random()),user:{name:ze.userName||"User",avatar:(ze.userName||"U").slice(0,2).toUpperCase(),role:ze.userRole||"Participant"},content:ze.message||"",timestamp:ze.createdAt||new Date().toISOString(),isCurrentUser:rt===N,attachments:Array.isArray(ze.attachments)?ze.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}}):[];C(tt)}catch{C(Be=>[...Be,Ve])}f(""),R([])}};h.useEffect(()=>{if(s&&Array.isArray(s))try{const Re=s.filter(ce=>(ce.type||"").toLowerCase()!=="sla_warning").map(ce=>{var Be;if(ce.type||ce.activityType||ce.isSystem)return{id:ce.id||`activity-${ce.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:ce.details||ce.action||ce.content||"",timestamp:ce.timestamp||ce.createdAt||ce.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const tt=ce.userName||ce.user_name||((Be=ce.user)==null?void 0:Be.name)||"User",ze=ce.userRole||ce.user_role,rt=ne(ze),qe=ce.userId||ce.user_id;return{id:ce.noteId||ce.note_id||ce.id||String(Math.random()),user:{name:tt,avatar:tt.split(" ").map(ot=>ot[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:rt},content:ce.message||ce.content||"",timestamp:ce.createdAt||ce.created_at||ce.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(ce.attachments)?ce.attachments.map(ot=>({attachmentId:ot.attachmentId||ot.attachment_id,name:ot.fileName||ot.file_name||ot.name,fileName:ot.fileName||ot.file_name||ot.name,url:ot.storageUrl||ot.storage_url||ot.url||"#",type:ot.fileType||ot.file_type||ot.type||"file",fileType:ot.fileType||ot.file_type||ot.type||"file",fileSize:ot.fileSize||ot.file_size})):void 0,isCurrentUser:qe===N}}}).sort((ce,Ve)=>new Date(ce.timestamp).getTime()-new Date(Ve.timestamp).getTime());C(Re)}catch(ie){console.error("[WorkNoteChat] Error mapping messages:",ie)}else(async()=>{try{const ie=await Zr(u),Re=Array.isArray(ie)?ie.map(ce=>{const Ve=ce.userName||ce.user_name||"User",Be=ce.userRole||ce.user_role,tt=ne(Be),ze=ce.userId||ce.user_id;return{id:ce.noteId||ce.note_id||ce.id||String(Math.random()),user:{name:Ve,avatar:Ve.split(" ").map(rt=>rt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:tt},content:ce.message||"",timestamp:ce.createdAt||ce.created_at||new Date().toISOString(),attachments:Array.isArray(ce.attachments)?ce.attachments.map(rt=>({attachmentId:rt.attachmentId||rt.attachment_id,name:rt.fileName||rt.file_name||rt.name,fileName:rt.fileName||rt.file_name||rt.name,url:rt.storageUrl||rt.storage_url||rt.url||"#",type:rt.fileType||rt.file_type||rt.type||"file",fileType:rt.fileType||rt.file_type||rt.type||"file",fileSize:rt.fileSize||rt.file_size})):void 0,isCurrentUser:ze===N}}):[];C(Re)}catch(ie){console.error("[WorkNoteChat] Error loading work notes:",ie)}})()},[s,u,se]);const Q=ie=>{const Re=O.maxFileSizeMB*1024*1024;if(ie.size>Re)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${O.maxFileSizeMB}MB. Current size: ${(ie.size/(1024*1024)).toFixed(2)}MB`};const ce=ie.name.toLowerCase(),Ve=ce.substring(ce.lastIndexOf(".")+1);return O.allowedFileTypes.includes(Ve)?{valid:!0}:{valid:!1,reason:`File type "${Ve}" is not allowed. Allowed types: ${O.allowedFileTypes.join(", ")}`}},le=ie=>{if(!ie.target.files||ie.target.files.length===0)return;const Re=Array.from(ie.target.files),ce=[],Ve=[];Re.forEach(Be=>{const tt=Q(Be);tt.valid?Ve.push(Be):ce.push({fileName:Be.name,reason:tt.reason||"Unknown validation error"})}),ce.length>0&&re({open:!0,errors:ce}),Ve.length>0&&(R(Be=>[...Be,...Ve]),Ve.length{R(Re=>Re.filter((ce,Ve)=>Ve!==ie)),V.current&&(V.current.value="")},ge=ie=>{f(Re=>Re+ie),w(!1)},Fe=()=>{var ie;(ie=V.current)==null||ie.click()},_e=async ie=>{var Re,ce;try{await op(u,ie);const Ve=await Es(u),Be=Array.isArray(Ve==null?void 0:Ve.participants)?Ve.participants:[];if(Be.length){const tt=Be.map(ze=>{const rt=ze.participantType||ze.participant_type||"participant",qe=ze.userId||ze.user_id||"",ot=ze.userName||ze.user_name||ze.userEmail||ze.user_email||"User",Us=ze.userEmail||ze.user_email||"",rs=ot.split(" ").map(gt=>gt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:ot,avatar:rs,role:Ne(rt),status:"offline",email:Us,lastSeen:void 0,permissions:["read"],userId:qe}});ve(tt),Y.current&&Y.current.connected&&Y.current.emit("request:online-users",{requestId:u})}$(!1),E({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),B(!0)}catch(Ve){throw console.error("Failed to add spectator:",Ve),E({success:!1,title:"Failed to Add Spectator",message:((ce=(Re=Ve==null?void 0:Ve.response)==null?void 0:Re.data)==null?void 0:ce.error)||"Failed to add spectator. Please try again."}),B(!0),Ve}},Xe=async(ie,Re,ce)=>{var Ve,Be;if(d)await d(ie,Re,ce),T(!1);else try{await lp(u,ie,Re,ce);const tt=await Es(u),ze=Array.isArray(tt==null?void 0:tt.participants)?tt.participants:[];if(ze.length){const rt=ze.map(qe=>{const ot=qe.participantType||qe.participant_type||"participant",Us=qe.userId||qe.user_id||"",rs=qe.userName||qe.user_name||qe.userEmail||qe.user_email||"User",gt=qe.userEmail||qe.user_email||"",ct=rs.split(" ").map(Dt=>Dt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:rs,avatar:ct,role:Ne(ot),status:"offline",email:gt,lastSeen:void 0,permissions:["read"],userId:Us}});ve(rt),Y.current&&Y.current.connected&&Y.current.emit("request:online-users",{requestId:u})}T(!1),E({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${ce} with ${Re}h TAT`}),B(!0)}catch(tt){throw console.error("Failed to add approver:",tt),E({success:!1,title:"Failed to Add Approver",message:((Be=(Ve=tt==null?void 0:tt.response)==null?void 0:Ve.data)==null?void 0:Be.error)||"Failed to add approver. Please try again."}),B(!0),tt}},lt=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],Nt=ie=>{const Re=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,ce=[];let Ve;for(;(Ve=Re.exec(ie))!==null;)if(Ve[1]){const Be=Ve.index+Ve[0].length,tt=ie.slice(Be),ze=ie[Be];(tt.startsWith("@")||!ze||/\s|[.,!?;:]|@/.test(ze))&&ce.push(Ve[1].trim())}return ce},wt=ie=>{ie.key==="Enter"&&!ie.shiftKey&&(ie.preventDefault(),Ae())},As=(ie,Re)=>{C(ce=>ce.map(Ve=>{if(Ve.id===ie){const Be=Ve.reactions||[],tt=Be.find(ze=>ze.emoji===Re);if(tt)if(tt.users.includes("You")){if(tt.users=tt.users.filter(ze=>ze!=="You"),tt.users.length===0)return{...Ve,reactions:Be.filter(ze=>ze.emoji!==Re)}}else tt.users.push("You");else Be.push({emoji:Re,users:["You"]});return{...Ve,reactions:Be}}return Ve}))};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(Hs,{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:G.title}),e.jsx(ae,{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:[Te.slice(0,3).map((ie,Re)=>e.jsx(ls,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(os,{className:"bg-blue-500 text-white text-xs font-semibold",children:ie.avatar})},Re)),Te.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:["+",Te.length-3]})]})}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>L(!A),className:"lg:hidden",children:e.jsx(Jt,{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(Ss,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ce,{placeholder:"Search messages...",value:b,onChange:ie=>j(ie.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:[Ke.map(ie=>{const Re=ie.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${ie.isSystem?"justify-center":Re?"justify-end":""}`,children:[!ie.isSystem&&!Re&&e.jsx(ls,{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(os,{className:`text-white font-semibold text-xs sm:text-sm ${ie.user.role==="Initiator"?"bg-green-600":ie.user.role==="Current User"?"bg-blue-500":ie.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:ie.user.avatar})}),e.jsx("div",{className:`${Re?"max-w-[70%]":"flex-1"} min-w-0 ${ie.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:ie.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($t,{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:ie.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:gs(ie.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${Re?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[ie.user.name," ",Re&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(ae,{variant:"outline",className:"text-xs flex-shrink-0",children:ie.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"}),gs(ie.timestamp)]}),ie.isHighPriority&&e.jsxs(ae,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(Cb,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${Re?"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:ET(ie.content)}}),ie.attachments&&ie.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:ie.attachments.map((ce,Ve)=>{const Be=ce.fileSize||ce.file_size,tt=ce.fileName||ce.file_name||ce.name,ze=ce.fileType||ce.file_type||ce.type||"",rt=ce.attachmentId||ce.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(Cx,{type:ze})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs sm:text-sm font-medium text-gray-700 truncate",children:tt}),Be&&e.jsx("p",{className:"text-xs text-gray-500",children:_T(Be)})]}),rt&&(()=>{const qe=(ze||"").toLowerCase();return qe.includes("image")||qe.includes("pdf")||qe.includes("jpg")||qe.includes("jpeg")||qe.includes("png")||qe.includes("gif")})()&&e.jsx(M,{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:qe=>{qe.preventDefault(),qe.stopPropagation();const ot=Fw(rt);U({fileName:tt,fileType:ze,fileUrl:ot,fileSize:Be,attachmentId:rt})},title:"Preview file",children:e.jsx(St,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(M,{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 qe=>{if(qe.preventDefault(),qe.stopPropagation(),!rt){X.error("Cannot download: Attachment ID missing");return}try{await Km(rt)}catch{X.error("Failed to download file")}},title:"Download file",children:e.jsx(Rt,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Ve)})})}),ie.reactions&&ie.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:[ie.reactions.map((ce,Ve)=>e.jsxs("button",{onClick:()=>As(ie.id,ce.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${ce.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:ce.emoji}),e.jsx("span",{className:"text-xs font-medium",children:ce.users.length})]},Ve)),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>w(!y),children:e.jsx(bs,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!ie.isSystem&&Re&&e.jsx(ls,{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(os,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:ie.user.avatar})})]},ie.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:V,onChange:le,className:"hidden",multiple:!0,accept:O.allowedFileTypes.map(ie=>`.${ie}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((ie,Re)=>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(Cx,{type:ie.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:ie.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(ie.size/1024).toFixed(1)," KB"]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>pe(Re),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(jt,{className:"h-3 w-3 text-red-600"})})]},Re))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const ie=g.lastIndexOf("@"),Re=ie>=0;if(!Re)return null;const ce=g.slice(ie+1),Ve=ce.trim(),Be=ce.endsWith(" "),tt=Ve.length>0,ze=Ve.includes(" ")&&!Be,rt=Be&&tt;if(!(Re&&ce.length<=20&&!ze&&!rt))return null;const ot=Ve.toLowerCase(),Us=se.filter(rs=>rs.userId===N?!1:ot?rs.name.toLowerCase().includes(ot):!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:Us.length>0?Us.map((rs,gt)=>e.jsxs("button",{type:"button",onClick:ct=>{ct.preventDefault(),ct.stopPropagation();const Dt=g.lastIndexOf("@"),vs=g.slice(0,Dt);f(vs+"@"+rs.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(ls,{className:"h-10 w-10",children:e.jsx(os,{className:`text-white text-sm font-semibold ${rs.role==="Initiator"?"bg-green-600":rs.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:rs.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:rs.name}),e.jsx("p",{className:"text-xs text-gray-600",children:rs.role})]})]},gt)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:ot?`No participants found matching "${ot}"`:"No other participants available"})})]})})(),e.jsx(is,{placeholder:"Type your message... Use @username to mention someone",value:g,onChange:ie=>f(ie.target.value),onKeyPress:wt,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}),y&&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(M,{variant:"ghost",size:"sm",onClick:()=>w(!1),className:"h-6 w-6 p-0",children:e.jsx(jt,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:lt.map((ie,Re)=>e.jsx("button",{onClick:()=>ge(ie),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:ie,children:ie},Re))})]})]}),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(M,{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:Fe,title:"Attach file",children:e.jsx(Wi,{className:"h-4 w-4"})}),e.jsx(M,{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(!y),title:"Add emoji",children:e.jsx(Sb,{className:"h-4 w-4"})}),e.jsx(M,{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:()=>f(ie=>ie+"@"),title:"Mention someone",children:e.jsx(Xi,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto flex-shrink-0",children:[e.jsxs("span",{className:"text-xs text-gray-500 hidden md:inline whitespace-nowrap",children:[g.length,"/2000"]}),e.jsxs(M,{onClick:Ae,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(mh,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),A&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>L(!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 ${A?"fixed right-0 top-0 bottom-0 z-50 shadow-xl":"hidden lg:flex"} @@ -47,7 +47,7 @@ Activity has been automatically created for claim ${n}. All stakeholders have been notified. -This is an automated message.`,p=o||m;return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-2xl lg:max-w-[1000px] max-w-2xl",children:[e.jsx(pt,{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(fa,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ut,{className:"text-lg leading-none font-semibold",children:"Email Notification Template"}),e.jsxs(_t,{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(fa,{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(Ji,{className:"w-5 h-5 text-purple-600"}),e.jsx("span",{className:"font-semibold text-gray-900",children:"Royal Enfield"})]}),e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("pre",{className:"whitespace-pre-wrap font-sans text-sm text-gray-700 leading-relaxed bg-transparent p-0 border-0",children:p})}),e.jsx("div",{className:"pt-3 border-t border-gray-200",children:e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx(dt,{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(ae,{className:"bg-blue-50 text-blue-700 border-blue-200",children:["Step ",a]}),e.jsx(ae,{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(M,{variant:"outline",onClick:s,className:"h-9",children:[e.jsx(jt,{className:"w-4 h-4 mr-2"}),"Close"]})})]})})}function R5({isOpen:t,onClose:s,onApprove:a,onReject:r,onRequestRevision:n,proposalData:i,dealerName:l="Dealer",activityName:o="Activity",requestId:c,request:d,previousProposalData:m,taxationType:p}){const x=h.useMemo(()=>p==="Non GST"||p==="Non-GST",[p]),[u,g]=h.useState(""),[f,b]=h.useState(!1),[j,y]=h.useState(null),[w,v]=h.useState(!1),C=h.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const I=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(I)?I.reduce((E,W)=>{const V=typeof W=="object"&&W.amount||0,Y=typeof W=="object"&&W.quantity||1,Z=V*Y,O=typeof W=="object"&&W.gstAmt||0,z=W.totalAmt||Z+O;return E+(Number(z)||0)},0):0},[i]),A=h.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const I=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(I)?I.reduce((E,W)=>{const V=typeof W=="object"&&W.amount||0,Y=typeof W=="object"&&W.quantity||1;return E+Number(V)*Number(Y)},0):0},[i]),L=h.useMemo(()=>{const I=(d==null?void 0:d.internalOrders)||(d==null?void 0:d.internal_orders)||[];if(Array.isArray(I)&&I.length>0)return I.reduce((W,V)=>{const Y=Number(V.ioBlockedAmount||V.io_blocked_amount||0);return W+Y},0);const E=(d==null?void 0:d.internalOrder)||(d==null?void 0:d.internal_order);return Number((E==null?void 0:E.ioBlockedAmount)||(E==null?void 0:E.io_blocked_amount)||0)},[d==null?void 0:d.internalOrders,d==null?void 0:d.internal_orders,d==null?void 0:d.internalOrder,d==null?void 0:d.internal_order]),D=L>=A-.01,R=Math.max(0,A-L),[N,_]=h.useState(null),S=I=>{if(!I)return"—";try{return new Date(I).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return I}},U=I=>{if(!I.name)return!1;const E=I.name.toLowerCase();return E.endsWith(".pdf")||E.endsWith(".jpg")||E.endsWith(".jpeg")||E.endsWith(".png")||E.endsWith(".gif")||E.endsWith(".webp")},F=I=>{let E=I.url||I.storageUrl||"";const W=I.id||I.documentId||"";if(!W&&!E){X.error("Document preview not available");return}if(E&&!E.startsWith("http")&&!E.startsWith("blob:")){const V="https://reflow-uat.royalenfield.com",Y=V.endsWith("/")?V.slice(0,-1):V,Z=E.startsWith("/")?E:`/${E}`;E=`${Y}${Z}`}_({name:I.name||"Document",url:E||(W?mn(W):""),type:(I.name||"").toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg",id:W})};h.useEffect(()=>()=>{N!=null&&N.url&&N.url.startsWith("blob:")&&window.URL.revokeObjectURL(N.url)},[N]);const $=async()=>{if(!u.trim()){X.error("Please provide approval comments");return}try{b(!0),y("approve"),await a(u),k(),s()}catch(I){console.error("Failed to approve proposal:",I),X.error("Failed to approve proposal. Please try again.")}finally{b(!1),y(null)}},P=async()=>{if(!u.trim()){X.error("Please provide rejection reason");return}try{b(!0),y("reject"),await r(u),k(),s()}catch(I){console.error("Failed to reject proposal:",I),X.error("Failed to reject proposal. Please try again.")}finally{b(!1),y(null)}},T=async()=>{if(!u.trim()){X.error("Please provide reasons for requesting a revision");return}if(!n){X.error("Revision feature is not available");return}try{b(!0),y("revision"),await n(u),k(),s()}catch(I){console.error("Failed to request revision:",I),X.error("Failed to request revision. Please try again.")}finally{b(!1),y(null)}},k=()=>{g(""),y(null)},B=()=>{f||(k(),s())};return t?e.jsxs(ht,{open:t,onOpenChange:B,children:[e.jsxs(mt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(ut,{className:"flex items-center gap-2 text-lg lg:text-xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600"}),"Requestor Evaluation & Confirmation"]}),p&&e.jsx(ae,{className:`ml-2 border-none shadow-sm ${x?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:x?"Non-GST Claim":"GST Claim"})]}),e.jsx(_t,{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(!w),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(Ie,{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(ae,{variant:"secondary",className:"bg-amber-200 text-amber-800 text-[10px]",children:["₹",Number(m.totalEstimatedBudget||m.totalBudget||0).toLocaleString("en-IN")]})]}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:w?e.jsx(Vo,{className:"w-4 h-4"}):e.jsx(bs,{className:"w-4 h-4"})})]}),w&&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(dt,{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:U({name:m.documentUrl})?e.jsxs(e.Fragment,{children:[e.jsx(St,{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(Rt,{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(or,{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((I,E)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:I.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(I.amount).toLocaleString("en-IN")]})]},E)),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(Ie,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:m.otherDocuments.map((I,E)=>e.jsx(Er,{document:{documentId:I.documentId||I.id||"",name:I.originalFileName||I.fileName||I.name||"Supporting Document",fileType:(I.originalFileName||I.fileName||I.name||"").split(".").pop()||"file",uploadedAt:I.uploadedAt||new Date().toISOString()},onPreview:U({name:I.originalFileName||I.fileName||I.name||""})?()=>F(I):void 0,onDownload:async W=>{if(W)await Ls(W);else{let V=I.storageUrl||I.documentUrl;if(V&&!V.startsWith("http")){const Y="https://reflow-uat.royalenfield.com",Z=Y.endsWith("/")?Y.slice(0,-1):Y,O=V.startsWith("/")?V:`/${V}`;V=`${Z}${O}`}V&&window.open(V,"_blank")}}},E))})]}),(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(Hs,{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(Ie,{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(Ie,{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 ",S(i.submittedAt)]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:i.proposalDocument.id&&e.jsxs(e.Fragment,{children:[U(i.proposalDocument)&&e.jsx("button",{type:"button",onClick:()=>F(i.proposalDocument),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(St,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var I;try{(I=i.proposalDocument)!=null&&I.id&&await Ls(i.proposalDocument.id)}catch(E){console.error("Failed to download document:",E),X.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Rt,{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(Ie,{className:"w-4 h-4 text-gray-600"}),"Other Supporting Documents"]}),e.jsxs(ae,{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((I,E)=>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(Ie,{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:I.name,children:I.name})]}),I.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[U(I)&&e.jsx("button",{type:"button",onClick:()=>F(I),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(St,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{I.id&&await Ls(I.id)}catch(W){console.error("Failed to download document:",W),X.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Rt,{className:"w-5 h-5 text-gray-600"})})]})]},E))})]})]}),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(or,{className:"w-4 h-4 text-green-600"}),"Cost Breakup"]})}),(()=>{const I=i!=null&&i.costBreakup?Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[]:[];return I&&Array.isArray(I)&&I.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden max-h-[200px] lg:max-h-[180px] overflow-y-auto",children:[e.jsx("div",{className:"bg-gray-50 px-3 lg:px-4 py-2 border-b sticky top-0",children:e.jsxs("div",{className:`grid ${x?"grid-cols-3":"grid-cols-4"} gap-4 text-xs lg:text-sm font-semibold text-gray-700`,children:[e.jsx("div",{className:"col-span-1",children:"Item Description"}),e.jsx("div",{className:"text-right",children:"Base"}),!x&&e.jsx("div",{className:"text-right",children:"GST"}),e.jsx("div",{className:"text-right",children:"Total"})]})}),e.jsx("div",{className:"divide-y",children:I.map((E,W)=>{var V,Y;return e.jsxs("div",{className:`px-3 lg:px-4 py-2 lg:py-3 grid ${x?"grid-cols-3":"grid-cols-4"} gap-4`,children:[e.jsxs("div",{className:"col-span-1 text-xs lg:text-sm text-gray-700",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[e.jsx("span",{className:"font-medium",children:(V=E==null?void 0:E.description)!=null&&V.startsWith("[ADDITIONAL]")?E.description.replace("[ADDITIONAL]","").trim():(E==null?void 0:E.description)||"N/A"}),I.some(Z=>{var O;return(O=Z==null?void 0:Z.description)==null?void 0:O.startsWith("[ADDITIONAL]")})&&((Y=E==null?void 0:E.description)!=null&&Y.startsWith("[ADDITIONAL]")?e.jsx(ae,{className:"text-[9px] h-3.5 px-1 bg-amber-100 text-amber-700 hover:bg-amber-100 border-none leading-none",children:"ADDITIONAL"}):e.jsx(ae,{className:"text-[9px] h-3.5 px-1 bg-gray-100 text-gray-600 hover:bg-gray-100 border-none leading-none",children:"ORIGINAL"}))]}),!x&&(E!=null&&E.gstRate)?e.jsxs("span",{className:"block text-[10px] text-gray-400",children:[E.gstRate,"% GST"]}):null]}),e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number(E==null?void 0:E.amount)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),!x&&e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number(E==null?void 0:E.gstAmt)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),e.jsxs("div",{className:"text-xs lg:text-sm font-semibold text-gray-900 text-right",children:["₹",(Number((E==null?void 0:E.totalAmt)||((E==null?void 0:E.amount)||0)*((E==null?void 0:E.quantity)||1)+((E==null?void 0:E.gstAmt)||0))||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]},(E==null?void 0:E.id)||(E==null?void 0:E.description)||W)})})]}),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(or,{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:["₹",C.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(dt,{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?S(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(Hs,{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(is,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:u,onChange:I=>g(I.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:[u.length," characters"]})]})]})}),!u.trim()&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-2 flex items-start gap-2 lg:col-span-2",children:[e.jsx(At,{className:"w-3.5 h-3.5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-amber-800",children:"Please provide comments before making a decision. Comments are required and will be visible to all participants."})]})]})]}),e.jsxs(Et,{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(M,{variant:"outline",onClick:B,disabled:f,className:"border-2 w-full sm:w-auto",children:"Cancel"}),e.jsxs("div",{className:"flex flex-col gap-2 w-full sm:w-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(M,{onClick:T,disabled:!u.trim()||f,variant:"secondary",className:"bg-amber-100 hover:bg-amber-200 text-amber-900 border border-amber-200 w-full sm:w-auto",children:f&&j==="revision"?"Requesting...":e.jsxs(e.Fragment,{children:[e.jsx(Hs,{className:"w-4 h-4 mr-2"}),"Request Revised Quotation"]})}),e.jsx(M,{onClick:P,disabled:!u.trim()||f,variant:"destructive",className:"bg-red-600 hover:bg-red-700 w-full sm:w-auto",children:f&&j==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),"Reject (Cancel Request)"]})}),e.jsx(M,{onClick:$,disabled:!u.trim()||!D||f,className:"bg-green-600 hover:bg-green-700 text-white disabled:opacity-50 disabled:cursor-not-allowed w-full sm:w-auto",title:D?"":"Please block IO budget before approving",children:f&&j==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Oe,{className:"w-4 h-4 mr-2"}),"Approve (Continue to Dept Lead)"]})})]}),!D&&e.jsx("p",{className:"text-xs text-red-600 text-center sm:text-left font-medium",children:L>0?`Pending block: ₹${R.toLocaleString("en-IN",{minimumFractionDigits:2})} more needs to be blocked in the IO Tab.`:"Please block IO budget in the IO Tab before approving."})]})]})]}),N&&e.jsx(Lr,{fileName:N.name,fileType:N.type||"",fileUrl:N.url,fileSize:N.size,attachmentId:N.id,onDownload:Ls,open:!!N,onClose:()=>_(null)})]}):null}function D5({isOpen:t,onClose:s,snapshot:a,type:r,title:n}){const[i,l]=h.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)},p=u=>{var f;const g=(f=(u||"").split(".").pop())==null?void 0:f.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"),f=u.documentId||"",b=g.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let j="";if(f)j=mn(f);else if(j=u.storageUrl||u.documentUrl||"",j&&!j.startsWith("http")){const y="https://reflow-uat.royalenfield.com",w=y.endsWith("/")?y.slice(0,-1):y,v=j.startsWith("/")?j:`/${j}`;j=`${w}${v}`}l({fileName:g,fileType:b,documentId:f,fileUrl:j,fileSize:u.sizeBytes})};return e.jsxs(e.Fragment,{children:[e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"max-w-2xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden",children:[e.jsxs(pt,{className:"px-6 py-4 border-b",children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[o?e.jsx(Ie,{className:"w-5 h-5 text-blue-600"}):e.jsx(Pt,{className:"w-5 h-5 text-green-600"}),n||(o?"Proposal Snapshot Details":"Completion Snapshot Details")]}),e.jsxs(_t,{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(dt,{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(Er,{document:{documentId:"",name:o?"Proposal Document":"Completion Document",fileType:p(a.documentUrl),uploadedAt:new Date().toISOString()},onPreview:m(a.documentUrl)?()=>x({fileName:o?"Proposal Document":"Completion Document",documentUrl:a.documentUrl}):void 0,onDownload:async()=>{let u=a.documentUrl;if(!u.startsWith("http")){const g="https://reflow-uat.royalenfield.com",f=g.endsWith("/")?g.slice(0,-1):g,b=u.startsWith("/")?u:`/${u}`;u=`${f}${b}`}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(ae,{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(Er,{document:{documentId:u.documentId||"",name:u.originalFileName||u.fileName||"Supporting Document",fileType:p(u.originalFileName||u.fileName||""),uploadedAt:u.uploadedAt||new Date().toISOString()},onPreview:m(u.originalFileName||u.fileName||"")?()=>x(u):void 0,onDownload:u.documentId?Ls:async()=>{let f=u.storageUrl||u.documentUrl;if(f&&!f.startsWith("http")){const b="https://reflow-uat.royalenfield.com",j=b.endsWith("/")?b.slice(0,-1):b,y=f.startsWith("/")?f:`/${f}`;f=`${j}${y}`}f&&window.open(f,"_blank")}},g))})]}),(a.costItems||a.expenses)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1",children:o?"Cost Breakdown":"Expenses Breakdown"}),e.jsx("div",{className:"border rounded-md overflow-hidden text-sm",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-600 text-xs uppercase",children:e.jsxs("tr",{children:[e.jsx("th",{className:"p-3 font-medium",children:"Description"}),e.jsx("th",{className:"p-3 font-medium text-right",children:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-100",children:[(a.costItems||a.expenses).length>0?(a.costItems||a.expenses).map((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(rh,{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(M,{onClick:s,children:"Close"})})]})}),i&&e.jsx(Lr,{fileName:i.fileName,fileType:i.fileType,fileUrl:i.fileUrl,fileSize:i.fileSize,attachmentId:i.documentId,onDownload:Ls,open:!!i,onClose:()=>l(null)})]})}async function F5(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 I5(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 P5(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 E5(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 _5(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 f0(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 M5(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 L5(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 O5(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}}async function $5(t){var s;try{const a=await je.post(`/dealer-claims/${t}/wfm/retrigger`);return((s=a.data)==null?void 0:s.data)||a.data}catch(a){throw console.error("[DealerClaimAPI] Error re-triggering WFM push:",a),a}}const Br=t=>{if(!t)return"";try{return gs(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}}},U5=t=>{switch(t){case"approved":return e.jsx(Oe,{className:"w-5 h-5 text-green-600"});case"skipped":return e.jsx(Oe,{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(Oe,{className:"w-5 h-5 text-red-600"});default:return e.jsx(st,{className:"w-5 h-5 text-gray-400"})}},B5=t=>{switch(t){case"approved":return"bg-green-100 text-green-800 border-green-200";case"skipped":return"bg-green-50 text-green-700 border-green-200";case"pending":return"bg-purple-100 text-purple-800 border-purple-200";case"rejected":return"bg-red-100 text-red-800 border-red-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},V5=(t,s)=>s&&(t==="pending"||t==="in_progress")?"border-purple-500 bg-purple-50 shadow-md":t==="approved"||t==="skipped"?"border-green-500 bg-green-50":t==="rejected"?"border-red-500 bg-red-50":"border-gray-200 bg-white",z5=t=>{switch(t){case"approved":return"bg-green-100";case"skipped":return"bg-green-100";case"pending":return"bg-purple-100";case"rejected":return"bg-red-100";default:return"bg-gray-100"}};function H5({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n,documentPolicy:i}){var fr,Xa,Ta,Ja,Za,qa,er,tr,Gt,Ts,yt,xs,Os,ks,Oa,ja,sr,pn,gn,fn,Qc,Xc,Jc,Zc,qc,ed,td,sd,ad,rd,nd,id,ld,od,cd,dd,md,ud,xd,hd,pd,gd,fd,bd,jd,yd,vd,Nd,wd,Cd,Sd,Ad,Td,kd,Rd,Dd,Fd,Id,Pd,Ed,_d,Md,Ld,Od,$d,Ud,Bd,Vd,zd,Hd,Wd,Gd,Yd,Kd,Qd,Xd,Jd,Zd,qd,em,tm,sm,am,rm,nm,im,lm,om,cm,dm,mm,um,xm,hm,pm,gm,fm,bm,jm,ym,vm,Nm,wm;const[l,o]=h.useState(!1),[c,d]=h.useState(!1),[m,p]=h.useState(!1),[x,u]=h.useState(!1),[g,f]=h.useState(!1),[b,j]=h.useState(!1),[y,w]=h.useState(!1),[v,C]=h.useState(null),[A,L]=h.useState(!1),[D,R]=h.useState(null),[N,_]=h.useState([]),[S,U]=h.useState(!1),[F,$]=h.useState(new Set),[P,T]=h.useState(null),[k,B]=h.useState(null),[I,E]=h.useState(!1),[W,V]=h.useState(!1),[Y,Z]=h.useState([]),[O,z]=h.useState(0);h.useEffect(()=>{(async()=>{if(t!=null&&t.id||t!=null&&t.requestId){const Le=t.id||t.requestId;try{const be=await Es(Le),me=(be==null?void 0:be.approvalLevels)||(be==null?void 0:be.approvals)||[];if(me&&me.length>0){const fe=me.map(ue=>{var ke;return{step:ue.levelNumber||ue.level_number||0,levelNumber:ue.levelNumber||ue.level_number||0,levelName:ue.levelName||ue.level_name,approver:ue.approverName||ue.approver_name||"",approverEmail:(ue.approverEmail||ue.approver_email||"").toLowerCase(),status:((ke=ue.status)==null?void 0:ke.toLowerCase())||"waiting",tatHours:ue.tatHours||ue.tat_hours||24,elapsedHours:ue.elapsedHours||ue.elapsed_hours,approvedAt:ue.actionDate||ue.action_date,comment:ue.comments||ue.comment,levelId:ue.levelId||ue.level_id}}).sort((ue,ke)=>(ue.levelNumber||0)-(ke.levelNumber||0));Z(ue=>ue.length!==fe.length||ue.some((De,we)=>{const vt=fe[we];return!vt||De.levelNumber!==vt.levelNumber||De.levelName!==vt.levelName||De.approverEmail!==vt.approverEmail||De.status!==vt.status})?fe:ue)}else Z([])}catch(be){console.warn("Failed to load approval flows from API:",be),t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&Z(t.approvalFlow)}}else t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&Z(t.approvalFlow)})()},[t==null?void 0:t.id,t==null?void 0:t.requestId,t==null?void 0:t.totalLevels,O]),h.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const H=t.id||t.requestId;(async()=>{try{const be=await Es(H),me=(be==null?void 0:be.approvalLevels)||(be==null?void 0:be.approvals)||[];if(me&&me.length>0){const fe=me.map(ue=>{var ke;return{step:ue.levelNumber||ue.level_number||0,levelNumber:ue.levelNumber||ue.level_number||0,levelName:ue.levelName||ue.level_name,approver:ue.approverName||ue.approver_name||"",approverEmail:(ue.approverEmail||ue.approver_email||"").toLowerCase(),status:((ke=ue.status)==null?void 0:ke.toLowerCase())||"waiting",tatHours:ue.tatHours||ue.tat_hours||24,elapsedHours:ue.elapsedHours||ue.elapsed_hours,approvedAt:ue.actionDate||ue.action_date,comment:ue.comments||ue.comment,levelId:ue.levelId||ue.level_id}}).sort((ue,ke)=>(ue.levelNumber||0)-(ke.levelNumber||0));Z(fe)}}catch(be){console.warn("Failed to load approval flows from API:",be)}})()}},[t==null?void 0:t.currentStep,t==null?void 0:t.totalLevels]);const K=async()=>{z(H=>H+1),await new Promise(H=>setTimeout(H,500)),n==null||n(),re()},re=async()=>{if(t!=null&&t.id||t!=null&&t.requestId)try{const Le=[...await _w(t.id||t.requestId)||[]].sort((be,me)=>new Date(me.createdAt).getTime()-new Date(be.createdAt).getTime());_(Le)}catch(H){console.warn("Failed to load version history:",H)}};h.useEffect(()=>{re()},[t==null?void 0:t.id,t==null?void 0:t.requestId,O]);const G=(H,Le,be)=>{var ue;const me=((t==null?void 0:t.totalLevels)||0)>5||(((ue=t==null?void 0:t.approvalLevels)==null?void 0:ue.length)||0)>5;if(Le&&Le.trim()&&(Le.toLowerCase().includes("additional approver")||!/^step\s+\d+$/i.test(Le)))return Le;const fe=me?{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 fe[H]?fe[H]:be&&be!=="Unknown"&&be!=="System"?`Additional Approver - ${be}`:`Additional Approver - Step ${H}`},se=(H,Le,be)=>{var ke;if(Le&&Le.toLowerCase().includes("additional approver"))return be&&be!=="Unknown"&&be!=="System"?`${be} will review and approve this request as an additional approver.`:"Additional approver will review and approve this request.";const fe=((t==null?void 0:t.totalLevels)||0)>5||(((ke=t==null?void 0:t.approvalLevels)==null?void 0:ke.length)||0)>5;if(Le&&Le.trim()){const De=Le.toLowerCase();if(De.includes("dealer")&&De.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(De.includes("requestor")&&(De.includes("evaluation")||De.includes("confirmation")))return"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)";if(De.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(De.includes("activity creation"))return"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.";if(De.includes("dealer")&&(De.includes("completion")||De.includes("documents")))return"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description";if(De.includes("requestor")&&(De.includes("claim")||De.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(De.includes("e-invoice")||De.includes("invoice generation")||De.includes("dms"))return"E-Invoice will be generated upon settlement initiation.";if(De.includes("credit note")||De.includes("sap"))return"Got credit note from SAP. Review and send to dealer to complete the claim management process."}const ue=fe?{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 ue[H]?ue[H]:be&&be!=="Unknown"&&be!=="System"?`${be} will review and approve this request.`:`Step ${H} approval required.`},ve=H=>{if(!N||N.length===0||!H)return{current:null,previous:null};const me=[...N.filter(ke=>{var De;return!!(ke.levelName&&ke.levelName.trim()===H.trim()||(De=ke.snapshotData)!=null&&De.levelName&&ke.snapshotData.levelName.trim()===H.trim())})].sort((ke,De)=>{if(De.version!==ke.version)return De.version-ke.version;const we=ke.snapshotType==="APPROVE"?1:ke.snapshotType==="PROPOSAL"||ke.snapshotType==="COMPLETION"?2:3,vt=De.snapshotType==="APPROVE"?1:De.snapshotType==="PROPOSAL"||De.snapshotType==="COMPLETION"?2:3;return we-vt}).filter((ke,De,we)=>ke.snapshotType==="WORKFLOW"?!we.some(Ct=>Ct.snapshotType==="APPROVE"&&Ct.levelName===ke.levelName&&Ct.version>=ke.version):!0),fe=me.length>0?me[0]:null,ue=me.length>1?me[1]:null;return{current:fe,previous:ue,all:me}},Te=(t==null?void 0:t.currentLevel)||(t==null?void 0:t.current_level)||(t==null?void 0:t.currentStep),Ke=Te!=null?Number(Te):null,Je=((t==null?void 0:t.status)||"").toUpperCase(),Pe=Je==="REJECTED",$e=Je==="CLOSED",ne=!Pe&&!$e&&(Je==="PENDING"||Je==="IN_PROGRESS"||Je==="IN-PROGRESS"),he=Y.find(H=>{var me,fe;const Le=H.levelId||H.level_id,be=(me=t==null?void 0:t.approvals)==null?void 0:me.find(ue=>ue.levelId===Le);return((fe=be==null?void 0:be.status)==null?void 0:fe.toLowerCase())==="rejected"}),Ne=he?Number(he.levelNumber||he.level_number||he.step||0):null,Ae=Y.map((H,Le)=>{var ya,Fs,xe,ft,zt,Ns,Tt;const be=Number(H.levelNumber||H.level_number||H.step||Le+1),me=H.levelName||H.level_name,fe=(ya=t==null?void 0:t.approvals)==null?void 0:ya.find(Ue=>Ue.levelId===H.levelId);let ue;if(me&&me.toLowerCase().includes("department lead")||be===3){const Ue=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);(Ue!=null&&Ue.ioNumber||Ue!=null&&Ue.io_number)&&(ue={ioNumber:Ue.ioNumber||Ue.io_number||"",blockedAmount:Ue.ioBlockedAmount||Ue.io_blocked_amount||0,availableBalance:Ue.ioAvailableBalance||Ue.io_available_balance||0,remainingBalance:Ue.ioRemainingBalance||Ue.io_remaining_balance||0,organizedBy:((Fs=Ue.organizer)==null?void 0:Fs.displayName)||((xe=Ue.organizer)==null?void 0:xe.name)||Ue.organizedBy||H.approver||"N/A",organizedAt:Ue.organizedAt||Ue.organized_at||H.approvedAt||(t==null?void 0:t.updatedAt)||""})}let De;be===6&&(fe!=null&&fe.dmsDetails?De={dmsNumber:fe.dmsDetails.dmsNumber||"",dmsRemarks:fe.dmsDetails.dmsRemarks||"",pushedBy:fe.dmsDetails.pushedBy||H.approver,pushedAt:fe.dmsDetails.pushedAt||H.approvedAt||""}:t!=null&&t.dmsNumber&&(De={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||((ft=t.dmsDetails)==null?void 0:ft.dmsRemarks)||"",pushedBy:H.approver,pushedAt:H.approvedAt||t.updatedAt||""}));let we;if(Pe||$e)((zt=fe==null?void 0:fe.status)==null?void 0:zt.toLowerCase())==="rejected"?we="rejected":Ne!==null&&be>Ne?we="waiting":((Ns=fe==null?void 0:fe.status)==null?void 0:Ns.toLowerCase())==="approved"?we="approved":Ne!==null&&beKe,we="waiting");else if(ne&&Ke!==null&&Ke>0)if(be>Ke)we="waiting";else if(beLe.step===Ke):null;Q=H&&(H.status==="pending"||H.status==="in_progress")?H:Ae.find(Le=>{var me;const be=((me=Le.status)==null?void 0:me.toLowerCase())||"";return be==="pending"||be==="in_progress"||be==="in-review"||be==="in_review"}),le=Q?Q.step:Ke||(t==null?void 0:t.currentStep)||1}else le=Ke||(t==null?void 0:t.currentStep)||1;const pe=((fr=s==null?void 0:s.email)==null?void 0:fr.toLowerCase())||"",ge=((Xa=t==null?void 0:t.dealerEmail)==null?void 0:Xa.toLowerCase())||((Ja=(Ta=t==null?void 0:t.dealer)==null?void 0:Ta.email)==null?void 0:Ja.toLowerCase())||((qa=(Za=t==null?void 0:t.claimDetails)==null?void 0:Za.dealerEmail)==null?void 0:qa.toLowerCase())||((tr=(er=t==null?void 0:t.claimDetails)==null?void 0:er.dealer_email)==null?void 0:tr.toLowerCase())||"",Fe=ge&&pe===ge,_e=Y.find(H=>(H.step||H.levelNumber||H.level_number)===le),Xe=((_e==null?void 0:_e.approverEmail)||"").toLowerCase(),lt=Xe&&pe===Xe,Nt=((Ts=(Gt=t==null?void 0:t.initiator)==null?void 0:Gt.email)==null?void 0:Ts.toLowerCase())||((yt=t==null?void 0:t.initiatorEmail)==null?void 0:yt.toLowerCase())||"",wt=Y.find(H=>{const Le=(H.approverEmail||"").toLowerCase(),be=(H.levelName||"").toLowerCase();return Nt&&Le===Nt||be.includes("requestor evaluation")||be.includes("requestor")&&be.includes("confirmation")}),As=wt&&(wt.step||wt.levelNumber||wt.level_number)||2,ie=wt||Y.find(H=>(H.step||H.levelNumber||H.level_number)===2),Re=((ie==null?void 0:ie.approverEmail)||"").toLowerCase(),ce=Re&&pe===Re,Ve=Y.find(H=>(H.step||H.levelNumber||H.level_number)===1),Be=((Ve==null?void 0:Ve.approverEmail)||"").toLowerCase(),tt=Be&&pe===Be,ze=Y.find(H=>(H.levelName||"").toLowerCase().includes("department lead")),rt=((ze==null?void 0:ze.approverEmail)||"").toLowerCase(),qe=rt&&pe===rt,ot=async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId;H.proposalDocument&&await Rn(H.proposalDocument,me,"APPROVAL");for(const ue of H.otherDocuments)await Rn(ue,me,"SUPPORTING");const fe=H.costBreakup.reduce((ue,ke)=>ue+(ke.totalAmt||ke.amount||0),0);await P5(me,{proposalDocument:H.proposalDocument||void 0,costBreakup:H.costBreakup.map(ue=>({description:ue.description,amount:ue.amount,gstRate:ue.gstRate,gstAmt:ue.gstAmt,cgstRate:ue.cgstRate,cgstAmt:ue.cgstAmt,sgstRate:ue.sgstRate,sgstAmt:ue.sgstAmt,igstRate:ue.igstRate,igstAmt:ue.igstAmt,utgstRate:ue.utgstRate,utgstAmt:ue.utgstAmt,cessRate:ue.cessRate,cessAmt:ue.cessAmt,totalAmt:ue.totalAmt,quantity:ue.quantity,hsnCode:ue.hsnCode,isService:ue.isService})),totalEstimatedBudget:fe,expectedCompletionDate:H.expectedCompletionDate,dealerComments:H.dealerComments}),X.success("Proposal submitted successfully"),K()}catch(me){console.error("Failed to submit proposal:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to submit proposal. Please try again.";throw X.error(fe),me}},Us=async H=>{var Le,be,me,fe,ue;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ke=t.id||t.requestId,De=await Es(ke),we=(De==null?void 0:De.approvalLevels)||(De==null?void 0:De.approvals)||[],vt=((be=(Le=t==null?void 0:t.initiator)==null?void 0:Le.email)==null?void 0:be.toLowerCase())||((me=t==null?void 0:t.initiatorEmail)==null?void 0:me.toLowerCase())||"",Ct=we.find(kt=>{const ya=(kt.approverEmail||kt.approver_email||"").toLowerCase(),Fs=(kt.levelName||kt.level_name||"").toLowerCase(),xe=kt.levelNumber||kt.level_number;return vt&&ya===vt||Fs.includes("requestor evaluation")||Fs.includes("requestor")&&Fs.includes("confirmation")||xe===As})||we.find(kt=>(kt.levelNumber||kt.level_number)===2);if(!(Ct!=null&&Ct.levelId)&&!(Ct!=null&&Ct.level_id))throw new Error("Initiator approval level not found");const Rs=Ct.levelId||Ct.level_id;await Tn(ke,Rs,H),X.success("Proposal approved successfully"),K()}catch(ke){console.error("Failed to approve proposal:",ke);const De=((ue=(fe=ke==null?void 0:ke.response)==null?void 0:fe.data)==null?void 0:ue.message)||(ke==null?void 0:ke.message)||"Failed to approve proposal. Please try again.";throw X.error(De),ke}},rs=async H=>{var Le,be,me,fe,ue;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ke=t.id||t.requestId,De=await Es(ke),we=(De==null?void 0:De.approvalLevels)||(De==null?void 0:De.approvals)||[],vt=((be=(Le=t==null?void 0:t.initiator)==null?void 0:Le.email)==null?void 0:be.toLowerCase())||((me=t==null?void 0:t.initiatorEmail)==null?void 0:me.toLowerCase())||"",Ct=we.find(kt=>{const ya=(kt.approverEmail||kt.approver_email||"").toLowerCase(),Fs=(kt.levelName||kt.level_name||"").toLowerCase(),xe=kt.levelNumber||kt.level_number;return vt&&ya===vt||Fs.includes("requestor evaluation")||Fs.includes("requestor")&&Fs.includes("confirmation")||xe===As})||we.find(kt=>(kt.levelNumber||kt.level_number)===2);if(!(Ct!=null&&Ct.levelId)&&!(Ct!=null&&Ct.level_id))throw new Error("Initiator approval level not found");const Rs=Ct.levelId||Ct.level_id;await wr(ke,Rs,"Proposal rejected by requestor",H),X.success("Proposal rejected. Request has been cancelled."),K()}catch(ke){console.error("Failed to reject proposal:",ke);const De=((ue=(fe=ke==null?void 0:ke.response)==null?void 0:fe.data)==null?void 0:ue.message)||(ke==null?void 0:ke.message)||"Failed to reject proposal. Please try again.";throw X.error(De),ke}},gt=async H=>{var Le,be,me,fe,ue;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ke=t.id||t.requestId,De=await Es(ke),we=(De==null?void 0:De.approvalLevels)||(De==null?void 0:De.approvals)||[],vt=((be=(Le=t==null?void 0:t.initiator)==null?void 0:Le.email)==null?void 0:be.toLowerCase())||((me=t==null?void 0:t.initiatorEmail)==null?void 0:me.toLowerCase())||"",Ct=we.find(kt=>{const ya=(kt.approverEmail||kt.approver_email||"").toLowerCase(),Fs=(kt.levelName||kt.level_name||"").toLowerCase(),xe=kt.levelNumber||kt.level_number;return vt&&ya===vt||Fs.includes("requestor evaluation")||Fs.includes("requestor")&&Fs.includes("confirmation")||xe===As})||we.find(kt=>(kt.levelNumber||kt.level_number)===2);if(!(Ct!=null&&Ct.levelId)&&!(Ct!=null&&Ct.level_id))throw new Error("Initiator approval level not found");const Rs=Ct.levelId||Ct.level_id;await wr(ke,Rs,"Revised Quotation Requested",H),X.success("Revision requested. Request returned to dealer."),K()}catch(ke){console.error("Failed to request revision:",ke);const De=((ue=(fe=ke==null?void 0:ke.response)==null?void 0:fe.data)==null?void 0:ue.message)||(ke==null?void 0:ke.message)||"Failed to request revision. Please try again.";throw X.error(De),ke}},ct=async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=await Es(me),ke=((fe==null?void 0:fe.approvalLevels)||(fe==null?void 0:fe.approvals)||[]).find(we=>{const vt=(we.levelName||we.level_name||"").toLowerCase();return vt.includes("requestor claim")||vt.includes("requestor - claim")});if(!(ke!=null&&ke.levelId)&&!(ke!=null&&ke.level_id))throw new Error("Claim approval level not found");const De=ke.levelId||ke.level_id;await wr(me,De,"Revised Quotation Requested",H),X.success("Re-quotation requested. Request returned to dealer."),K()}catch(me){console.error("Failed to request re-quotation:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to request re-quotation. Please try again.";throw X.error(fe),me}},Dt=async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=await Es(me),ue=(fe==null?void 0:fe.approvalLevels)||(fe==null?void 0:fe.approvals)||[],ke=ue.find(we=>(we.levelName||we.level_name||"").toLowerCase().includes("department lead"))||ue.find(we=>(we.levelNumber||we.level_number)===3);if(!(ke!=null&&ke.levelId)&&!(ke!=null&&ke.level_id))throw new Error("Department Lead approval level not found");const De=ke.levelId||ke.level_id;await f0(me,{ioNumber:H.ioNumber}),await Tn(me,De,H.comments),X.success("Request approved and IO organized successfully"),K()}catch(me){console.error("Failed to approve and organize IO:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to approve request. Please try again.";throw X.error(fe),me}},vs=async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=H.closedExpenses.map(ue=>({description:ue.description,amount:ue.amount,gstRate:ue.gstRate,gstAmt:ue.gstAmt,cgstRate:ue.cgstRate,cgstAmt:ue.cgstAmt,sgstRate:ue.sgstRate,sgstAmt:ue.sgstAmt,igstRate:ue.igstRate,igstAmt:ue.igstAmt,utgstRate:ue.utgstRate,utgstAmt:ue.utgstAmt,cessRate:ue.cessRate,cessAmt:ue.cessAmt,totalAmt:ue.totalAmt,quantity:ue.quantity,hsnCode:ue.hsnCode,isService:ue.isService}));if(await E5(me,{activityCompletionDate:H.activityCompletionDate,numberOfParticipants:H.numberOfParticipants,closedExpenses:fe,totalClosedExpenses:H.totalClosedExpenses,completionDocuments:H.completionDocuments,activityPhotos:H.activityPhotos,completionDescription:H.completionDescription}),H.invoicesReceipts&&H.invoicesReceipts.length>0)for(const ue of H.invoicesReceipts)await Rn(ue,me,"SUPPORTING");H.attendanceSheet&&await Rn(H.attendanceSheet,me,"SUPPORTING"),X.success("Completion documents submitted successfully"),K()}catch(me){console.error("Failed to submit completion documents:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to submit completion documents. Please try again.";throw X.error(fe),me}},ts=async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=new Date().toISOString().slice(0,10);await M5(me,{eInvoiceDate:fe}),X.success("E-Invoice generation initiated successfully."),K()}catch(me){console.error("[DealerClaimWorkflowTab] Error generating e-invoice:",me);let ue=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"E-Invoice generation failed. Please try again.";throw ue.length>300&&(ue=ue.substring(0,300)+"..."),X.error(ue),me}},Sa=async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=await Es(me),ue=(fe==null?void 0:fe.approvalLevels)||(fe==null?void 0:fe.approvals)||[],ke=ue.find(we=>(we.levelName||we.level_name||"").toLowerCase().includes("department lead"))||ue.find(we=>(we.levelNumber||we.level_number)===3);if(!(ke!=null&&ke.levelId)&&!(ke!=null&&ke.level_id))throw new Error("Department Lead approval level not found");const De=ke.levelId||ke.level_id;await wr(me,De,"Dept Lead rejected - More clarification required",H),X.success("Request rejected. Request has been cancelled."),K()}catch(me){console.error("Failed to reject request:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to reject request. Please try again.";throw X.error(fe),me}},[Ma,Aa]=h.useState(null);h.useEffect(()=>{if(!t){Aa(null);return}(async()=>{try{const Le=t.id||t.requestId;if(!Le){Aa(null);return}const be=await Es(Le),me=(be==null?void 0:be.documents)||[],fe=t.proposalDetails||(be==null?void 0:be.proposalDetails)||{},ue=me.find(we=>we.category==="APPROVAL"||we.type==="proposal"||we.documentCategory==="APPROVAL"),ke=me.filter(we=>we.category==="SUPPORTING"||we.type==="supporting"||we.documentCategory==="SUPPORTING");let De=fe.costBreakup||[];if(typeof De=="string")try{De=JSON.parse(De)}catch(we){console.warn("Failed to parse costBreakup JSON:",we),De=[]}Array.isArray(De)||(De=[]),Aa({proposalDocument:ue?{name:ue.fileName||ue.file_name||ue.name,id:ue.documentId||ue.document_id||ue.id}:void 0,costBreakup:De,expectedCompletionDate:fe.expectedCompletionDate||"",otherDocuments:ke.map(we=>({name:we.fileName||we.file_name||we.name,id:we.documentId||we.document_id||we.id})),dealerComments:fe.dealerComments||"",submittedAt:fe.submittedAt})}catch(Le){console.warn("Failed to load proposal data:",Le);const be=t.proposalDetails||{};let me=be.costBreakup||[];if(typeof me=="string")try{me=JSON.parse(me)}catch(fe){console.warn("Failed to parse costBreakup JSON:",fe),me=[]}Array.isArray(me)||(me=[]),Aa({proposalDocument:void 0,costBreakup:me,expectedCompletionDate:be.expectedCompletionDate||"",otherDocuments:[],dealerComments:be.dealerComments||"",submittedAt:be.submittedAt})}})()},[t]);const[Ya,Ft]=h.useState(null);h.useEffect(()=>{if(!t){Ft(null);return}(async()=>{try{const Le=t.id||t.requestId;if(!Le){Ft(null);return}const be=await Es(Le),me=(be==null?void 0:be.documents)||[],fe=[],ue=[],ke=[];let De=null;me.forEach(we=>{const vt=(we.category||we.documentCategory||we.type||"").toUpperCase(),Ct=(we.fileName||we.file_name||we.name||"").toLowerCase(),Rs={name:we.fileName||we.file_name||we.name,id:we.documentId||we.document_id||we.id,url:we.url||we.storageUrl||we.storage_url};vt==="COMPLETION"||vt==="COMPLETION_DOCUMENT"?fe.push(Rs):vt==="ACTIVITY_PHOTO"||vt==="PHOTO"||vt==="IMAGE"?ue.push(Rs):vt==="ATTENDANCE"||vt==="ATTENDANCE_SHEET"?De=Rs:(vt==="SUPPORTING"||vt==="INVOICE"||vt==="RECEIPT")&&(!De&&(Ct.includes("attendance")||Ct.includes("participant"))?De=Rs:ke.push(Rs))}),fe.length===0&&ue.length===0&&t.completionDetails,Ft({completionDocuments:fe,activityPhotos:ue,invoicesReceipts:ke,attendanceSheet:De})}catch(Le){console.warn("Failed to load completion documents:",Le),Ft(null)}})()},[t]);const La=async()=>{try{X.loading("Retriggering WFM push...",{id:"wfm-retrigger"}),await $5(t.id),X.success("WFM push re-triggered successfully",{id:"wfm-retrigger"}),n?n():window.location.reload()}catch(H){console.error("Error retriggering WFM push:",H),X.error(H.message||"Failed to re-trigger WFM push",{id:"wfm-retrigger"})}},Bs=async()=>{try{const H=t.id||t.requestId;if(!H){X.error("Request ID not found");return}const be=await fetch(`https://reflow-uat.royalenfield.com/api/v1//dealer-claims/${H}/e-invoice/csv`,{headers:{Authorization:`Bearer ${at.getAccessToken()}`}});if(!be.ok)throw new Error("Failed to download CSV");const me=await be.blob(),fe=window.URL.createObjectURL(me),ue=document.createElement("a");ue.href=fe,ue.download=`Invoice_${t.requestNumber||"Export"}.csv`,document.body.appendChild(ue),ue.click(),window.URL.revokeObjectURL(fe),document.body.removeChild(ue),X.success("CSV downloaded successfully")}catch(H){console.error("Error downloading CSV:",H),X.error("Failed to download CSV")}},Or=async()=>{try{const H=t.id||t.requestId;if(!H){X.error("Request ID not found");return}if(!t.invoice&&!t.irn){X.error("Invoice not generated yet");return}V(!0),E(!0);const be=await fetch(`https://reflow-uat.royalenfield.com/api/v1//dealer-claims/${H}/e-invoice/pdf`,{headers:{Authorization:`Bearer ${at.getAccessToken()}`}});if(!be.ok)throw new Error("Failed to fetch invoice PDF");const me=await be.blob(),fe=window.URL.createObjectURL(me);k&&window.URL.revokeObjectURL(k),B(fe)}catch(H){console.error("Failed to preview invoice:",H),X.error("Failed to load invoice preview"),E(!1)}finally{V(!1)}},pr=()=>{E(!1),k&&(window.URL.revokeObjectURL(k),B(null))},$r=()=>{if(k){const H=document.createElement("a");H.href=k,H.download=`Invoice_${t.requestNumber||"Download"}.pdf`,document.body.appendChild(H),H.click(),document.body.removeChild(H),X.success("Invoice PDF downloaded")}},Ka=((xs=t==null?void 0:t.claimDetails)==null?void 0:xs.dealerName)||((Os=t==null?void 0:t.dealerInfo)==null?void 0:Os.name)||"Dealer",gr=((ks=t==null?void 0:t.claimDetails)==null?void 0:ks.dealerGstin)||((Oa=t==null?void 0:t.dealerInfo)==null?void 0:Oa.gstin)||((ja=t==null?void 0:t.dealerInfo)==null?void 0:ja.dealerGSTIN),Qa=((sr=t==null?void 0:t.claimDetails)==null?void 0:sr.activityName)||((pn=t==null?void 0:t.activityInfo)==null?void 0:pn.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(q,{children:[e.jsx(oe,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Ws,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx(ye,{className:"mt-2",children:"Approval process for dealer claim management"})]})})}),e.jsxs(ee,{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(es,{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:Ae.map((H,Le)=>{var Ct,Rs,kt,ya,Fs;const me=(((Ct=H.status)==null?void 0:Ct.toLowerCase())||"")==="in_progress",fe=H.step===le,ue=ne&&me&&fe,ke=H.status==="approved"||H.status==="skipped",De=Y.find(xe=>(xe.step||xe.levelNumber||xe.level_number)===H.step),we=De!=null&&De.levelId?(Rs=t==null?void 0:t.approvals)==null?void 0:Rs.find(xe=>xe.levelId===De.levelId||xe.level_id===De.levelId):null,vt=(we==null?void 0:we.status)==="PAUSED"||((kt=t==null?void 0:t.pauseInfo)==null?void 0:kt.isPaused)&&(((ya=t==null?void 0:t.pauseInfo)==null?void 0:ya.levelId)===(we==null?void 0:we.levelId)||((Fs=t==null?void 0:t.pauseInfo)==null?void 0:Fs.level_id)===(we==null?void 0:we.levelId));return e.jsx("div",{className:`relative p-5 rounded-lg border-2 transition-all ${V5(H.status,ue)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${z5(H.status)}`,children:U5(H.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:H.title}),e.jsx(ae,{className:B5(H.status),children:H.status.toLowerCase()}),H.emailTemplateUrl&&H.status==="approved"&&e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",title:"View email template",onClick:()=>{C({stepNumber:H.step,stepName:H.title}),w(!0)},children:e.jsx(fa,{className:"w-3.5 h-3.5 text-blue-600"})}),H.step===7&&H.einvoiceUrl&&ke&&e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",title:"Download E-Invoice",onClick:()=>window.open(H.einvoiceUrl,"_blank"),children:e.jsx(Rt,{className:"w-3.5 h-3.5 text-green-600"})}),(()=>{const xe=(H.levelName||H.title||"").toLowerCase().includes("requestor claim")||(H.levelName||H.title||"").toLowerCase().includes("requestor - claim"),ft=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&H.status==="approved";return xe&&ft&&e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-amber-100",title:"Preview Invoice",onClick:Or,children:e.jsx(Pt,{className:"w-3.5 h-3.5 text-amber-600"})})})(),(()=>{var Tt,Ue,ws,Bt;const xe=(H.levelName||H.title||"").toLowerCase().includes("requestor claim")||(H.levelName||H.title||"").toLowerCase().includes("requestor - claim"),ft=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&H.status==="approved",zt=((Tt=t==null?void 0:t.invoice)==null?void 0:Tt.wfmPushStatus)||((Ue=t==null?void 0:t.invoice)==null?void 0:Ue.wfmPushStatus),Ns=((ws=t==null?void 0:t.invoice)==null?void 0:ws.wfmPushError)||((Bt=t==null?void 0:t.invoice)==null?void 0:Bt.wfmPushError);return xe&&ft&&e.jsxs("div",{className:"flex items-center gap-1 ml-1",children:[e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-emerald-100",title:"Export CSV",onClick:Bs,children:e.jsx(uh,{className:"w-3.5 h-3.5 text-emerald-600"})}),zt==="SUCCESS"?e.jsx("div",{title:"Pushed to WFM successfully",children:e.jsx(us,{className:"w-3.5 h-3.5 text-green-500"})}):zt==="FAILED"?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{title:`WFM Push Failed: ${Ns||"Unknown error"}`,children:e.jsx(At,{className:"w-3.5 h-3.5 text-red-500"})}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-5 px-1.5 text-[10px] text-red-600 hover:text-red-700 hover:bg-red-50 border border-red-200 h-auto py-0",onClick:La,children:"Retry Push"})]}):e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{title:"WFM Push Pending",children:e.jsx(st,{className:"w-3.5 h-3.5 text-amber-500"})}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-5 px-1.5 text-[10px] text-amber-600 hover:text-amber-700 hover:bg-amber-50 border border-amber-200 h-auto py-0",onClick:La,children:"Push Now"})]})]})})()]}),e.jsx("p",{className:"text-sm text-gray-600",children:H.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:H.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",Kt(H.tatHours)]}),H.elapsedHours&&(ue||ke)&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",Kt(H.elapsedHours)]})]})]}),H.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:H.comment})}),H.versionHistory&&H.versionHistory.all&&H.versionHistory.all.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsxs(M,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs text-amber-700 hover:text-amber-800 hover:bg-amber-50",onClick:()=>{const xe=new Set(F);xe.has(H.step)?xe.delete(H.step):xe.add(H.step),$(xe)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ph,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"font-medium",children:"Version History"}),H.versionHistory.all&&H.versionHistory.all.length>0&&e.jsxs(ae,{className:"bg-amber-100 text-amber-800 text-[10px] px-1.5 py-0",children:[H.versionHistory.all.length," Versions"]})]}),F.has(H.step)?e.jsx(Hi,{className:"w-4 h-4"}):e.jsx(rn,{className:"w-4 h-4"})]}),F.has(H.step)&&H.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:H.versionHistory.all.map((xe,ft)=>{var zt,Ns,Tt,Ue;return e.jsxs("div",{className:`space-y-2 ${ft>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(ae,{className:`${ft===0?"bg-amber-500":"bg-gray-400"} text-white text-[10px] px-2 py-0.5`,children:[ft===0?"Current":"Previous",": v",xe.version]}),e.jsx("span",{className:"text-[10px] text-gray-600 font-medium",children:Br(xe.createdAt)})]})}),e.jsx("p",{className:"text-xs text-gray-700 font-medium",children:xe.changeReason||"Version Update"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${ft===0?"bg-blue-100":"bg-gray-100"} flex items-center justify-center`,children:e.jsx("span",{className:`text-[8px] font-bold ${ft===0?"text-blue-600":"text-gray-600"}`,children:((Ns=(zt=xe.changer)==null?void 0:zt.displayName)==null?void 0:Ns.charAt(0))||"U"})}),e.jsxs("span",{className:"text-[10px] text-gray-600",children:["By ",((Tt=xe.changer)==null?void 0:Tt.displayName)||((Ue=xe.changer)==null?void 0:Ue.email)||"Unknown User"]})]}),xe.snapshotType==="PROPOSAL"&&xe.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(xe.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:xe.snapshotData,type:"PROPOSAL",title:`Proposal (v${xe.version})`}),children:[e.jsx(St,{className:"w-3 h-3"}),"View Details"]})]}),xe.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",xe.snapshotData.comments]})]}),xe.snapshotType==="INTERNAL_ORDER"&&xe.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: ",xe.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Blocked Amount: ₹",Number(xe.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),xe.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-[10px] text-gray-600",children:["SAP Doc: ",xe.snapshotData.sapDocumentNumber]})]}),xe.snapshotType==="COMPLETION"&&xe.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(xe.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:xe.snapshotData,type:"COMPLETION",title:`Completion (v${xe.version})`}),children:[e.jsx(St,{className:"w-3 h-3"}),"View Details"]})]}),xe.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",xe.snapshotData.comments]})]}),xe.snapshotType==="APPROVE"&&xe.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:[xe.snapshotData.action==="APPROVE"?"Approval":"Rejection"," Snapshot:"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["By: ",xe.snapshotData.approverName||xe.snapshotData.approverEmail||"Unknown"]}),xe.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1",children:["Comments: ",xe.snapshotData.comments.substring(0,100),xe.snapshotData.comments.length>100?"...":""]}),xe.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-[10px] text-red-600 mt-1",children:["Rejection Reason: ",xe.snapshotData.rejectionReason.substring(0,100),xe.snapshotData.rejectionReason.length>100?"...":""]})]}),xe.snapshotType==="WORKFLOW"&&xe.snapshotData&&xe.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:[xe.snapshotData.comments.substring(0,100),xe.snapshotData.comments.length>100?"...":""]})]})]},ft)})})]}),ue&&(we==null?void 0:we.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:we.sla.deadline?wa(we.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${vt?"bg-gray-100 border-gray-300":(we.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(we.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(we.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 ",vt&&"(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:we.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:[we.sla.elapsedText||"0 hours"," / ",Kt(H.tatHours)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const xe=we.sla.percentageUsed||0,ft=()=>vt?"bg-gray-500":xe>=100?"bg-red-600":xe>=75?"bg-orange-500":xe>=50?"bg-amber-500":"bg-green-600",zt=()=>vt?"text-gray-600":xe>=100?"text-red-600":xe>=75?"text-orange-600":xe>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(qs,{value:xe,className:"h-3",indicatorClassName:ft()}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`text-xs font-semibold ${zt()}`,children:["Progress: ",Math.min(100,xe),"% of TAT used"]}),e.jsxs("span",{className:"text-xs font-medium text-gray-700",children:[we.sla.remainingText||"0 hours"," remaining"]})]})]})})(),we.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(Di,{className:"w-4 h-4"}),"Deadline Breached"]}),we.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(es,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),(()=>{const xe=H.levelName||H.level_name;return(xe&&xe.toLowerCase().includes("department lead")||H.title&&H.title.toLowerCase().includes("department lead"))&&H.status==="approved"&&H.ioDetails&&H.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(Pt,{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:H.ioDetails.ioNumber})]}),H.ioDetails.blockedAmount!==void 0&&H.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:["₹",H.ioDetails.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),H.ioDetails.remainingBalance!==void 0&&H.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:["₹",H.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 ",H.ioDetails.organizedBy||H.approver||"N/A"," on"," ",H.ioDetails.organizedAt?Br(H.ioDetails.organizedAt):H.approvedAt?Br(H.approvedAt):"N/A"]})]})]})})(),H.step===6&&H.dmsDetails&&H.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($t,{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:H.dmsDetails.dmsNumber})]}),H.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:H.dmsDetails.dmsRemarks})]}),H.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Initiated by ",H.dmsDetails.pushedBy," on"," ",Br(H.dmsDetails.pushedAt)]})]})]}),(()=>{const xe=Y.find(Ue=>(Ue.step||Ue.levelNumber||Ue.level_number)===H.step),ft=((xe==null?void 0:xe.approverEmail)||"").toLowerCase(),zt=ft&&pe===ft,Ns=H.step===1||(xe==null?void 0:xe.levelName)&&xe.levelName.toLowerCase().includes("dealer");return ue&&(zt||Ns&&Fe)})()&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[(()=>{const xe=((De==null?void 0:De.levelName)||H.title||"").toLowerCase();return(H.step===1||xe.includes("proposal")||xe.includes("submission"))&&(Fe||tt)})()&&e.jsxs(M,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{o(!0)},children:[e.jsx(js,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),(()=>{const xe=((De==null?void 0:De.levelName)||H.title||"").toLowerCase();return(xe.includes("requestor evaluation")||xe.includes("confirmation")||H.step===As)&&(a||ce)})()&&e.jsxs(M,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{d(!0)},children:[e.jsx(Oe,{className:"w-4 h-4 mr-2"}),"Review Request"]}),(()=>{const xe=Y.find(Ue=>(Ue.step||Ue.levelNumber||Ue.level_number)===H.step);if(!((xe==null?void 0:xe.levelName)||H.title||"").toLowerCase().includes("initiator action")||!(a||pe===Nt))return null;const Tt=async Ue=>{var ws,Bt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Is=t.requestId||t.id;await mp(Is,Ue,{reason:""}),X.success(`Action "${Ue==="REVISE"?"Revision Requested":"Request Reopened"}" performed successfully`),K()}catch(Is){console.error("Failed to perform initiator action:",Is);const O0=((Bt=(ws=Is==null?void 0:Is.response)==null?void 0:ws.data)==null?void 0:Bt.message)||(Is==null?void 0:Is.message)||"Failed to perform action";X.error(O0)}};return e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(M,{variant:"outline",className:"border-orange-500 text-orange-600 hover:bg-orange-50",onClick:()=>Tt("REVISE"),children:[e.jsx(Ut,{className:"w-4 h-4 mr-2"}),"Request Re-quotation"]}),e.jsxs(M,{variant:"outline",className:"border-blue-500 text-blue-600 hover:bg-blue-50",onClick:()=>Tt("REOPEN"),children:[e.jsx(oh,{className:"w-4 h-4 mr-2"}),"Reopen"]})]})})(),(()=>{const xe=Y.find(Bt=>(Bt.levelName||"").toLowerCase().includes("department lead"));if(!(xe&&H.step===(xe.step||xe.levelNumber||xe.level_number)))return null;const zt=((xe==null?void 0:xe.approverEmail)||"").toLowerCase();if(!(zt&&pe===zt||qe||lt))return null;const Tt=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order),Ue=(Tt==null?void 0:Tt.ioNumber)||(Tt==null?void 0:Tt.io_number)||(t==null?void 0:t.ioNumber)||"",ws=Ue&&Ue.trim()!=="";return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(M,{className:"bg-green-600 hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>{p(!0)},disabled:!ws,children:[e.jsx(Oe,{className:"w-4 h-4 mr-2"}),"Review and Approve"]}),!ws&&e.jsx("p",{className:"text-xs text-amber-600",children:"Please add an IO number in the IO tab before approving this step."})]})})(),(()=>{const xe=Y.find(Ue=>(Ue.step||Ue.levelNumber||Ue.level_number)===H.step),ft=((xe==null?void 0:xe.approverEmail)||"").toLowerCase(),zt=Fe&&ft===ge,Ns=((xe==null?void 0:xe.levelName)||H.title||"").toLowerCase(),Tt=Ns.includes("dealer completion")||Ns.includes("completion documents");return zt&&Tt})()&&e.jsxs(M,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{u(!0)},children:[e.jsx(js,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),(()=>{const xe=Y.find(Tt=>{const Ue=(Tt.levelName||"").toLowerCase();return Ue.includes("requestor claim")||Ue.includes("requestor - claim")});if(!(xe&&H.step===(xe.step||xe.levelNumber||xe.level_number)))return null;const zt=((xe==null?void 0:xe.approverEmail)||"").toLowerCase();return a||zt&&pe===zt?e.jsxs(M,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:()=>{f(!0)},children:[e.jsx($t,{className:"w-4 h-4 mr-2"}),"Generate E-Invoice & Sync"]}):null})(),(()=>{var ws;const xe=((De==null?void 0:De.levelName)||H.title||"").toLowerCase(),ft=xe.includes("credit note")||xe.includes("sap")||H.step===8&&!xe.includes("additional"),zt=((De==null?void 0:De.approverEmail)||"").toLowerCase(),Ns=zt&&pe===zt,Tt=((ws=s==null?void 0:s.role)==null?void 0:ws.toUpperCase())||"";return ft&&(Ns||(Tt==="FINANCE"||Tt==="ADMIN"))})()&&e.jsxs(M,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{j(!0)},children:[e.jsx(Pt,{className:"w-4 h-4 mr-2"}),"View & Send Credit Note"]}),(()=>{const xe=Y.find(Tt=>(Tt.step||Tt.levelNumber||Tt.level_number)===H.step),ft=((xe==null?void 0:xe.levelName)||H.title||"").toLowerCase(),zt=ft.includes("additional approver"),Ns=H.step===1||ft.includes("proposal")||ft.includes("submission")||ft.includes("requestor evaluation")||ft.includes("confirmation")||ft.includes("department lead")||ft.includes("dealer completion")||ft.includes("completion documents")||ft.includes("requestor claim")||ft.includes("requestor - claim")||ft.includes("credit note")||ft.includes("sap");if(zt||!Ns){const Tt=(xe==null?void 0:xe.levelId)||(xe==null?void 0:xe.level_id);if(Tt){const Ue=(xe==null?void 0:xe.levelName)||(xe==null?void 0:xe.level_name)||H.title||"Approval Level",ws=(xe==null?void 0:xe.approverName)||(xe==null?void 0:xe.approver_name)||H.approver||"Approver";return e.jsxs(M,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{R({levelId:Tt,levelName:Ue,approverName:ws}),L(!0)},children:[e.jsx(Oe,{className:"w-4 h-4 mr-2"}),"Review Request"]})}return e.jsxs(e.Fragment,{children:[e.jsxs(M,{className:"bg-green-600 hover:bg-green-700",onClick:async()=>{var Ue,ws;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Bt=t.id||t.requestId;if(!Tt){X.error("Approval level not found");return}await Tn(Bt,Tt,""),X.success("Request approved successfully"),K()}catch(Bt){console.error("Failed to approve:",Bt);const Is=((ws=(Ue=Bt==null?void 0:Bt.response)==null?void 0:Ue.data)==null?void 0:ws.message)||(Bt==null?void 0:Bt.message)||"Failed to approve request. Please try again.";X.error(Is)}},children:[e.jsx(Oe,{className:"w-4 h-4 mr-2"}),"Approve"]}),e.jsxs(M,{variant:"destructive",onClick:async()=>{var Ue,ws;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Bt=t.id||t.requestId;if(!Tt){X.error("Approval level not found");return}const Is=prompt("Please provide a reason for rejection:");if(Is===null)return;await wr(Bt,Tt,"Request rejected",Is),X.success("Request rejected successfully"),K()}catch(Bt){console.error("Failed to reject:",Bt);const Is=((ws=(Ue=Bt==null?void 0:Bt.response)==null?void 0:Ue.data)==null?void 0:ws.message)||(Bt==null?void 0:Bt.message)||"Failed to reject request. Please try again.";X.error(Is)}},children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),"Reject"]})]})}return null})()]}),H.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",Br(H.approvedAt)]})]})]})},Le)})})]})]}),e.jsx(S5,{isOpen:l,onClose:()=>o(!1),onSubmit:ot,dealerName:Ka,dealerGSTIN:gr,activityName:Qa,defaultGstRate:(gn=t==null?void 0:t.claimDetails)==null?void 0:gn.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),previousProposalData:(fn=N==null?void 0:N.find(H=>H.snapshotType==="PROPOSAL"))==null?void 0:fn.snapshotData,documentPolicy:i,taxationType:(Qc=t==null?void 0:t.claimDetails)==null?void 0:Qc.taxationType,totalBlockedAmount:((t==null?void 0:t.internalOrders)||[]).reduce((H,Le)=>H+Number(Le.ioBlockedAmount||Le.io_blocked_amount||Le.blockedAmount||0),0)}),e.jsx(R5,{isOpen:c,onClose:()=>{d(!1)},onApprove:Us,onReject:rs,onRequestRevision:gt,proposalData:Ma,dealerName:Ka,activityName:Qa,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),request:t,previousProposalData:(()=>{const H=(N==null?void 0:N.filter(Le=>Le.snapshotType==="PROPOSAL"))||[];return H.length>1?H[1].snapshotData:null})(),taxationType:(Xc=t==null?void 0:t.claimDetails)==null?void 0:Xc.taxationType}),e.jsx(A5,{isOpen:m,onClose:()=>p(!1),onApprove:Dt,onReject:Sa,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),preFilledIONumber:((Jc=t==null?void 0:t.internalOrder)==null?void 0:Jc.ioNumber)||((Zc=t==null?void 0:t.internalOrder)==null?void 0:Zc.io_number)||((qc=t==null?void 0:t.internal_order)==null?void 0:qc.ioNumber)||((ed=t==null?void 0:t.internal_order)==null?void 0:ed.io_number)||void 0,preFilledBlockedAmount:((td=t==null?void 0:t.internalOrder)==null?void 0:td.ioBlockedAmount)||((sd=t==null?void 0:t.internalOrder)==null?void 0:sd.io_blocked_amount)||((ad=t==null?void 0:t.internal_order)==null?void 0:ad.ioBlockedAmount)||((rd=t==null?void 0:t.internal_order)==null?void 0:rd.io_blocked_amount)||void 0,preFilledRemainingBalance:((nd=t==null?void 0:t.internalOrder)==null?void 0:nd.ioRemainingBalance)||((id=t==null?void 0:t.internalOrder)==null?void 0:id.io_remaining_balance)||((ld=t==null?void 0:t.internal_order)==null?void 0:ld.ioRemainingBalance)||((od=t==null?void 0:t.internal_order)==null?void 0:od.io_remaining_balance)||void 0,taxationType:(cd=t==null?void 0:t.claimDetails)==null?void 0:cd.taxationType}),e.jsx(C5,{isOpen:x,onClose:()=>u(!1),onSubmit:vs,dealerName:Ka,dealerGSTIN:gr,activityName:Qa,defaultGstRate:(dd=t==null?void 0:t.claimDetails)==null?void 0:dd.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),documentPolicy:i,taxationType:(md=t==null?void 0:t.claimDetails)==null?void 0:md.taxationType}),e.jsx(T5,{isOpen:g,onClose:()=>f(!1),onPush:ts,completionDetails:{activityCompletionDate:((ud=t==null?void 0:t.completionDetails)==null?void 0:ud.activityCompletionDate)||((xd=t==null?void 0:t.completionDetails)==null?void 0:xd.activity_completion_date),numberOfParticipants:((hd=t==null?void 0:t.completionDetails)==null?void 0:hd.numberOfParticipants)||((pd=t==null?void 0:t.completionDetails)==null?void 0:pd.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||((gd=t==null?void 0:t.completionDetails)==null?void 0:gd.closedExpenses)||((fd=t==null?void 0:t.completionDetails)==null?void 0:fd.closed_expenses),totalClosedExpenses:((bd=t==null?void 0:t.budgetTracking)==null?void 0:bd.closedExpenses)||((jd=t==null?void 0:t.budgetTracking)==null?void 0:jd.closed_expenses)||((yd=t==null?void 0:t.completionDetails)==null?void 0:yd.totalClosedExpenses)||((vd=t==null?void 0:t.completionDetails)==null?void 0:vd.total_closed_expenses),completionDescription:((Nd=t==null?void 0:t.completionDetails)==null?void 0:Nd.completionDescription)||((wd=t==null?void 0:t.completionDetails)==null?void 0:wd.completion_description)},ioDetails:{ioNumber:((Cd=t==null?void 0:t.internalOrder)==null?void 0:Cd.ioNumber)||((Sd=t==null?void 0:t.internalOrder)==null?void 0:Sd.io_number)||((Ad=t==null?void 0:t.internal_order)==null?void 0:Ad.ioNumber)||((Td=t==null?void 0:t.internal_order)==null?void 0:Td.io_number),blockedAmount:((kd=t==null?void 0:t.internalOrder)==null?void 0:kd.ioBlockedAmount)||((Rd=t==null?void 0:t.internalOrder)==null?void 0:Rd.io_blocked_amount)||((Dd=t==null?void 0:t.internal_order)==null?void 0:Dd.ioBlockedAmount)||((Fd=t==null?void 0:t.internal_order)==null?void 0:Fd.io_blocked_amount),availableBalance:((Id=t==null?void 0:t.internalOrder)==null?void 0:Id.ioAvailableBalance)||((Pd=t==null?void 0:t.internalOrder)==null?void 0:Pd.io_available_balance)||((Ed=t==null?void 0:t.internal_order)==null?void 0:Ed.ioAvailableBalance)||((_d=t==null?void 0:t.internal_order)==null?void 0:_d.io_available_balance),remainingBalance:((Md=t==null?void 0:t.internalOrder)==null?void 0:Md.ioRemainingBalance)||((Ld=t==null?void 0:t.internalOrder)==null?void 0:Ld.io_remaining_balance)||((Od=t==null?void 0:t.internal_order)==null?void 0:Od.ioRemainingBalance)||(($d=t==null?void 0:t.internal_order)==null?void 0:$d.io_remaining_balance)},completionDocuments:Ya,requestTitle:t==null?void 0:t.title,requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.request_number)||(t==null?void 0:t.id),taxationType:(Ud=t==null?void 0:t.claimDetails)==null?void 0:Ud.taxationType,onReQuotation:ct}),e.jsx(b5,{isOpen:b,onClose:()=>j(!1),taxationType:(Bd=t==null?void 0:t.claimDetails)==null?void 0:Bd.taxationType,onDownload:async()=>{X.info("Download functionality will be implemented")},onSendToDealer:async()=>{var H,Le;try{const be=(t==null?void 0:t.requestId)||(t==null?void 0:t.id);if(!be){X.error("Request ID not found");return}await L5(be),X.success("Credit note sent to dealer successfully. Step 8 has been approved."),n&&n()}catch(be){console.error("Failed to send credit note to dealer:",be);const me=((Le=(H=be==null?void 0:be.response)==null?void 0:H.data)==null?void 0:Le.message)||(be==null?void 0:be.message)||"Failed to send credit note to dealer";X.error(me)}},creditNoteData:{creditNoteNumber:((Vd=t==null?void 0:t.creditNote)==null?void 0:Vd.creditNoteNumber)||((zd=t==null?void 0:t.creditNote)==null?void 0:zd.credit_note_number)||((Wd=(Hd=t==null?void 0:t.claimDetails)==null?void 0:Hd.creditNote)==null?void 0:Wd.creditNoteNumber)||((Gd=t==null?void 0:t.claimDetails)==null?void 0:Gd.creditNoteNumber)||((Yd=t==null?void 0:t.claimDetails)==null?void 0:Yd.credit_note_number),creditNoteDate:((Kd=t==null?void 0:t.creditNote)==null?void 0:Kd.creditNoteDate)||((Qd=t==null?void 0:t.creditNote)==null?void 0:Qd.credit_note_date)||((Jd=(Xd=t==null?void 0:t.claimDetails)==null?void 0:Xd.creditNote)==null?void 0:Jd.creditNoteDate)||((Zd=t==null?void 0:t.claimDetails)==null?void 0:Zd.creditNoteDate)||((qd=t==null?void 0:t.claimDetails)==null?void 0:qd.credit_note_date),creditNoteAmount:(em=t==null?void 0:t.creditNote)!=null&&em.creditNoteAmount?Number((tm=t==null?void 0:t.creditNote)==null?void 0:tm.creditNoteAmount):(sm=t==null?void 0:t.creditNote)!=null&&sm.credit_note_amount?Number((am=t==null?void 0:t.creditNote)==null?void 0:am.credit_note_amount):(nm=(rm=t==null?void 0:t.claimDetails)==null?void 0:rm.creditNote)!=null&&nm.creditNoteAmount?Number((lm=(im=t==null?void 0:t.claimDetails)==null?void 0:im.creditNote)==null?void 0:lm.creditNoteAmount):(om=t==null?void 0:t.claimDetails)!=null&&om.creditNoteAmount?Number((cm=t==null?void 0:t.claimDetails)==null?void 0:cm.creditNoteAmount):(dm=t==null?void 0:t.claimDetails)!=null&&dm.credit_note_amount?Number((mm=t==null?void 0:t.claimDetails)==null?void 0:mm.credit_note_amount):void 0,status:((um=t==null?void 0:t.creditNote)==null?void 0:um.status)||((hm=(xm=t==null?void 0:t.claimDetails)==null?void 0:xm.creditNote)==null?void 0:hm.status)||((pm=t==null?void 0:t.creditNote)!=null&&pm.creditNoteNumber?"CONFIRMED":"PENDING")},dealerInfo:{dealerName:((gm=t==null?void 0:t.claimDetails)==null?void 0:gm.dealerName)||((fm=t==null?void 0:t.claimDetails)==null?void 0:fm.dealer_name),dealerCode:((bm=t==null?void 0:t.claimDetails)==null?void 0:bm.dealerCode)||((jm=t==null?void 0:t.claimDetails)==null?void 0:jm.dealer_code),dealerEmail:((ym=t==null?void 0:t.claimDetails)==null?void 0:ym.dealerEmail)||((vm=t==null?void 0:t.claimDetails)==null?void 0:vm.dealer_email)},activityName:((Nm=t==null?void 0:t.claimDetails)==null?void 0:Nm.activityName)||((wm=t==null?void 0:t.claimDetails)==null?void 0:wm.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(k5,{isOpen:y,onClose:()=>{w(!1),C(null)},stepNumber:(v==null?void 0:v.stepNumber)||4,stepName:(v==null?void 0:v.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(f5,{isOpen:A,onClose:()=>{L(!1),R(null)},onApprove:async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=D.levelId;if(!fe){X.error("Approval level not found");return}await Tn(me,fe,H),X.success("Request approved successfully"),K(),L(!1),R(null)}catch(me){console.error("Failed to approve:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to approve request. Please try again.";throw X.error(fe),me}},onReject:async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=D.levelId;if(!fe){X.error("Approval level not found");return}await wr(me,fe,"Request rejected",H),X.success("Request rejected successfully"),K(),L(!1),R(null)}catch(me){console.error("Failed to reject:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to reject request. Please try again.";throw X.error(fe),me}},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(q,{className:"mt-6 border-amber-100 bg-amber-50/30",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(de,{className:"text-sm font-bold flex items-center gap-2 text-amber-900",children:[e.jsx($t,{className:"w-4 h-4"}),"Revision History & Audit Trail"]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>U(!S),className:"text-amber-700 hover:text-amber-800 hover:bg-amber-100",children:S?"Hide History":"View History"})]}),e.jsx(ye,{className:"text-xs text-amber-700",children:"Records of all revisions and actions taken on this request"})]}),S&&e.jsx(ee,{children:e.jsx("div",{className:"space-y-4",children:N.map((H,Le)=>{var be,me,fe,ue;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 ",H.version]}),H.snapshotType&&e.jsx(ae,{className:"bg-blue-100 text-blue-700 text-[9px] px-1.5 py-0",children:H.snapshotType}),H.levelNumber&&e.jsxs(ae,{className:"bg-gray-100 text-gray-600 text-[9px] px-1.5 py-0",children:["Step ",H.levelNumber]})]}),e.jsx("span",{className:"text-[10px] text-amber-600 font-medium bg-amber-100 px-2 py-0.5 rounded-full",children:Br(H.createdAt)})]}),e.jsx("p",{className:"text-xs font-medium text-gray-800",children:H.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:((me=(be=H.changer)==null?void 0:be.displayName)==null?void 0:me.charAt(0))||"U"})}),e.jsxs("span",{className:"text-xs text-gray-500",children:["By ",((fe=H.changer)==null?void 0:fe.displayName)||((ue=H.changer)==null?void 0:ue.email)||"Unknown User"]})]}),H.snapshotType==="PROPOSAL"&&H.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:"}),H.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(M,{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:H.snapshotData,type:"PROPOSAL",title:`Historical Proposal (Version ${H.version})`}),children:["View Details",e.jsx(St,{className:"w-2 h-2"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Budget: ₹",Number(H.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),H.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",H.snapshotData.comments.substring(0,80),H.snapshotData.comments.length>80?"...":""]})]}),H.snapshotType==="COMPLETION"&&H.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:"}),H.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(M,{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:H.snapshotData,type:"COMPLETION",title:`Historical Completion (Version ${H.version})`}),children:["View Details",e.jsx(St,{className:"w-3 h-3"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Total Expenses: ₹",Number(H.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),H.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",H.snapshotData.comments.substring(0,80),H.snapshotData.comments.length>80?"...":""]})]}),H.snapshotType==="INTERNAL_ORDER"&&H.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: ",H.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-gray-600",children:["Blocked: ₹",Number(H.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),H.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-gray-600",children:["SAP Doc: ",H.snapshotData.sapDocumentNumber]})]}),H.snapshotType==="APPROVE"&&H.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:[H.snapshotData.action==="APPROVE"?"Approval":"Rejection",":"]}),e.jsxs("p",{className:"text-gray-600",children:["By: ",H.snapshotData.approverName||H.snapshotData.approverEmail||"Unknown"]}),H.snapshotData.levelName&&e.jsxs("p",{className:"text-gray-600",children:["Level: ",H.snapshotData.levelName]}),H.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",H.snapshotData.comments.substring(0,80),H.snapshotData.comments.length>80?"...":""]}),H.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-red-600 mt-1",children:["Rejection Reason: ",H.snapshotData.rejectionReason.substring(0,80),H.snapshotData.rejectionReason.length>80?"...":""]})]}),H.snapshotType==="WORKFLOW"&&H.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: ",H.snapshotData.status||"N/A"]}),H.snapshotData.currentLevel&&e.jsxs("p",{className:"text-gray-600",children:["Current Level: ",H.snapshotData.currentLevel]})]})]})]},H.historyId||Le)})})})]}),e.jsx(D5,{isOpen:!!P,onClose:()=>T(null),snapshot:P==null?void 0:P.data,type:(P==null?void 0:P.type)||"PROPOSAL",title:P==null?void 0:P.title}),I&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/60",onClick:pr}),e.jsxs("div",{className:"relative w-[95vw] max-w-5xl h-[90vh] bg-white rounded-xl shadow-2xl flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b bg-gray-50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-5 h-5 text-amber-600"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Invoice Preview"}),e.jsx(ae,{className:"bg-amber-100 text-amber-800 text-xs",children:t.requestNumber})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[k&&e.jsxs(M,{variant:"outline",size:"sm",onClick:$r,className:"gap-1.5 text-xs",children:[e.jsx(Rt,{className:"w-3.5 h-3.5"}),"Download"]}),e.jsx(M,{variant:"ghost",size:"icon",onClick:pr,className:"h-8 w-8 hover:bg-gray-200",children:e.jsx(jt,{className:"w-4 h-4"})})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden",children:W?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3",children:[e.jsx(Qe,{className:"w-8 h-8 text-amber-600 animate-spin"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading invoice..."})]}):k?e.jsx("iframe",{src:k,className:"w-full h-full border-0",title:"Invoice PDF Preview"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Failed to load invoice"})})})]})]})]})}function W5({request:t,apiRequest:s,onRefresh:a}){const{user:r}=cs(),n=(s==null?void 0:s.requestId)||(t==null?void 0:t.requestId),i=(s==null?void 0:s.proposalDetails)||{},l=(s==null?void 0:s.claimDetails)||s||{},c=h.useMemo(()=>{const _=(i==null?void 0:i.costBreakup)||(l==null?void 0:l.costBreakup)||[],S=Array.isArray(_)?_:typeof _=="string"?JSON.parse(_):[];return!Array.isArray(S)||S.length===0?Number((l==null?void 0:l.totalProposedTaxableAmount)||(i==null?void 0:i.totalEstimatedBudget)||(i==null?void 0:i.total_estimated_budget)||0):S.reduce((U,F)=>{const $=typeof F=="object"&&F.amount||0,P=typeof F=="object"&&F.quantity||1;return U+Number($)*Number(P)},0)},[i==null?void 0:i.costBreakup,l==null?void 0:l.costBreakup,l==null?void 0:l.totalProposedTaxableAmount,i==null?void 0:i.totalEstimatedBudget]),d=(s==null?void 0:s.budgetTracking)||(t==null?void 0:t.budgetTracking)||{},m=(d==null?void 0:d.budgetStatus)||(d==null?void 0:d.budget_status)||"",p=(s==null?void 0:s.internalOrders)||(s==null?void 0:s.internal_orders)||(t==null?void 0:t.internalOrders)||[],x=m==="PROPOSED"&&p.length>0,[u,g]=h.useState(""),[f,b]=h.useState(!1),[j,y]=h.useState(null),[w,v]=h.useState(""),[C,A]=h.useState([]),[L,D]=h.useState(!1);h.useEffect(()=>{if(p.length>0){const _=p.map(S=>{const U=S.organizer||null,F=(U==null?void 0:U.displayName)||(U==null?void 0:U.display_name)||(U==null?void 0:U.name)||(U!=null&&U.firstName&&(U!=null&&U.lastName)?`${U.firstName} ${U.lastName}`.trim():null)||(U==null?void 0:U.email)||"Unknown User";return{ioNumber:S.ioNumber||S.io_number,blockedAmount:Number(S.ioBlockedAmount||S.io_blocked_amount||0),availableBalance:Number(S.ioAvailableBalance||S.io_available_balance||0),remainingBalance:Number(S.ioRemainingBalance||S.io_remaining_balance||0),blockedDate:S.organizedAt||S.organized_at||new Date().toISOString(),blockedBy:F,sapDocumentNumber:S.sapDocumentNumber||S.sap_document_number||"",status:S.status==="BLOCKED"?"blocked":S.status==="RELEASED"?"released":S.status==="PENDING"?"pending":"blocked"}});A(_),!x&&_.length>0&&g(_[_.length-1].ioNumber)}},[s,t,x,p]);const R=async()=>{var _,S;if(!u.trim()){X.error("Please enter an IO number");return}if(!n){X.error("Request ID not found");return}b(!0);try{const U=await _5(n,u.trim());if(U.isValid&&U.availableBalance>0){y(U.availableBalance);const F=C.reduce((P,T)=>P+T.blockedAmount,0),$=Math.max(0,c-F);$>0?v(String($.toFixed(2))):c>0&&F===0?v(String(c.toFixed(2))):v(String(U.availableBalance.toFixed(2))),X.success(`IO fetched from SAP. Available balance: ₹${U.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`)}else X.error("Invalid IO number or no available balance found"),y(null),v("")}catch(U){console.error("Failed to fetch IO budget:",U);const F=((S=(_=U==null?void 0:U.response)==null?void 0:_.data)==null?void 0:S.message)||(U==null?void 0:U.message)||"Failed to validate IO number or fetch budget from SAP";X.error(F),y(null)}finally{b(!1)}},N=async()=>{var $,P;if(!u.trim()||j===null){X.error("Please fetch IO amount first");return}if(!n){X.error("Request ID not found");return}const _=parseFloat(w);if(!w||isNaN(_)||_<=0){X.error("Please enter a valid amount to block");return}const S=parseFloat(_.toFixed(2));if(S>j){X.error("Amount to block exceeds available IO budget");return}const F=C.reduce((T,k)=>T+k.blockedAmount,0)+S;if(c>0){const T=parseFloat(c.toFixed(2)),k=parseFloat(F.toFixed(2));if(Math.abs(k-T)>.01){X.error(`Total blocked amount (₹${k.toLocaleString("en-IN")}) must be exactly equal to the estimated budget (₹${T.toLocaleString("en-IN")})`);return}}D(!0);try{const T=parseFloat(j.toFixed(2)),k=parseFloat((T-S).toFixed(2)),B={ioNumber:u.trim(),ioAvailableBalance:T,ioBlockedAmount:S,ioRemainingBalance:k};await f0(n,B);const I=await I5(n),E=(I==null?void 0:I.internalOrder)||(I==null?void 0:I.internal_order);if(E){const W=Number(E.ioBlockedAmount||E.io_blocked_amount||S),V=Number(E.ioRemainingBalance||E.io_remaining_balance||0),Y=j-W;Math.abs(W-S)>.01&&console.warn("[IOTab] ⚠️ Amount mismatch! Sent:",S,"Saved:",W),Math.abs(V-Y)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:j,blockedAmount:W,expectedRemaining:Y,backendRemaining:V,difference:V-Y});const Z=r,O=(Z==null?void 0:Z.displayName)||(Z==null?void 0:Z.display_name)||(Z==null?void 0:Z.name)||(Z!=null&&Z.firstName&&(Z!=null&&Z.lastName)?`${Z.firstName} ${Z.lastName}`.trim():null)||(Z==null?void 0:Z.email)||"Current User",z={ioNumber:E.ioNumber||E.io_number||u,blockedAmount:W,availableBalance:j,remainingBalance:V,blockedDate:E.organizedAt||E.organized_at||new Date().toISOString(),blockedBy:O,sapDocumentNumber:E.sapDocumentNumber||E.sap_document_number||"",status:"blocked"};A(K=>[...K,z]),v(""),y(null),X.success("IO budget blocked successfully in SAP"),a==null||a()}else X.error("IO blocked but failed to fetch updated details"),a==null||a()}catch(T){console.error("Failed to block IO budget:",T);const k=((P=($=T==null?void 0:T.response)==null?void 0:$.data)==null?void 0:P.message)||(T==null?void 0:T.message)||"Failed to block IO budget in SAP";X.error(k)}finally{D(!1)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx(ye,{children:"Enter IO number to fetch available budget from SAP"})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(te,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ce,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:u,onChange:_=>g(_.target.value),disabled:f||C.length>0&&!x,className:"flex-1"}),e.jsxs(M,{onClick:R,disabled:!u.trim()||f||C.length>0&&!x,className:"bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Rt,{className:"w-4 h-4 mr-2"}),f?"Fetching...":"Fetch Amount"]})]})]}),!j&&C.length===0&&u.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.']})}),j!==null&&(C.length===0||x)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-green-50 border-2 border-green-200 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600 uppercase tracking-wide mb-1",children:"Available Amount"}),e.jsxs("p",{className:"text-2xl font-bold text-green-700",children:["₹",j.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsx(Oe,{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:"})," ",u]}),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(te,{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(Ce,{type:"number",id:"blockAmount",placeholder:"Enter amount to block",min:"0",step:"0.01",value:w,onChange:_=>v(_.target.value),className:"pl-8"})]}),c>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:["₹",c.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs(M,{onClick:N,disabled:L||!w||parseFloat(w)<=0||parseFloat(w)>j||c>0&&Math.abs(C.reduce((_,S)=>_+S.blockedAmount,0)+parseFloat(w)-c)>.01,className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(qt,{className:"w-4 h-4 mr-2"}),L?"Blocking in SAP...":"Block IO in SAP"]})]})]})]}),e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Oe,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx(ye,{children:"Details of IO blocked in SAP system"})]}),e.jsx(ee,{children:C.length>0?e.jsxs("div",{className:"space-y-6",children:[x&&e.jsx("div",{className:"bg-amber-50 border-2 border-amber-500 rounded-lg p-4 animate-pulse",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ze,{className:"w-6 h-6 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-amber-900",children:"Additional Budget Blocking Required"}),e.jsxs("p",{className:"text-sm text-amber-700 mt-1",children:["Actual expenses exceed the previously blocked amount. Please block an additional ₹",(c-C.reduce((_,S)=>_+S.blockedAmount,0)).toLocaleString("en-IN",{minimumFractionDigits:2}),"."]})]})]})}),C.slice().reverse().map((_,S)=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:`p-3 flex justify-between items-center ${S===0?"bg-green-50":"bg-gray-50"}`,children:[e.jsxs("span",{className:"font-semibold text-sm",children:["IO: ",_.ioNumber]}),e.jsx(ae,{className:_.status==="blocked"?"bg-green-100 text-green-800":_.status==="pending"?"bg-amber-100 text-amber-800":"bg-blue-100 text-blue-800",children:_.status==="blocked"?"Blocked":_.status==="pending"?"Provisioned":"Released"})]}),e.jsxs("div",{className:"grid grid-cols-2 divide-x divide-y",children:[e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Amount"}),e.jsxs("p",{className:"text-sm font-bold text-green-700",children:["₹",_.blockedAmount.toLocaleString("en-IN")]})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"SAP Doc"}),e.jsx("p",{className:"text-sm font-medium",children:_.sapDocumentNumber||"N/A"})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Blocked By"}),e.jsx("p",{className:"text-xs",children:_.blockedBy})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Date"}),e.jsx("p",{className:"text-[10px]",children:new Date(_.blockedDate).toLocaleString()})]})]})]},S)),e.jsxs("div",{className:"mt-4 p-4 bg-[#2d4a3e] text-white rounded-lg flex justify-between items-center",children:[e.jsx("span",{className:"font-bold",children:"Total Blocked:"}),e.jsxs("span",{className:"text-xl font-bold",children:["₹",C.reduce((_,S)=>_+S.blockedAmount,0).toLocaleString("en-IN",{minimumFractionDigits:2})]})]})]}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ha,{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 G5(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)}}async function Y5(t){var s;try{const a=await je.get(`/dealers-external/search/${t}`);return((s=a.data)==null?void 0:s.data)||a.data||null}catch(a){return console.error("[DealerAPI] Error searching external dealer:",a),null}}const Ks=[{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 K5({formData:t,updateFormData:s,onValidationError:a,currentUserEmail:r="",currentUserId:n="",currentUserName:i="",onValidate:l,maxApprovalLevels:o,onPolicyViolation:c}){const{userSearchResults:d,userSearchLoading:m,searchUsersForIndex:p,clearSearchForIndex:x}=Xg(),[u,g]=h.useState(!1),[f,b]=h.useState(""),[j,y]=h.useState(24),[w,v]=h.useState("hours"),[C,A]=h.useState(3),[L,D]=h.useState([]),[R,N]=h.useState(!1),[_,S]=h.useState(null),U=h.useRef(null),F=()=>{const O=t.approvers||[],z=[];return Ks.forEach(K=>{if(K.isAuto||K.approverType==="dealer"||K.approverType==="initiator")return;const re=O.find(G=>G.level===K.level);(!re||!re.email||!re.userId||!re.tat)&&z.push(`${K.name}`)}),{isValid:z.length===0,missingSteps:z}};h.useEffect(()=>{if(l){const O=F();l(O.isValid)}},[t.approvers]),h.useEffect(()=>{const O=t.approvers||[];if(O.length>0){const z=[],K=O.filter(G=>G.isAdditional);Ks.forEach(G=>{const se=O.find(ve=>ve.originalStepLevel===G.level||!ve.originalStepLevel&&!ve.isAdditional&&ve.level===G.level);if(se)z.push(se);else if(G.isAuto){const ve=G.level===8?"finance@royalenfield.com":"system@royalenfield.com",Te=G.level===8?"System/Finance":"System";z.push({email:ve,name:Te,level:G.level,tat:G.defaultTat,tatType:"hours",originalStepLevel:G.level})}else G.approverType==="dealer"?z.push({email:t.dealerEmail||"",name:t.dealerName||"",level:G.level,tat:G.defaultTat,tatType:"hours",originalStepLevel:G.level}):G.approverType==="initiator"?z.push({email:r||"",name:i||r||"User",userId:n,level:G.level,tat:G.defaultTat,tatType:"hours",originalStepLevel:G.level}):z.push({email:"",name:"",level:G.level,tat:G.defaultTat,tatType:"hours",originalStepLevel:G.level})}),K.forEach(G=>{z.push(G)}),z.sort((G,se)=>G.level-se.level),JSON.stringify(O.map(G=>({level:G.level,originalStepLevel:G.originalStepLevel})))!==JSON.stringify(z.map(G=>({level:G.level,originalStepLevel:G.originalStepLevel})))&&s("approvers",z)}else{const z=[];Ks.forEach(K=>{K.isAuto||(K.approverType==="dealer"?z.push({email:t.dealerEmail||"",name:t.dealerName||"",level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level}):K.approverType==="initiator"?z.push({email:r||"",name:i||r||"User",userId:n,level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level}):z.push({email:"",name:"",level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level}))}),s("approvers",z)}},[t.dealerEmail,t.dealerName,r,n,i]);const $=(O,z)=>{const K=[...t.approvers||[]],re=K.findIndex(G=>G.originalStepLevel===O||!G.originalStepLevel&&G.level===O&&!G.isAdditional);if(re===-1){const G=Ks.find(se=>se.level===O);K.push({email:z,name:"",level:O,tat:(G==null?void 0:G.defaultTat)||48,tatType:"hours",originalStepLevel:O})}else{const G=K[re];if(G){const se=G.email;K[re]={...G,email:z,name:z!==se?"":G.name,userId:z!==se?void 0:G.userId}}}if(s("approvers",K),!z||!z.startsWith("@")||z.length<2){x(O-1);return}p(O-1,z,10)},P=async(O,z)=>{var K,re;try{const G=Ks.find(Pe=>Pe.level===O);if(G&&!G.isAuto&&G.approverType!=="initiator"&&((K=z.email)==null?void 0:K.toLowerCase())===(r==null?void 0:r.toLowerCase())){X.error(`You cannot assign yourself as ${G.name} approver.`),a&&a({type:"self-assign",email:z.email,message:`You cannot assign yourself as ${G.name} approver.`});return}if((t.approvers||[]).some(Pe=>{var $e,ne;return Pe.level!==O&&(Pe.userId===z.userId||(($e=Pe.email)==null?void 0:$e.toLowerCase())===((ne=z.email)==null?void 0:ne.toLowerCase()))})){X.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 Te=await ga({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}),Ke=[...t.approvers||[]],Je=Ke.findIndex(Pe=>Pe.originalStepLevel===O||!Pe.originalStepLevel&&Pe.level===O&&!Pe.isAdditional);if(Je===-1){const Pe=Ks.find($e=>$e.level===O);Ke.push({email:z.email,name:z.displayName||[z.firstName,z.lastName].filter(Boolean).join(" "),userId:Te.userId,level:O,tat:(Pe==null?void 0:Pe.defaultTat)||48,tatType:"hours",originalStepLevel:O})}else{const Pe=Ke[Je];Pe&&(Ke[Je]={...Pe,email:z.email,name:z.displayName||[z.firstName,z.lastName].filter(Boolean).join(" "),userId:Te.userId,originalStepLevel:Pe.originalStepLevel||O})}s("approvers",Ke),x(O-1),X.success(`Approver for ${(re=Ks.find(Pe=>Pe.level===O))==null?void 0:re.name} selected successfully.`)}catch(G){console.error("Failed to ensure user exists:",G),X.error("Failed to validate user. Please try again."),a&&a({type:"error",email:z.email,message:"Failed to validate user. Please try again."})}},T=(O,z)=>{const K=[...t.approvers||[]],re=K.findIndex(G=>G.originalStepLevel===O||!G.originalStepLevel&&G.level===O&&!G.isAdditional);if(re!==-1){const G=K[re];G&&(K[re]={...G,tat:z},s("approvers",K))}},k=(O,z)=>{const K=[...t.approvers||[]],re=K.findIndex(G=>G.originalStepLevel===O||!G.originalStepLevel&&G.level===O&&!G.isAdditional);if(re!==-1){const G=K[re];G&&(K[re]={...G,tatType:z,tat:""},s("approvers",K))}},B=O=>{if(b(O),_&&_.email.toLowerCase()!==O.toLowerCase()&&S(null),U.current&&clearTimeout(U.current),!O||!O.startsWith("@")||O.length<2){D([]),N(!1);return}N(!0),U.current=setTimeout(async()=>{var z;try{const K=O.slice(1),G=((z=(await ba(K,10)).data)==null?void 0:z.data)||[];D(G)}catch(K){console.error("Search failed:",K),D([])}finally{N(!1)}},300)},I=async O=>{try{await ga({userId:O.userId,email:O.email,displayName:O.displayName,firstName:O.firstName,lastName:O.lastName,department:O.department,phone:O.phone,mobilePhone:O.mobilePhone,designation:O.designation,jobTitle:O.jobTitle,manager:O.manager,employeeId:O.employeeId,employeeNumber:O.employeeNumber,secondEmail:O.secondEmail,location:O.location}),b(O.email),S(O),D([]),N(!1)}catch(z){console.error("Failed to ensure user exists:",z),X.error("Failed to verify user. Please try again.")}},E=async()=>{var $e,ne;const O=f.trim().toLowerCase();if(!O){X.error("Please enter an email address");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(O)){X.error("Please enter a valid email address");return}const K=typeof j=="string"?Number(j):j;if(!K||K<=0||isNaN(K)){X.error("Please enter valid TAT (minimum 1)");return}const re=w==="days"?30:720;if((w==="days"?K*24:K)>720){X.error(`TAT cannot exceed ${re} ${w==="days"?"days":"hours"}`);return}const se=Ks.find(he=>he.name==="Requestor Claim Approval");if(se&&C>=se.level){X.error('Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.');return}if(O===(r==null?void 0:r.toLowerCase())){X.error("You cannot add yourself as an additional approver.");return}const ve=t.approvers||[];if(ve.some(he=>{var Ne;return he.userId&&(_==null?void 0:_.userId)&&he.userId===_.userId||((Ne=he.email)==null?void 0:Ne.toLowerCase())===O})){X.error("This user is already assigned as an approver.");return}const Ke=ve.find(he=>he.originalStepLevel===C||!he.originalStepLevel&&!he.isAdditional&&he.level===C),Pe=(Ke?Ke.level:C)+1;if(o){const Ne=new Set(ve.map(Ae=>Ae.level)).size+1;if(Ne>o){const Ae=[{type:"max_approval_levels",message:`Adding this approver would create ${Ne} approval levels, which exceeds the maximum allowed (${o}). Please remove some approvers before adding a new one.`,currentValue:Ne,maxValue:o}];c?c(Ae):X.error((($e=Ae[0])==null?void 0:$e.message)||"Maximum approval levels exceeded");return}}if(!_||_.email.toLowerCase()!==O)try{const Ne=((ne=(await ba(O,1)).data)==null?void 0:ne.data)||[];if(Ne.length===0){X.error("User not found in organization directory. Please use @ to search for users.");return}const Ae=Ne[0];await ga({userId:Ae.userId,email:Ae.email,displayName:Ae.displayName,firstName:Ae.firstName,lastName:Ae.lastName,department:Ae.department,phone:Ae.phone,mobilePhone:Ae.mobilePhone,designation:Ae.designation,jobTitle:Ae.jobTitle,manager:Ae.manager,employeeId:Ae.employeeId,employeeNumber:Ae.employeeNumber,secondEmail:Ae.secondEmail,location:Ae.location});const Q={email:Ae.email,name:Ae.displayName||[Ae.firstName,Ae.lastName].filter(Boolean).join(" "),userId:Ae.userId,level:Pe,tat:typeof j=="string"?Number(j):j,tatType:w,isAdditional:!0,insertAfterLevel:C,stepName:`Additional Approver - ${Ae.displayName||Ae.email}`},le=ve.map(pe=>pe.level>=Pe?{...pe,level:pe.level+1}:pe);le.push(Q),le.sort((pe,ge)=>pe.level-ge.level),s("approvers",le),X.success("Additional approver added and subsequent steps shifted")}catch(he){console.error("Failed to validate approver:",he),X.error("Failed to validate user. Please try again.");return}else{const he={email:_.email,name:_.displayName||[_.firstName,_.lastName].filter(Boolean).join(" "),userId:_.userId,level:Pe,tat:j,tatType:w,isAdditional:!0,insertAfterLevel:C,stepName:`Additional Approver - ${_.displayName||_.email}`},Ne=ve.map(Ae=>Ae.level>=Pe?{...Ae,level:Ae.level+1}:Ae);Ne.push(he),Ne.sort((Ae,Q)=>Ae.level-Q.level),s("approvers",Ne),X.success("Additional approver added and subsequent steps shifted")}b(""),y(24),v("hours"),A(3),S(null),D([]),g(!1)},W=O=>{const z=[...t.approvers||[]];if(!z.find(se=>se.level===O))return;const G=z.filter(se=>se.level!==O).map(se=>se.level>O&&!se.isAdditional?{...se,level:se.level-1}:se);G.sort((se,ve)=>se.level-ve.level),s("approvers",G),X.success("Additional approver removed and subsequent steps shifted back")},V=()=>[...t.approvers||[]].sort((z,K)=>z.level-K.level),Y=t.approvers||[],Z=V();return e.jsxs(Ht.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(Jt,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Approver Selection"}),e.jsx("p",{className:"text-gray-600",children:"Assign approvers for workflow steps with TAT (Turn Around Time)"})]}),e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(q,{className:"border-2 border-blue-200 bg-blue-50",children:e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-blue-900",children:[e.jsx(_r,{className:"w-5 h-5"}),"Workflow Steps Information"]}),e.jsxs(ye,{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 O=t.approvers||[],K=new Set(O.map(re=>re.level)).size;return K>0?e.jsxs("span",{children:[" (",K,"/",o,")"]}):null})()]})]})]})}),e.jsxs(q,{className:"border-2",children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-5 h-5"}),"Approval Hierarchy"]}),e.jsx(ye,{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(ee,{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 O=t.approvers||[],K=new Set(O.map(re=>re.level)).size;return K>0?e.jsxs("span",{children:[" (",K,"/",o,")"]}):null})()]}),e.jsxs(M,{type:"button",variant:"outline",onClick:()=>g(!0),className:"flex items-center gap-2",children:[e.jsx(bs,{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(ae,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-xs text-blue-700",children:"Creates and submits the request"})]})]})}),(()=>{const O=Z.filter(K=>K.isAdditional&&K.insertAfterLevel===0);let z=O.length;return Ks.filter(K=>!K.isAuto).map((K,re,G)=>{const se=Y.find($e=>$e.originalStepLevel===K.level||!$e.originalStepLevel&&$e.level===K.level&&!$e.isAdditional)||{email:"",name:"",level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level},ve=re===G.length-1,Te=K.isAuto||K.approverType==="dealer"||K.approverType==="initiator",Ke=!K.isAuto,Je=Z.filter($e=>$e.isAdditional&&$e.insertAfterLevel===K.level).sort(($e,ne)=>$e.level-ne.level),Pe=z+1;return z++,z+=Je.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"})}),re===0&&O.map(($e,ne)=>{const he=ne+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:he})}),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(ae,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",onClick:()=>W($e.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(jt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:$e.name||$e.email}),e.jsxs("div",{className:"text-xs text-gray-500",children:[e.jsxs("div",{children:["Email: ",$e.email]}),e.jsxs("div",{children:["TAT: ",$e.tat," ",$e.tatType]})]})]})]})})]},`additional-${$e.level}`)}),e.jsx("div",{className:`p-3 rounded-lg border-2 transition-all ${se.email&&se.userId?"border-green-200 bg-green-50":Te?"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 ${se.email&&se.userId?"bg-green-600":Te?"bg-blue-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold text-sm",children:Pe})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-sm",children:K.name}),ve&&e.jsx(ae,{variant:"destructive",className:"text-xs",children:"FINAL"}),Te&&e.jsx(ae,{variant:"outline",className:"text-xs",children:"PRE-FILLED"})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:K.description}),Ke&&(()=>{var he,Ne;const $e=!!(se.email&&se.userId),ne=!se.email&&!Te;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(te,{htmlFor:`approver-${K.level}`,className:`text-xs font-bold ${ne?"text-blue-900":$e?"text-green-900":"text-gray-900"}`,children:["Approver Email ",!Te&&"*",ne&&e.jsx("span",{className:"ml-2 text-[10px] font-semibold italic text-blue-600",children:"(Required)"})]}),$e&&e.jsxs(ae,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Oe,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ce,{id:`approver-${K.level}`,type:"text",placeholder:Te?se.email:"@username or email...",value:se.email||"",onChange:Ae=>{const Q=Ae.target.value;Te||$(K.level,Q)},disabled:Te||K.isAuto,className:`h-9 border-2 transition-all mt-1 w-full text-sm ${Te?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":$e?"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"}`}),!Te&&!K.isAuto&&(m[K.level-1]||(((he=d[K.level-1])==null?void 0:he.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:m[K.level-1]?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:(Ne=d[K.level-1])==null?void 0:Ne.map(Ae=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>P(K.level,Ae),children:[e.jsx("div",{className:"font-medium text-gray-900",children:Ae.displayName||Ae.email}),e.jsx("div",{className:"text-xs text-gray-600",children:Ae.email}),Ae.department&&e.jsx("div",{className:"text-xs text-gray-500",children:Ae.department})]},Ae.userId))})})]}),se.name&&e.jsxs("p",{className:"text-xs text-green-600 mt-1",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:se.name})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:`tat-${K.level}`,className:`text-xs font-bold ${ne?"text-blue-900":$e?"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(Ce,{id:`tat-${K.level}`,type:"number",placeholder:se.tatType==="days"?"7":"24",min:"1",max:se.tatType==="days"?"30":"720",value:se.tat||"",onChange:Ae=>T(K.level,parseInt(Ae.target.value)||""),disabled:K.isAuto,className:`h-9 border-2 transition-all flex-1 text-sm ${Te?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":$e?"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(He,{value:se.tatType||"hours",onValueChange:Ae=>k(K.level,Ae),disabled:K.isAuto,children:[e.jsx(Ge,{className:`w-20 h-9 border-2 transition-all text-sm ${Te?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed":$e?"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(We,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"hours",children:"Hours"}),e.jsx(J,{value:"days",children:"Days"})]})]})]})]})]})})()]})]})}),Je.map(($e,ne)=>{const he=Pe+ne+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:he})}),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:$e.stepName||"Additional Approver"}),e.jsx(ae,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),$e.email&&$e.userId&&e.jsxs(ae,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Oe,{className:"w-3 h-3 mr-1"}),"Verified"]}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",onClick:()=>W($e.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(jt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:$e.name||$e.email||"No approver assigned"}),$e.email&&e.jsxs("div",{className:"text-xs text-gray-500 space-y-1",children:[e.jsxs("div",{children:["Email: ",$e.email]}),$e.tat&&e.jsxs("div",{children:["TAT: ",$e.tat," ",$e.tatType]})]})]})]})})]},`additional-${$e.level}`)})]},K.level)})})()]})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(st,{className:"w-5 h-5"}),"TAT Summary"]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3",children:Z.map(O=>{const z=O.originalStepLevel?Ks.find(se=>se.level===O.originalStepLevel):Ks.find(se=>se.level===O.level&&!O.isAdditional);if(z!=null&&z.isAuto)return null;const K=Number(O.tat||0),G=(O.tatType||"hours")==="days"?K*24:K;if(!K)return null;if(O.isAdditional){const se=Ks.find(ve=>ve.level===O.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:O.stepName||`Additional Approver (after "${(se==null?void 0:se.name)||"Unknown"}")`}),e.jsxs("span",{className:"text-sm text-gray-600",children:[G," hours"]})]},O.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:[G," hours"]})]},O.level)})})})]})]}),e.jsx(ht,{open:u,onOpenChange:g,children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(bs,{className:"w-5 h-5 text-blue-600"}),"Add Additional Approver"]}),e.jsx(_t,{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(te,{className:"text-sm font-medium",children:"Insert After Step *"}),e.jsxs(He,{value:C.toString(),onValueChange:O=>A(Number(O)),children:[e.jsx(Ge,{className:"h-11 border-gray-300",children:e.jsx(We,{placeholder:"Select step"})}),e.jsx(Ye,{children:Ks.filter(O=>{if(O.isAuto)return!1;const z=Ks.find(K=>K.name==="Requestor Claim Approval");return!(z&&O.level>=z.level)}).map(O=>e.jsx(J,{value:O.level.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:O.name})]})},O.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 O=t.approvers||[],K=new Set(O.map(re=>re.level)).size;return K>0?e.jsxs("span",{children:[" (",K,"/",o,")"]}):null})()]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ce,{type:"number",min:"1",max:w==="days"?"30":"720",value:j,onChange:O=>{const z=O.target.value;if(z==="")y("");else{const K=Number(z);!isNaN(K)&&K>=0&&y(K)}},onBlur:O=>{const z=O.target.value;(!z||z===""||Number(z)<=0)&&y(24)},className:"h-11 border-gray-300 flex-1",placeholder:"24"}),e.jsxs(He,{value:w,onValueChange:O=>v(O),children:[e.jsx(Ge,{className:"w-24 h-11 border-gray-300",children:e.jsx(We,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"hours",children:"Hours"}),e.jsx(J,{value:"days",children:"Days"})]})]})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Maximum time for this approver to respond (1-",w==="days"?"30 days":"720 hours",")"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-sm font-medium",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Xi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ce,{type:"text",placeholder:"@username or user@example.com",value:f,onChange:O=>B(O.target.value),className:"pl-10 h-11 border-gray-300",autoFocus:!0}),(R||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 max-h-60 overflow-auto",children:R?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):L.length>0?e.jsx("ul",{className:"divide-y",children:L.map(O=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>I(O),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:O.displayName||[O.firstName,O.lastName].filter(Boolean).join(" ")||O.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:O.email}),O.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:O.designation})]})})},O.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(Et,{children:[e.jsx(M,{type:"button",variant:"outline",onClick:()=>{g(!1),b(""),y(24),v("hours"),A(3),S(null),D([])},className:"flex-1",children:"Cancel"}),e.jsxs(M,{type:"button",onClick:E,className:"flex-1 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:!f.trim()||!j,children:[e.jsx(bs,{className:"w-4 h-4 mr-2"}),"Add Approver"]})]})]})})]})}const Gl=[{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"}],Yl=["Claim Details","Approver Selection","Review & Submit"];function Q5({onBack:t,onSubmit:s}){const{user:a}=cs(),[r,n]=h.useState(1),[i,l]=h.useState(!1),[o,c]=h.useState([]),[d,m]=h.useState(!1),[p,x]=h.useState(""),u=h.useRef(null),[g,f]=h.useState(!1),b=h.useRef(null),[j,y]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[w,v]=h.useState({open:!1,violations:[]}),[C,A]=h.useState([]),[L,D]=h.useState(!0);h.useEffect(()=>{(async()=>{try{D(!0);const E=await LA();A(E)}catch(E){console.error("Failed to load activity types:",E),X.error("Failed to load activity types. Please refresh the page.")}finally{D(!1)}})()},[]),h.useEffect(()=>{(async()=>{var E;try{const W=await la("SYSTEM_SETTINGS"),V=await la("WORKFLOW_SHARING"),Y=[...W,...V],Z={};Y.forEach(O=>{Z[O.configKey]=O.configValue}),y({maxApprovalLevels:parseInt(Z.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(Z.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((E=Z.ALLOW_ADD_SPECTATOR)==null?void 0:E.toLowerCase())==="true",maxSpectators:parseInt(Z.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(W){console.error("Failed to load system policy:",W)}})()},[]),h.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const[R,N]=h.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:"",approvers:[]}),_=Yl.length,S=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 E=await Y5(I);if(E){const W={dealerId:E.dealer||E.dealer_code||I,dealerCode:E.dealer||E.dealer_code||I,dealerName:E["dealer name"]||E.dealer_name||"Unknown Dealer",displayName:E["dealer name"]||E.dealer_name||"Unknown Dealer",email:E["dealer email"]||"",phone:E["dealer phone"]||"",city:E["re city"]||E.city||"",state:E["re state code"]||E.state||"",isLoggedIn:!0};c([W])}else c([])}catch(E){console.error("Error searching external dealer:",E),c([])}finally{m(!1)}},300)},U=(I,E)=>{N(W=>{const V={...W,[I]:E};if(I==="periodStartDate")E&&V.periodEndDate&&E>V.periodEndDate&&(V.periodEndDate=void 0,X.error("End date must be on or after the start date. End date has been cleared."));else if(I==="periodEndDate"&&E&&V.periodStartDate&&E{switch(r){case 1:return R.activityName&&R.activityType&&R.dealerCode&&R.dealerName&&R.activityDate&&R.location&&R.requestDescription;case 2:const E=(R.approvers||[]).find(W=>W.originalStepLevel===3||!W.originalStepLevel&&W.level===3&&!W.isAdditional);return(E==null?void 0:E.email)&&(E==null?void 0:E.userId)&&(E==null?void 0:E.tat);case 3:return!0;default:return!1}},$=()=>{if(r<_){if(!F()){if(r===2){const E=(R.approvers||[]).find(V=>V.originalStepLevel===3||!V.originalStepLevel&&V.level===3&&!V.isAdditional),W=[];(!(E!=null&&E.email)||!(E!=null&&E.userId)||!(E!=null&&E.tat))&&W.push("Department Lead Approval"),W.length>0?X.error(`Please add missing approvers: ${W.join(", ")}`):X.error("Please complete all required approver selections (email, user verification, and TAT) before proceeding.")}else X.error("Please complete all required fields before proceeding.");return}n(r+1)}},P=()=>{r>1&&n(r-1)},T=async I=>{l(!0);try{const E=await G5(I.dealerCode);if(!E.isLoggedIn){X.error(`Dealer "${E.dealerName||E.displayName}" (${E.dealerCode}) is not mapped to the system.`,{duration:5e3}),x(""),c([]),U("dealerCode",""),U("dealerName",""),U("dealerEmail",""),U("dealerPhone",""),U("dealerAddress",""),l(!1);return}U("dealerCode",E.dealerCode),U("dealerName",E.dealerName||E.displayName),U("dealerEmail",E.email||""),U("dealerPhone",E.phone||""),U("dealerAddress",""),x(E.dealerName||E.displayName),c([]),X.success(`Dealer "${E.dealerName||E.displayName}" verified and mapped to the System`)}catch{X.error("Dealer is not mapped to the system",{duration:5e3}),x(""),c([]),U("dealerCode",""),U("dealerName",""),U("dealerEmail",""),U("dealerPhone",""),U("dealerAddress","")}finally{l(!1)}},k=()=>{if(g)return;const E=[...R.approvers||[]].sort((O,z)=>O.level-z.level),W=new Map,V=[];if(E.forEach(O=>{W.has(O.level)?V.push(O.level):W.set(O.level,O)}),V.length>0){X.error(`Duplicate approver levels detected: ${V.join(", ")}. Please refresh and try again.`),console.error("Duplicate levels found:",V,E);return}const Y=E.map(O=>{const z={email:O.email,name:O.name,userId:O.userId,level:O.level,tat:O.tat,tatType:O.tatType};return O.isAdditional&&O.stepName&&(z.stepName=O.stepName,z.isAdditional=!0),O.originalStepLevel&&(z.originalStepLevel=O.originalStepLevel),z}),Z={...R,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",approvers:Y};if(f(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{f(!1),b.current=null},3e4),s)try{s(Z)}catch(O){b.current&&(clearTimeout(b.current),b.current=null),f(!1),console.error("Error submitting claim:",O)}else b.current&&(clearTimeout(b.current),b.current=null),f(!1)},B=()=>{switch(r){case 1:return e.jsxs(Ht.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(Pt,{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(te,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(Ce,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:R.activityName,onChange:I=>U("activityName",I.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(He,{value:R.activityType,onValueChange:I=>U("activityType",I),disabled:L,children:[e.jsx(Ge,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(We,{placeholder:L?"Loading activity types...":"Select activity type"})}),e.jsx(Ye,{children:C.length>0?C.map(I=>e.jsx(J,{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(te,{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(Ce,{placeholder:"Type dealer code, name, or email to search...",value:R.dealerCode?`${R.dealerName} (${R.dealerCode})`:p,onChange:I=>{R.dealerCode?(U("dealerCode",""),U("dealerName",""),U("dealerEmail",""),U("dealerPhone",""),U("dealerAddress",""),x(I.target.value)):S(I.target.value)},onFocus:()=>{p&&p.length>=2&&S(p)},className:"h-12 border-2 border-gray-300 focus:border-blue-500",disabled:i}),R.dealerCode&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsxs(ae,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Oe,{className:"w-3 h-3 mr-1"}),"Verified"]})}),(d||o.length>0)&&!R.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(Oe,{className:"w-4 h-4 text-green-600"}):e.jsx(At,{className:"w-4 h-4 text-red-500"})})]})},I.dealerId))})})]})}),R.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:R.dealerName})," (",R.dealerCode,")"]}),R.dealerEmail&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Email: ",R.dealerEmail]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(M,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(dt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:R.activityDate?et(R.activityDate,"d MMM yyyy"):"Select date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(gi,{mode:"single",selected:R.activityDate,onSelect:I=>U("activityDate",I),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(Ce,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:R.location,onChange:I=>U("location",I.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(te,{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(Xn,{value:R.requestDescription||"",onChange:I=>U("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(te,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(ae,{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(te,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(M,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(dt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:R.periodStartDate?et(R.periodStartDate,"d MMM yyyy"):"Start date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(gi,{mode:"single",selected:R.periodStartDate,onSelect:I=>U("periodStartDate",I),initialFocus:!0,toDate:R.periodEndDate||void 0})})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(M,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",disabled:!R.periodStartDate,children:[e.jsx(dt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:R.periodEndDate?et(R.periodEndDate,"d MMM yyyy"):"End date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(gi,{mode:"single",selected:R.periodEndDate,onSelect:I=>U("periodEndDate",I),initialFocus:!0,fromDate:R.periodStartDate||void 0})})]}),!R.periodStartDate&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Please select start date first"})]})]}),(R.periodStartDate||R.periodEndDate)&&e.jsx("div",{className:"mt-2",children:R.periodStartDate&&R.periodEndDate?e.jsxs("p",{className:"text-xs text-gray-600",children:["Period: ",et(R.periodStartDate,"d MMM yyyy")," - ",et(R.periodEndDate,"d MMM yyyy")]}):e.jsx("p",{className:"text-xs text-gray-500",children:R.periodStartDate?"Please select end date for the period":"Please select start date first"})})]})]})]});case 2:return e.jsx(K5,{formData:R,updateFormData:U,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:j.maxApprovalLevels,onPolicyViolation:I=>v({open:!0,violations:I})});case 3:return e.jsxs(Ht.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(Oe,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Review & Submit"}),e.jsx("p",{className:"text-gray-600",children:"Review your claim details before submission"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.activityName})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(ae,{variant:"secondary",className:"mt-1",children:R.activityType})]})]})})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Ji,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{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:R.dealerCode})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.dealerName})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:R.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:R.dealerPhone})]}),R.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:R.dealerAddress})]})]})})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-purple-50 to-indigo-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Jt,{className:"w-5 h-5 text-purple-600"}),"Selected Approvers"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsx("div",{className:"space-y-3",children:[...R.approvers||[]].filter(E=>{var W,V;return!((W=E.email)!=null&&W.includes("system@"))&&!((V=E.email)!=null&&V.includes("finance@"))}).sort((E,W)=>E.level-W.level).map(E=>{const W=Number(E.tat||0),Y=(E.tatType||"hours")==="days"?W*24:W;let Z="Unknown",O="";if(E.isAdditional){Z=E.stepName||"Additional Approver";const z=Gl.find(K=>K.level===E.insertAfterLevel);O=E.stepName||`Additional Approver (after "${(z==null?void 0:z.name)||"Unknown"}")`}else{const z=E.originalStepLevel?Gl.find(K=>K.level===E.originalStepLevel):Gl.find(K=>K.level===E.level&&!K.isAuto);Z=(z==null?void 0:z.name)||"Unknown",O=Z}return e.jsx("div",{className:`p-3 rounded-lg border ${E.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(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:O}),E.isAdditional&&e.jsx(ae,{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:E.name||E.email||"Not selected"}),E.email&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:E.email})]}),e.jsxs("div",{className:"text-right ml-4",children:[e.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:[Y," hours"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"TAT"})]})]})},`${E.level}-${E.email}`)})})})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.activityDate?et(R.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(te,{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(zo,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:R.location})]})]}),R.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(te,{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:R.estimatedBudget})]})]})})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(te,{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(_s,{content:R.requestDescription||"",className:"text-sm"})})]})})]}),(R.periodStartDate||R.periodEndDate)&&e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(st,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.periodStartDate?et(R.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.periodEndDate?et(R.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(_r,{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(M,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(Cs,{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(ae,{variant:"secondary",className:"mb-2 text-xs",children:"Claim Management Template"}),e.jsx("h1",{className:"text-xl sm:text-2xl lg:text-3xl font-bold text-gray-900",children:"New Claim Request"}),e.jsxs("p",{className:"text-sm sm:text-base text-gray-600 mt-1",children:["Step ",r," of ",_,": ",e.jsx("span",{className:"hidden sm:inline",children:Yl[r-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(qs,{value:r/_*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:Yl.map((I,E)=>e.jsx("span",{className:`text-xs sm:text-sm ${E+1<=r?"text-blue-600 font-medium":"text-gray-400"}`,children:E+1},E))})]})]}),e.jsx(q,{className:"mb-6 sm:mb-8",children:e.jsx(ee,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(ll,{mode:"wait",children:B()})})}),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(M,{variant:"outline",onClick:P,disabled:r===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Previous"]}),r<_?e.jsxs(M,{onClick:$,className:`gap-2 w-full sm:w-auto order-1 sm:order-2 ${F()?"":"opacity-50 cursor-pointer hover:opacity-60"}`,children:["Next",e.jsx(fs,{className:"w-4 h-4"})]}):e.jsx(M,{onClick:k,disabled:!F()||g,className:"gap-2 bg-green-600 hover:bg-green-700 w-full sm:w-auto order-1 sm:order-2",children:g?e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"w-4 h-4 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(za,{className:"w-4 h-4"}),"Submit Claim Request"]})})]})]}),e.jsx(ti,{open:w.open,onClose:()=>v({open:!1,violations:[]}),violations:w.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}const{DocumentsTab:X5,ActivityTab:J5,WorkNotesTab:Z5,SummaryTab:q5,RequestDetailHeader:ek,QuickActionsSidebar:tk,RequestDetailModals:sk}=d0;let ak=class extends h.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(es,{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(M,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(M,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function rk({requestId:t,onBack:s,dynamicRequests:a=[]}){var Za,qa,er,tr,Gt,Ts;const n=_a().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=h.useState(l),[d,m]=h.useState(!1),[p,x]=h.useState(null),[u,g]=h.useState(null),[f,b]=h.useState(!1),[j,y]=h.useState(0),[w,v]=h.useState(!1),[C,A]=h.useState(!1),[L,D]=h.useState(!1),[R,N]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[_,S]=h.useState({open:!1,violations:[]}),{user:U}=cs(),{request:F,apiRequest:$,loading:P,refreshing:T,refreshDetails:k,currentApprovalLevel:B,isSpectator:I,isInitiator:E,existingParticipants:W,accessDenied:V}=Vc(n,a,U),Y=(U==null?void 0:U.userId)||"",Z=(U==null?void 0:U.jobTitle)==="Dealer"||(U==null?void 0:U.designation)==="Dealer",z=((F==null?void 0:F.workflowType)==="CLAIM_MANAGEMENT"||($==null?void 0:$.workflowType)==="CLAIM_MANAGEMENT"||(F==null?void 0:F.templateType)==="claim-management")&&!Z,{mergedMessages:K,unreadWorkNotes:re,workNoteAttachments:G,setWorkNoteAttachments:se}=Jg(n,$,o,U),{uploadingDocument:ve,triggerFileInput:Te,previewDocument:Ke,setPreviewDocument:Je,documentPolicy:Pe,documentError:$e,setDocumentError:ne}=Zg($,k),[he,Ne]=h.useState(null),Ae=he||B,{showApproveModal:Q,setShowApproveModal:le,showRejectModal:pe,setShowRejectModal:ge,showAddApproverModal:Fe,setShowAddApproverModal:_e,showAddSpectatorModal:Xe,setShowAddSpectatorModal:lt,showSkipApproverModal:Nt,setShowSkipApproverModal:wt,showActionStatusModal:As,setShowActionStatusModal:ie,skipApproverData:Re,setSkipApproverData:ce,actionStatus:Ve,setActionStatus:Be,handleApproveConfirm:tt,handleRejectConfirm:ze,handleAddApprover:rt,handleSkipApprover:qe,handleAddSpectator:ot}=e0(n,Ae,k),Us=async yt=>{await tt(yt),Ne(null)},rs=async yt=>{await ze(yt),Ne(null)},gt=((F==null?void 0:F.status)||($==null?void 0:$.status)||"").toLowerCase(),ct=(gt==="approved"||gt==="rejected")&&E,{conclusionRemark:Dt,setConclusionRemark:vs,conclusionLoading:ts,conclusionSubmitting:Sa,aiGenerated:Ma,handleGenerateConclusion:Aa,handleFinalizeConclusion:Ya,generationAttempts:Ft,generationFailed:La,maxAttemptsReached:Bs}=qg(F,n,E,k,s,Be,ie);h.useEffect(()=>{(async()=>{var xs;try{const Os=await la("SYSTEM_SETTINGS"),ks=await la("WORKFLOW_SHARING"),Oa=[...Os,...ks],ja={};Oa.forEach(sr=>{ja[sr.configKey]=sr.configValue}),N({maxApprovalLevels:parseInt(ja.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(ja.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((xs=ja.ALLOW_ADD_SPECTATOR)==null?void 0:xs.toLowerCase())==="true",maxSpectators:parseInt(ja.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(Os){console.error("Failed to load system policy:",Os)}})()},[]),h.useEffect(()=>{const xs=new URLSearchParams(window.location.search).get("tab");xs&&c(xs)},[n]);const Or=()=>{k()},pr=()=>{v(!0)},$r=()=>{A(!0)},Ka=async()=>{await k()},gr=()=>{D(!0)},Qa=async()=>{await k()},fr=async()=>{await k()},Xa=async()=>{if(!($!=null&&$.requestId)){X.error("Request ID not found");return}if(!p){X.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},Ta=(F==null?void 0:F.status)==="closed";h.useEffect(()=>{(async()=>{if(!Ta||!($!=null&&$.requestId)){g(null),x(null);return}try{b(!0);const xs=await i0($.requestId);if(xs!=null&&xs.summaryId){x(xs.summaryId);try{const Os=await Hc(xs.summaryId);g(Os)}catch(Os){console.error("Failed to fetch summary details:",Os),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{b(!1)}})()},[Ta,$==null?void 0:$.requestId]),h.useEffect(()=>{if(!Y||!($!=null&&$.requestId))return;const yt=en();if(!yt)return;Gh(yt,Y);const xs=Os=>{var sr,pn,gn,fn;const ks=Os==null?void 0:Os.notification;if(!ks)return;const Oa=ks.requestId||ks.request_id,ja=((sr=ks.metadata)==null?void 0:sr.requestNumber)||((pn=ks.metadata)==null?void 0:pn.request_number);Oa!==$.requestId&&ja!==n&&ja!==$.requestNumber||((gn=ks.metadata)!=null&&gn.creditNoteNumber||(fn=ks.metadata)!=null&&fn.credit_note_number)&&k()};return yt.on("notification:new",xs),()=>{yt.off("notification:new",xs)}},[Y,$==null?void 0:$.requestId,n,k]);const Ja=((F==null?void 0:F.approvalFlow)||[]).filter(yt=>yt&&typeof yt.step=="number").map(yt=>({levelNumber:yt.step||0,approverName:yt.approver||"Unknown",status:yt.status||"pending",tatHours:yt.tatHours||24}));return P&&!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(Ut,{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..."})]})}):V!=null&&V.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(xh,{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:V.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(M,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(M,{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(ek,{request:F,refreshing:T,onBack:s||(()=>window.history.back()),onRefresh:Or,onShareSummary:Xa,isInitiator:E,slaData:((Za=F==null?void 0:F.summary)==null?void 0:Za.sla)||(F==null?void 0:F.sla)||null,isPaused:((qa=F==null?void 0:F.pauseInfo)==null?void 0:qa.isPaused)||!1}),e.jsxs(si,{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(ai,{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(Lt,{value:"overview",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-overview",children:[e.jsx(hh,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),Ta&&u&&e.jsxs(Lt,{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(Ho,{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(Lt,{value:"workflow",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-workflow",children:[e.jsx(Ws,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),z&&e.jsxs(Lt,{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(Ha,{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(Lt,{value:"documents",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-documents",children:[e.jsx(Ie,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Docs"})]}),e.jsxs(Lt,{value:"activity",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 col-span-1 sm:col-span-1","data-testid":"tab-activity",children:[e.jsx($t,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Activity"})]}),e.jsxs(Lt,{value:"worknotes",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 relative col-span-2 sm:col-span-1","data-testid":"tab-worknotes",children:[e.jsx(Hs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),re>0&&e.jsx(ae,{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:re>9?"9+":re})]})]})}),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(Ot,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(g5,{request:F,apiRequest:$,currentUserId:Y,isInitiator:E,needsClosure:ct,conclusionRemark:Dt,setConclusionRemark:vs,conclusionLoading:ts,conclusionSubmitting:Sa,aiGenerated:Ma,handleGenerateConclusion:Aa,handleFinalizeConclusion:Ya,generationAttempts:Ft,generationFailed:La,maxAttemptsReached:Bs})}),Ta&&e.jsx(Ot,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(q5,{summary:u,loading:f,onShare:Xa,isInitiator:E})}),e.jsx(Ot,{value:"workflow",className:"mt-0",children:e.jsx(H5,{request:F,user:U,isInitiator:E,onSkipApprover:yt=>{if(!yt.levelId){alert("Level ID not available");return}ce(yt),wt(!0)},onRefresh:k,documentPolicy:Pe})}),z&&e.jsx(Ot,{value:"io",className:"mt-0",children:e.jsx(W5,{request:F,apiRequest:$,onRefresh:k})}),e.jsx(Ot,{value:"documents",className:"mt-0",children:e.jsx(X5,{request:F,workNoteAttachments:G,uploadingDocument:ve,documentPolicy:Pe,triggerFileInput:Te,setPreviewDocument:Je,downloadDocument:Ls})}),e.jsx(Ot,{value:"activity",className:"mt-0",children:e.jsx(J5,{request:F})}),e.jsx(Ot,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(Z5,{requestId:n,requestTitle:F.title,mergedMessages:K,setWorkNoteAttachments:se,isInitiator:E,isSpectator:I,currentLevels:Ja,onAddApprover:rt,maxApprovalLevels:R.maxApprovalLevels,onPolicyViolation:yt=>S({open:!0,violations:yt})})})]}),o!=="worknotes"&&e.jsx(tk,{request:F,isInitiator:E,isSpectator:I,currentApprovalLevel:B,onAddApprover:()=>_e(!0),onAddSpectator:()=>lt(!0),onApprove:()=>le(!0),onReject:()=>ge(!0),onPause:pr,onResume:$r,onRetrigger:gr,summaryId:p,refreshTrigger:j,pausedByUserId:(tr=(er=F==null?void 0:F.pauseInfo)==null?void 0:er.pausedBy)==null?void 0:tr.userId,currentUserId:Y,apiRequest:$,hideApproveReject:Z})]})]})]})}),d&&p&&e.jsx(m0,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(F==null?void 0:F.title)||"N/A",onSuccess:()=>{k(),y(yt=>yt+1)}}),w&&($==null?void 0:$.requestId)&&e.jsx(u0,{isOpen:w,onClose:()=>v(!1),requestId:$.requestId,levelId:(B==null?void 0:B.levelId)||null,onSuccess:Qa}),C&&($==null?void 0:$.requestId)&&e.jsx(x0,{isOpen:C,onClose:()=>A(!1),requestId:$.requestId,onSuccess:Ka}),L&&($==null?void 0:$.requestId)&&e.jsx(h0,{isOpen:L,onClose:()=>D(!1),requestId:$.requestId,approverName:(Ts=(Gt=F==null?void 0:F.pauseInfo)==null?void 0:Gt.pausedBy)==null?void 0:Ts.name,onSuccess:fr}),e.jsx(sk,{showApproveModal:Q,showRejectModal:pe,showAddApproverModal:Fe,showAddSpectatorModal:Xe,showSkipApproverModal:Nt,showActionStatusModal:As,previewDocument:Ke,documentError:$e,request:F,skipApproverData:Re,actionStatus:Ve,existingParticipants:W,currentLevels:Ja,maxApprovalLevels:R.maxApprovalLevels,onPolicyViolation:yt=>S({open:!0,violations:yt}),setShowApproveModal:le,setShowRejectModal:ge,setShowAddApproverModal:_e,setShowAddSpectatorModal:lt,setShowSkipApproverModal:wt,setShowActionStatusModal:ie,setPreviewDocument:Je,setDocumentError:ne,setSkipApproverData:ce,setActionStatus:Be,handleApproveConfirm:Us,handleRejectConfirm:rs,handleAddApprover:rt,handleAddSpectator:ot,handleSkipApprover:qe,downloadDocument:Ls,documentPolicy:Pe}),e.jsx(ti,{open:_.open,onClose:()=>S({open:!1,violations:[]}),violations:_.violations,policyDetails:{maxApprovalLevels:R.maxApprovalLevels,maxParticipants:R.maxParticipants,allowSpectators:R.allowSpectators,maxSpectators:R.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(Ie,{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(M,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(M,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function nk(t){return e.jsx(ak,{children:e.jsx(rk,{...t})})}function ik({onNavigate:t,onNewRequest:s}){const[a,r]=h.useState(!0),[n,i]=h.useState(!1),[l,o]=h.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]=h.useState([]),[m,p]=h.useState("all"),[x,u]=h.useState(),[g,f]=h.useState(),b=async(S=!1)=>{try{S?i(!0):r(!0);const U=await O5(m||"all",x,g);o(U.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(U.categoryData||[])}catch(U){console.error("[DealerDashboard] Error fetching data:",U),X.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)}};h.useEffect(()=>{b()},[]);const j=(S,U=!1)=>{if(S==null||isNaN(S))return"₹0";const F=typeof S=="string"?parseFloat(S):Number(S);return F<=0?"₹0":U||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")}`},y=S=>S.toLocaleString("en-IN"),w=()=>l.totalClaims===0?0:(l.approved/l.totalClaims*100).toFixed(1),v=()=>l.approved===0?0:(l.credited/l.approved*100).toFixed(1),C=h.useMemo(()=>{const S=c.reduce((U,F)=>U+F.raised,0);return S===0?[]:c.map(U=>({name:U.activityType.length>20?U.activityType.substring(0,20)+"...":U.activityType,value:U.raised,fullName:U.activityType,percentage:(U.raised/S*100).toFixed(0)}))},[c]),A=h.useMemo(()=>c.map(S=>({name:S.activityType.length>15?S.activityType.substring(0,15)+"...":S.activityType,fullName:S.activityType,Raised:S.raised,Approved:S.approved,Rejected:S.rejected,Pending:S.pending})),[c]),L=h.useMemo(()=>c.map(S=>({name:S.activityType.length>15?S.activityType.substring(0,15)+"...":S.activityType,fullName:S.activityType,Raised:S.raisedValue,Approved:S.approvedValue,Credited:S.creditedValue})),[c]),D=["#166534","#15803d","#16a34a","#22c55e","#4ade80","#86efac","#bbf7d0"],R=h.useMemo(()=>c.length===0?null:c.reduce((S,U)=>U.approvalRate>((S==null?void 0:S.approvalRate)||0)?U:S),[c]),N=h.useMemo(()=>c.length===0?null:c.reduce((S,U)=>U.raisedValue>((S==null?void 0:S.raisedValue)||0)?U:S),[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(Ut,{className:"w-8 h-8 animate-spin text-blue-600"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading dashboard..."})]})}):l.totalClaims===0&&c.length===0?e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(q,{className:"border-0 shadow-xl relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(ee,{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(ps,{className:"w-8 h-8 text-slate-900"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-4xl text-white font-bold",children:"Claims Analytics Dashboard"}),e.jsx("p",{className:"text-xl text-gray-200 mt-1",children:"Comprehensive insights into approval workflows"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-4 mt-8",children:e.jsxs(M,{onClick:()=>{i(!0),b(!0)},disabled:n,variant:"outline",className:"bg-white/10 hover:bg-white/20 text-white border-white/20",children:[e.jsx(Ut,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh"]})})]})})})]}),e.jsx(q,{className:"shadow-lg",children:e.jsxs(ee,{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(ro,{className:"w-12 h-12 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-2",children:"No Claims Data Available"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md mb-6",children:"You don't have any claims data yet. Once you create and submit claim requests, your analytics will appear here."}),e.jsx("div",{className:"flex flex-col sm:flex-row gap-4",children:e.jsxs(M,{onClick:()=>{i(!0),b(!0)},disabled:n,variant:"outline",children:[e.jsx(Ut,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh Data"]})})]})})]}):e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(q,{className:"border-0 shadow-xl relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(ee,{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(ps,{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(M,{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(M,{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(Ie,{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(Ii,{className:"w-8 h-8 text-yellow-400"})})})})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6 gap-4",children:[e.jsxs(q,{className:"border-l-4 border-l-blue-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Raised Claims"}),e.jsx("div",{className:"p-2 rounded-lg bg-blue-50",children:e.jsx(Ie,{className:"h-4 w-4 text-blue-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.totalClaims)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:j(l.totalValue,!0)})]})]}),e.jsxs(q,{className:"border-l-4 border-l-green-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Approved"}),e.jsx("div",{className:"p-2 rounded-lg bg-green-50",children:e.jsx(Oe,{className:"h-4 w-4 text-green-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.approved)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Ws,{className:"h-3 w-3 text-green-600"}),e.jsxs("p",{className:"text-xs text-green-600",children:[w(),"% approval rate"]})]})]})]}),e.jsxs(q,{className:"border-l-4 border-l-red-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Rejected"}),e.jsx("div",{className:"p-2 rounded-lg bg-red-50",children:e.jsx(At,{className:"h-4 w-4 text-red-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.rejected)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Tb,{className:"h-3 w-3 text-red-600"}),e.jsxs("p",{className:"text-xs text-red-600",children:[l.totalClaims>0?(l.rejected/l.totalClaims*100).toFixed(1):0,"% rejection rate"]})]})]})]}),e.jsxs(q,{className:"border-l-4 border-l-orange-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{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(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.pending)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:j(l.pendingValue)})]})]}),e.jsxs(q,{className:"border-l-4 border-l-emerald-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Credited"}),e.jsx("div",{className:"p-2 rounded-lg bg-emerald-50",children:e.jsx(kb,{className:"h-4 w-4 text-emerald-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.credited)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Ws,{className:"h-3 w-3 text-emerald-600"}),e.jsxs("p",{className:"text-xs text-emerald-600",children:[v(),"% credit rate"]})]})]})]}),e.jsxs(q,{className:"border-l-4 border-l-amber-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Pending Credit"}),e.jsx("div",{className:"p-2 rounded-lg bg-amber-50",children:e.jsx(es,{className:"h-4 w-4 text-amber-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.pendingCredit)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:j(l.pendingCreditValue)})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(q,{className:"shadow-lg",children:[e.jsx(oe,{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(ro,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(de,{children:"Claims Distribution by Activity Type"}),e.jsx(ye,{children:"Total claims raised across activity types"})]})]})}),e.jsxs(ee,{children:[e.jsx(Qr,{width:"100%",height:300,children:e.jsxs(Qx,{children:[e.jsx(Xx,{data:C,cx:"50%",cy:"50%",labelLine:!1,label:({name:S,percentage:U})=>`${S}: ${U}%`,outerRadius:80,fill:"#8884d8",dataKey:"value",children:C.map((S,U)=>e.jsx(Jx,{fill:D[U%D.length]},`cell-${U}`))}),e.jsx(Xr,{})]})}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mt-4",children:C.slice(0,3).map((S,U)=>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[U%D.length]}}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600",children:S.name}),e.jsx("p",{className:"text-sm text-gray-900",children:y(S.value)})]})]},U))})]})]}),e.jsxs(q,{className:"shadow-lg",children:[e.jsx(oe,{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(Ii,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{children:"Claims Status by Activity Type"}),e.jsx(ye,{children:"Count comparison across workflow stages"})]})]})}),e.jsx(ee,{children:e.jsx(Qr,{width:"100%",height:300,children:e.jsxs(to,{data:A,children:[e.jsx(Si,{strokeDasharray:"3 3"}),e.jsx(Ai,{dataKey:"name"}),e.jsx(Ti,{}),e.jsx(Xr,{}),e.jsx(ki,{}),e.jsx(ka,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(ka,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(ka,{dataKey:"Rejected",fill:"#ef4444"}),e.jsx(ka,{dataKey:"Pending",fill:"#f59e0b"})]})})})]})]}),e.jsxs(q,{className:"shadow-lg",children:[e.jsx(oe,{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($t,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(de,{children:"Detailed Activity Type Breakdown"}),e.jsx(ye,{children:"In-depth analysis of claims by type and status"})]})]})}),e.jsx(ee,{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(Qr,{width:"100%",height:350,children:e.jsxs(to,{data:L,children:[e.jsx(Si,{strokeDasharray:"3 3"}),e.jsx(Ai,{dataKey:"name"}),e.jsx(Ti,{tickFormatter:S=>j(S)}),e.jsx(Xr,{formatter:S=>j(S),labelFormatter:S=>S}),e.jsx(ki,{}),e.jsx(ka,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(ka,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(ka,{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((S,U)=>e.jsxs(q,{className:"shadow-md hover:shadow-lg transition-shadow",children:[e.jsx(oe,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-base",children:S.activityType}),e.jsxs(ae,{className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:[S.approvalRate.toFixed(1),"% approved"]})]})}),e.jsxs(ee,{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:[y(S.raised)," (",j(S.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:[y(S.approved)," (",j(S.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:[y(S.rejected)," (",j(S.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:[y(S.pending)," (",j(S.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:[y(S.credited)," (",j(S.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:[y(S.pendingCredit)," (",j(S.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:[S.creditRate.toFixed(1),"%"]})]}),e.jsx(qs,{value:S.creditRate,className:"h-2"})]})]})]},U))})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(q,{className:"border-t-4 border-t-green-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{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(qt,{className:"h-6 w-6 text-green-600"})}),e.jsx(Ws,{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:(R==null?void 0:R.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-green-600",children:[(R==null?void 0:R.approvalRate.toFixed(2))||0,"% approval rate"]})]})}),e.jsx(q,{className:"border-t-4 border-t-blue-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{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(Ha,{className:"h-6 w-6 text-blue-600"})}),e.jsx($t,{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?j(N.raisedValue,!0):"₹0"," raised"]})]})}),e.jsx(q,{className:"border-t-4 border-t-emerald-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{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(Gi,{className:"h-6 w-6 text-emerald-600"})}),e.jsx(Oe,{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:[v(),"%"]}),e.jsxs("p",{className:"text-sm text-emerald-600",children:[y(l.credited)," claims credited"]})]})}),e.jsx(q,{className:"border-t-4 border-t-amber-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{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(lh,{className:"h-6 w-6 text-amber-600"})}),e.jsx(es,{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:y(l.pendingCredit)}),e.jsxs("p",{className:"text-sm text-amber-600",children:[j(l.pendingCreditValue)," awaiting credit"]})]})})]})]})}function lk({searchTerm:t,sortBy:s,sortOrder:a,onSearchChange:r,onSortByChange:n,onSortOrderChange:i,onClearFilters:l,activeFiltersCount:o,...c}){return e.jsxs(q,{className:"shadow-lg border-0",children:[e.jsx(oe,{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(Pa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ye,{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(M,{variant:"ghost",size:"sm",onClick:l,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(jt,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(ee,{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(Ss,{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(Ce,{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(He,{value:s,onValueChange:d=>n(d),children:[e.jsx(Ge,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(We,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"due",children:"Due Date"}),e.jsx(J,{value:"created",children:"Date Created"}),e.jsx(J,{value:"priority",children:"Priority"}),e.jsx(J,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(M,{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(Zi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(qi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function ok({searchTerm:t,statusFilter:s="all",sortBy:a,sortOrder:r,onSearchChange:n,onStatusChange:i,onSortByChange:l,onSortOrderChange:o,onClearFilters:c,activeFiltersCount:d,...m}){return e.jsxs(q,{className:"shadow-lg border-0","data-testid":"dealer-closed-requests-filters",children:[e.jsx(oe,{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(Pa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ye,{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(M,{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(jt,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(ee,{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(Ss,{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(Ce,{placeholder:"Search requests, IDs...",value:t,onChange:p=>n(p.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors","data-testid":"dealer-closed-requests-search"})]}),i&&e.jsxs(He,{value:s,onValueChange:i,children:[e.jsx(Ge,{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(We,{placeholder:"Closure Type"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Closures"}),e.jsx(J,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(J,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:a,onValueChange:p=>l(p),children:[e.jsx(Ge,{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(We,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"due",children:"Due Date"}),e.jsx(J,{value:"created",children:"Date Created"}),e.jsx(J,{value:"priority",children:"Priority"})]})]}),e.jsx(M,{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(Zi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(qi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function ck({searchTerm:t,statusFilter:s,initiatorFilter:a,approverFilter:r,approverFilterType:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,initiatorSearch:d,approverSearch:m,onSearchChange:p,onStatusChange:x,onInitiatorChange:u,onApproverChange:g,onApproverTypeChange:f,onDateRangeChange:b,onCustomStartDateChange:j,onCustomEndDateChange:y,onShowCustomDatePickerChange:w,onApplyCustomDate:v,onClearFilters:C,hasActiveFilters:A,...L}){return e.jsx(q,{className:"border-gray-200 shadow-md","data-testid":"dealer-user-all-requests-filters",children:e.jsx(ee,{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(Pa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),A&&e.jsx(ae,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),A&&e.jsxs(M,{variant:"ghost",size:"sm",onClick:C,className:"gap-2",children:[e.jsx(Ut,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Qt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Ss,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ce,{placeholder:"Search requests...",value:t,onChange:D=>p(D.target.value),className:"pl-10 h-10","data-testid":"dealer-search-input"})]}),e.jsxs(He,{value:s,onValueChange:x,children:[e.jsx(Ge,{className:"h-10","data-testid":"dealer-status-filter",children:e.jsx(We,{placeholder:"All Status"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"pending",children:"Pending"}),e.jsx(J,{value:"paused",children:"Paused"}),e.jsx(J,{value:"approved",children:"Approved"}),e.jsx(J,{value:"rejected",children:"Rejected"}),e.jsx(J,{value:"closed",children:"Closed"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(te,{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(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:d.handleClear,children:e.jsx(jt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{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(te,{className:"text-sm font-medium text-gray-700",children:"Approver"}),r!=="all"&&f&&e.jsxs(He,{value:n,onValueChange:D=>f(D),children:[e.jsx(Ge,{className:"h-7 w-32 text-xs",children:e.jsx(We,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"current",children:"Current Only"}),e.jsx(J,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:m.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:m.selectedUser.displayName||m.selectedUser.email}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:m.handleClear,children:e.jsx(jt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{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(dt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:i,onValueChange:D=>b(D),children:[e.jsx(Ge,{className:"w-[160px] h-10",children:e.jsx(We,{placeholder:"Date Range"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Time"}),e.jsx(J,{value:"today",children:"Today"}),e.jsx(J,{value:"week",children:"This Week"}),e.jsx(J,{value:"month",children:"This Month"}),e.jsx(J,{value:"last7days",children:"Last 7 Days"}),e.jsx(J,{value:"last30days",children:"Last 30 Days"}),e.jsx(J,{value:"custom",children:"Custom Range"})]})]}),i==="custom"&&e.jsxs(ra,{open:c,onOpenChange:w,children:[e.jsx(na,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(dt,{className:"w-4 h-4"}),l&&o?`${et(l,"MMM d, yyyy")} - ${et(o,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Js,{value:l||null,onChange:D=>{const R=D?new Date(D):void 0;R?(j==null||j(R),o&&R>o&&(y==null||y(R))):j==null||j(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"end-date",children:"End Date"}),e.jsx(Js,{value:o||null,onChange:D=>{const R=D?new Date(D):void 0;R?(y==null||y(R),l&&R{w==null||w(!1),j==null||j(void 0),y==null||y(void 0),b("month")},children:"Cancel"})]})]})})]})]})]})})})}function dk(t){switch(t){case"DEALER_CLAIM":return nk;case"CUSTOM":default:return o5}}function mk(t){switch(t){case"DEALER":return lk;case"STANDARD":default:return m5}}function uk(t){switch(t){case"DEALER":return ok;case"STANDARD":default:return h5}}function xk(t){switch(t){case"DEALER":return ck;case"STANDARD":default:return p5}}const hk=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ca,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:qt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:qt,iconColor:"text-gray-600"}}},pk=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:At,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Oe,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 gk({onViewRequest:t}){const[s,a]=h.useState([]),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState(1),[d,m]=h.useState(0),[p]=h.useState(10),x=h.useRef(null),u=jw(),g=h.useMemo(()=>{try{const R=at.getUserData();return lc(R)}catch(R){return console.error("[OpenRequests] Error getting user filter type:",R),"STANDARD"}},[]),f=h.useMemo(()=>mk(g),[g]),b=g==="DEALER",j=R=>{const N={search:u.searchTerm||void 0,status:R&&!b&&u.statusFilter!=="all"?u.statusFilter:void 0,priority:!b&&u.priorityFilter!=="all"?u.priorityFilter:void 0,templateType:u.templateTypeFilter!=="all"?u.templateTypeFilter:void 0,sortBy:u.sortBy,sortOrder:u.sortOrder};return N.templateType==="FORM_16"&&(u.form16FinancialYear&&(N.financialYear=u.form16FinancialYear),u.form16Quarter&&(N.quarter=u.form16Quarter)),N},y=h.useCallback(async(R=1,N)=>{try{R===1&&(n(!0),a([]));const _=await Gs.listOpenForMe({page:R,limit:p,search:N==null?void 0:N.search,status:N==null?void 0:N.status,priority:N==null?void 0:N.priority,templateType:N==null?void 0:N.templateType,financialYear:N==null?void 0:N.financialYear,quarter:N==null?void 0:N.quarter,sortBy:N==null?void 0:N.sortBy,sortOrder:N==null?void 0:N.sortOrder}),S=Array.isArray(_==null?void 0:_.data)?_.data:[],U=_==null?void 0:_.pagination;U&&(u.setCurrentPage(U.page||1),c(U.totalPages||1),m(U.total||0));const F=S.map($=>{var T,k,B,I;const P=$.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)||((k=$.initiator)==null?void 0:k.email)||"—",avatar:(((B=$.initiator)==null?void 0:B.displayName)||((I=$.initiator)==null?void 0:I.email)||"NA").split(" ").map(E=>E[0]).join("").slice(0,2).toUpperCase()},currentApprover:$.currentApprover?{name:$.currentApprover.name||$.currentApprover.email||"—",avatar:($.currentApprover.name||$.currentApprover.email||"CA").split(" ").map(E=>E[0]).join("").slice(0,2).toUpperCase(),sla:$.currentApprover.sla}:void 0,createdAt:P||"—",approvalStep:$.currentLevel?`Step ${$.currentLevel} of ${$.totalLevels||"?"}`:void 0,department:$.department,currentLevelSLA:$.currentLevelSLA,templateType:$.templateType||$.template_type,form16Submission:$.form16Submission??null}});a(F)}finally{n(!1),l(!1)}},[p,u]);x.current=y;const w=h.useCallback(()=>{l(!0),y(u.currentPage,j(!0))},[u.currentPage,y]),v=h.useCallback(R=>{R>=1&&R<=o&&(u.setCurrentPage(R),y(R,j(!0)))},[o,u,y]),C=()=>{const R=[];let _=Math.max(1,u.currentPage-Math.floor(2.5)),S=Math.min(o,_+5-1);S-_<4&&(_=Math.max(1,S-5+1));for(let U=_;U<=S;U++)R.push(U);return R},A=h.useRef(!1);h.useEffect(()=>{if(!A.current){A.current=!0;const R=u.currentPage||1;y(R,j(!0))}},[]);const L=h.useRef({searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,isDealer:b});h.useEffect(()=>{if(!A.current)return;const R=L.current;if(!(R.searchTerm!==u.searchTerm||R.statusFilter!==u.statusFilter||R.priorityFilter!==u.priorityFilter||R.templateTypeFilter!==u.templateTypeFilter||R.sortBy!==u.sortBy||R.sortOrder!==u.sortOrder||R.isDealer!==b))return;const _=setTimeout(()=>{u.setCurrentPage(1),y(1,j(!0)),L.current={searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,isDealer:b}},u.searchTerm?500:0);return()=>clearTimeout(_)},[u.searchTerm,u.statusFilter,u.priorityFilter,u.templateTypeFilter,u.form16FinancialYear,u.form16Quarter,u.sortBy,u.sortOrder,b]);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(Ie,{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(ae,{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(M,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:w,disabled:i,children:[e.jsx(Ut,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:i?"Refreshing...":"Refresh"})]})]})]}),e.jsx(f,{searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,form16FinancialYear:u.form16FinancialYear,form16Quarter:u.form16Quarter,sortBy:u.sortBy,sortOrder:u.sortOrder,onSearchChange:u.setSearchTerm,onStatusFilterChange:u.setStatusFilter,onPriorityFilterChange:u.setPriorityFilter,onTemplateTypeFilterChange:u.setTemplateTypeFilter,onForm16FinancialYearChange:u.setForm16FinancialYear,onForm16QuarterChange:u.setForm16Quarter,onSortByChange:u.setSortBy,onSortOrderChange:u.setSortOrder,onClearFilters:u.clearFilters,activeFiltersCount:u.activeFiltersCount}),e.jsx("div",{className:"space-y-3",children:D.map(R=>{const N=hk(R.priority),_=(R.templateType||R.template_type||"").toString().toUpperCase()==="FORM_16",S=R.form16Submission,U=S==null?void 0:S.displayStatus,F=U&&/balance mismatch|failed/i.test(String(U)),$=_&&U?{color:F?"bg-red-100 text-red-800 border-red-200":U==="Completed"?"bg-green-100 text-green-800 border-green-200":"bg-gray-100 text-gray-700 border-gray-200",icon:Ze,label:U}:pk(R.status);return e.jsx(q,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>t==null?void 0:t(R.id,R.title),children:e.jsx(ee,{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:R.displayId||R.id}),e.jsxs(ae,{variant:"outline",className:`${$.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx($.icon,{className:"w-3.5 h-3.5 mr-1"}),$.label||R.status]}),R.department&&e.jsx(ae,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:R.department}),e.jsx(ae,{variant:"outline",className:`${N.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:R.priority}),(()=>{const P=(R==null?void 0:R.templateType)||(R==null?void 0:R.template_type)||"",T=(P==null?void 0:P.toUpperCase())||"";let k="Non-Templatized",B="bg-purple-100 !text-purple-600 border-purple-200";return T==="DEALER CLAIM"?(k="Dealer Claim",B="bg-blue-100 !text-blue-700 border-blue-200"):T==="FORM_16"?(k="Form 16",B="bg-emerald-100 !text-emerald-700 border-emerald-200"):T==="TEMPLATE"&&(k="Template"),e.jsx(ae,{variant:"outline",className:`${B} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:k})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:R.title}),(R.templateType||"").toString().toUpperCase()==="FORM_16"&&R.form16Submission&&e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-600 mt-1",children:[R.form16Submission.dealerCode&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Dealer:"})," ",R.form16Submission.dealerCode]}),R.form16Submission.form16aNumber&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Form 16A:"})," ",R.form16Submission.form16aNumber]}),R.form16Submission.financialYear&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"FY:"})," ",R.form16Submission.financialYear]}),R.form16Submission.quarter&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Q:"})," ",R.form16Submission.quarter]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Total amount:"})," ",R.form16Submission.totalAmount!=null?new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(R.form16Submission.totalAmount):"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Credit note:"})," ",R.form16Submission.creditNoteNumber||"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Status:"})," ",R.form16Submission.displayStatus||R.form16Submission.status||"—"]})]}),R.currentLevelSLA&&(()=>{var I;const P=!!(R.isPaused||(I=R.pauseInfo)!=null&&I.isPaused||R.status==="paused"),T=R.currentLevelSLA.percentageUsed||0,B=P?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:T>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:T>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:T>=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 ${B.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:[P?e.jsx(ir,{className:`w-3.5 h-3.5 ${B.icon}`}):e.jsx(st,{className:`w-3.5 h-3.5 ${B.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",T,"% ",P&&"(paused)"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:R.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${B.text}`,children:[R.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(qs,{value:T,className:"h-1.5",indicatorClassName:B.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(ls,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(os,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:R.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:R.initiator.name})]}),R.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ls,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(os,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:R.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:R.currentApprover.name})]}),R.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:R.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(dt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",R.createdAt!=="—"?wa(R.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(fs,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},R.id)})}),D.length===0&&e.jsx(q,{className:"shadow-lg border-0",children:e.jsxs(ee,{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(Ie,{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(M,{variant:"outline",className:"mt-4",onClick:u.clearFilters,children:"Clear all filters"})]})}),o>1&&!r&&e.jsx(q,{className:"shadow-md",children:e.jsx(ee,{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)*p+1," to ",Math.min(u.currentPage*p,d)," of ",d," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>v(u.currentPage-1),disabled:u.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(fs,{className:"h-4 w-4 rotate-180"})}),u.currentPage>3&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>v(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),C().map(R=>e.jsx(M,{variant:R===u.currentPage?"default":"outline",size:"sm",onClick:()=>v(R),className:`h-8 w-8 p-0 ${R===u.currentPage?"bg-re-green text-white hover:bg-re-green/90":""}`,children:R},R)),u.currentPage5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>v(o),className:"h-8 w-8 p-0",children:o})]}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>v(u.currentPage+1),disabled:u.currentPage===o,className:"h-8 w-8 p-0",children:e.jsx(fs,{className:"h-4 w-4"})})]})]})})})]})}function fk({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(Ie,{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(ae,{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(M,{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(Ut,{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 bk(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ca,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:qt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:qt,iconColor:"text-gray-600"}}}function jk(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:Oe,iconColor:"text-slate-600",label:"Closed",description:"Request finalized and archived"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-300",icon:At,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ze,iconColor:"text-gray-600",label:t,description:""}}}function yk({request:t,onViewRequest:s}){var l;const a=bk(t.priority),r=jk(t.status),n=a.icon,i=r.icon;return e.jsx(q,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>s==null?void 0:s(t.id,t.title),"data-testid":`closed-request-card-${t.id}`,children:e.jsx(ee,{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(ae,{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(ae,{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(ae,{variant:"outline",className:`${a.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:t.priority}),(()=>{const o=t.templateType||"",c=(o==null?void 0:o.toUpperCase())||"";let d="Non-Templatized",m="bg-purple-100 !text-purple-600 border-purple-200";return c==="DEALER CLAIM"?(d="Dealer Claim",m="bg-blue-100 !text-blue-700 border-blue-200"):c==="FORM_16"?(d="Form 16",m="bg-emerald-100 !text-emerald-700 border-emerald-200"):c==="TEMPLATE"&&(d="Template"),e.jsx(ae,{variant:"outline",className:`${m} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:d})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:t.title}),((l=t.templateType)==null?void 0:l.toUpperCase())==="FORM_16"&&t.form16Submission&&e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-600",children:[t.form16Submission.dealerCode&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Dealer:"})," ",t.form16Submission.dealerCode]}),t.form16Submission.form16aNumber&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Form 16A:"})," ",t.form16Submission.form16aNumber]}),t.form16Submission.financialYear&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"FY:"})," ",t.form16Submission.financialYear]}),t.form16Submission.quarter&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Q:"})," ",t.form16Submission.quarter]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Total amount:"})," ",t.form16Submission.totalAmount!=null?new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t.form16Submission.totalAmount):"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Credit note:"})," ",t.form16Submission.creditNoteNumber||"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Status:"})," ",t.form16Submission.displayStatus||t.form16Submission.status||"—"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ls,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(os,{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(Oe,{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(dt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?wa(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Oe,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",wa(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(fs,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function vk({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(yk,{request:r,onViewRequest:a},r.id))})}function Nk({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(q,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(ee,{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(Ie,{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(M,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function wk(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 Ck({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const l=wk(a,r);return e.jsx(q,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(ee,{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(M,{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(fs,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(M,{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(M,{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(M,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(M,{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(fs,{className:"h-4 w-4"})})]})]})})})}function Sk(t){var s,a,r,n;return{id:t.requestNumber||t.request_number||t.requestId,requestId:t.requestId,displayId:t.requestNumber||t.request_number||t.requestId,title:t.title,description:t.description,status:(t.status||"").toString().toLowerCase(),priority:(t.priority||"").toString().toLowerCase(),initiator:{name:((s=t.initiator)==null?void 0:s.displayName)||((a=t.initiator)==null?void 0:a.email)||"—",avatar:(((r=t.initiator)==null?void 0:r.displayName)||"NA").split(" ").map(i=>i[0]).join("").slice(0,2).toUpperCase()},createdAt:t.submittedAt||t.createdAt||t.created_at||"—",dueDate:t.closureDate||t.closure_date||t.closedAt||void 0,reason:t.conclusionRemark||t.conclusion_remark,department:t.department,totalLevels:t.totalLevels||0,completedLevels:((n=t.summary)==null?void 0:n.approvedLevels)||0,templateType:t.templateType||t.template_type,form16Submission:t.form16Submission??null}}function Ak(t){return t.map(Sk)}function Tk({itemsPerPage:t=10}={}){const[s,a]=h.useState([]),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=h.useCallback(async(p=1,x)=>{try{p===1&&(n(!0),a([]));const u=await Gs.listClosedByMe({page:p,limit:t,search:x==null?void 0:x.search,status:x!=null&&x.status&&x.status!=="all"?x.status:void 0,priority:x==null?void 0:x.priority,templateType:x==null?void 0:x.templateType,financialYear:x==null?void 0:x.financialYear,quarter:x==null?void 0:x.quarter,sortBy:x==null?void 0:x.sortBy,sortOrder:x==null?void 0:x.sortOrder}),g=Array.isArray(u==null?void 0:u.data)?u.data:[],f=Ak(g);a(f);const b=u==null?void 0:u.pagination;b&&c({currentPage:b.page||1,totalPages:b.totalPages||1,totalRecords:b.total||0,itemsPerPage:t})}catch(u){console.error("[ClosedRequests] Error fetching requests:",u),a([])}finally{n(!1),l(!1)}},[t]),m=h.useCallback(p=>{l(!0),d(o.currentPage,p)},[d,o.currentPage]);return{requests:s,loading:r,refreshing:i,pagination:o,fetchRequests:d,handleRefresh:m}}const kk={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",form16FinancialYear:"",form16Quarter:"",sortBy:"created",sortOrder:"desc",currentPage:1},b0=on({name:"closedRequests",initialState:kk,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setTemplateTypeFilter:(t,s)=>{t.templateTypeFilter=s.payload},setForm16FinancialYear:(t,s)=>{t.form16FinancialYear=s.payload},setForm16Quarter:(t,s)=>{t.form16Quarter=s.payload},setSortBy:(t,s)=>{t.sortBy=s.payload},setSortOrder:(t,s)=>{t.sortOrder=s.payload},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.templateTypeFilter="all",t.form16FinancialYear="",t.form16Quarter="",t.currentPage=1}}}),{setSearchTerm:Rk,setStatusFilter:Dk,setPriorityFilter:Fk,setTemplateTypeFilter:Ik,setForm16FinancialYear:Pk,setForm16Quarter:Ek,setSortBy:_k,setSortOrder:Mk,setCurrentPage:Lk,clearFilters:Ok}=b0.actions;function $k({onFiltersChange:t,debounceMs:s=500}={}){const a=Gn(),r=h.useRef(null),n=h.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,form16FinancialYear:d,form16Quarter:m,sortBy:p,sortOrder:x,currentPage:u}=dn(N=>N.closedRequests),g=h.useCallback(N=>a(Rk(N)),[a]),f=h.useCallback(N=>a(Dk(N)),[a]),b=h.useCallback(N=>a(Fk(N)),[a]),j=h.useCallback(N=>a(Ik(N)),[a]),y=h.useCallback(N=>a(Pk(N)),[a]),w=h.useCallback(N=>a(Ek(N)),[a]),v=h.useCallback(N=>a(_k(N)),[a]),C=h.useCallback(N=>a(Mk(N)),[a]),A=h.useCallback(N=>a(Lk(N)),[a]),L=h.useCallback(()=>({search:i,status:l,priority:o,templateType:c!=="all"?c:void 0,financialYear:c==="FORM_16"&&d?d:void 0,quarter:c==="FORM_16"&&m?m:void 0,sortBy:p,sortOrder:x}),[i,l,o,c,d,m,p,x]);h.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const N=setTimeout(()=>{t&&t(L())},i?s:0);return r.current=N,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,d,m,p,x,t,L,s]);const D=h.useCallback(()=>{a(Ok())},[a]),R=[i,o!=="all"?o:null,l!=="all"?l:null,c!=="all"?c:null,c==="FORM_16"&&d?"fy":null,c==="FORM_16"&&m?"q":null].filter(Boolean).length;return{searchTerm:i,priorityFilter:o,statusFilter:l,templateTypeFilter:c,form16FinancialYear:d,form16Quarter:m,sortBy:p,sortOrder:x,currentPage:u,setSearchTerm:g,setPriorityFilter:b,setStatusFilter:f,setTemplateTypeFilter:j,setForm16FinancialYear:y,setForm16Quarter:w,setSortBy:v,setSortOrder:C,setCurrentPage:A,clearFilters:D,activeFiltersCount:R,getFilters:L}}function Uk({onViewRequest:t}){const s=Tk({itemsPerPage:10}),a=h.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=$k(),n=h.useMemo(()=>{try{const x=at.getUserData();return lc(x)}catch(x){return console.error("[ClosedRequests] Error getting user filter type:",x),"STANDARD"}},[]),i=h.useMemo(()=>uk(n),[n]),l=n==="DEALER",o=h.useCallback(()=>{const x=r.getFilters();return{search:x.search||void 0,status:x.status!=="all"?x.status:void 0,priority:!l&&x.priority?x.priority:void 0,templateType:x.templateType,financialYear:x.financialYear,quarter:x.quarter,sortBy:x.sortBy,sortOrder:x.sortOrder}},[r,l]),c=h.useRef({searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,form16FinancialYear:r.form16FinancialYear,form16Quarter:r.form16Quarter,sortBy:r.sortBy,sortOrder:r.sortOrder}),d=h.useRef(!1);h.useEffect(()=>{const x=r.currentPage||1;a.current(x,o()),d.current=!0},[l]),h.useEffect(()=>{if(!d.current)return;const x=c.current;if(!(x.searchTerm!==r.searchTerm||x.statusFilter!==r.statusFilter||x.priorityFilter!==r.priorityFilter||x.templateTypeFilter!==r.templateTypeFilter||x.form16FinancialYear!==r.form16FinancialYear||x.form16Quarter!==r.form16Quarter||x.sortBy!==r.sortBy||x.sortOrder!==r.sortOrder))return;const g=setTimeout(()=>{r.setCurrentPage(1),a.current(1,o()),c.current={searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,form16FinancialYear:r.form16FinancialYear,form16Quarter:r.form16Quarter,sortBy:r.sortBy,sortOrder:r.sortOrder}},r.searchTerm!==x.searchTerm?500:0);return()=>clearTimeout(g)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.templateTypeFilter,r.form16FinancialYear,r.form16Quarter,r.sortBy,r.sortOrder,l]);const m=h.useCallback(x=>{x>=1&&x<=s.pagination.totalPages&&(r.setCurrentPage(x),s.fetchRequests(x,o()))},[s,r,o]),p=h.useCallback(()=>{s.handleRefresh(o())},[s,o]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"closed-requests-page",children:[e.jsx(fk,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:p}),e.jsx(i,{searchTerm:r.searchTerm,priorityFilter:r.priorityFilter,statusFilter:r.statusFilter,templateTypeFilter:r.templateTypeFilter,form16FinancialYear:r.form16FinancialYear,form16Quarter:r.form16Quarter,sortBy:r.sortBy,sortOrder:r.sortOrder,activeFiltersCount:r.activeFiltersCount,onSearchChange:r.setSearchTerm,onPriorityChange:r.setPriorityFilter,onStatusChange:r.setStatusFilter,onTemplateTypeChange:r.setTemplateTypeFilter,onForm16FinancialYearChange:r.setForm16FinancialYear,onForm16QuarterChange:r.setForm16Quarter,onSortByChange:r.setSortBy,onSortOrderChange:()=>r.setSortOrder(r.sortOrder==="asc"?"desc":"asc"),onClearFilters:r.clearFilters}),e.jsx(vk,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(Nk,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(Ck,{pagination:s.pagination,onPageChange:m})]})}function Bk(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 Vk(t){return Bk(t)?"DEALER_CLAIM":"CUSTOM"}function zk(t,s){return`/request/${t}`}class Hk extends h.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(es,{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(M,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(M,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function Wk({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=_a().requestId||t||"",{user:i}=cs(),{apiRequest:l,loading:o}=Vc(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(Ut,{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=Vk(l),d=dk(c);return e.jsx(d,{requestId:t,onBack:s,dynamicRequests:a})}function Gk(t){return e.jsx(Hk,{children:e.jsx(Wk,{...t})})}function Yk({onViewSummary:t}){const s=ys(),[a,r]=h.useState([]),[n,i]=h.useState(!0),[l,o]=h.useState(""),[c,d]=h.useState(1),[m,p]=h.useState(1),[x,u]=h.useState(0),g=10,f=h.useCallback(async(w=1)=>{try{i(!0);const v=await BT({page:w,limit:g});r(v.data||[]),p(v.pagination.totalPages||1),u(v.pagination.total||0),d(v.pagination.page||1)}catch(v){console.error("Failed to fetch shared summaries:",v),X.error("Failed to load shared summaries")}finally{i(!1)}},[]);h.useEffect(()=>{f(1)},[f]);const b=async w=>{try{await n0(w),r(v=>v.map(C=>C.sharedSummaryId===w?{...C,isRead:!0,viewedAt:new Date().toISOString()}:C)),t?t(w):s(`/shared-summaries/${w}`)}catch(v){console.error("Failed to mark as viewed:",v),t?t(w):s(`/shared-summaries/${w}`)}},j=w=>{w>=1&&w<=m&&f(w)},y=a.filter(w=>{var C,A,L,D;if(!l)return!0;const v=l.toLowerCase();return((C=w.title)==null?void 0:C.toLowerCase().includes(v))||((A=w.requestNumber)==null?void 0:A.toLowerCase().includes(v))||((L=w.initiatorName)==null?void 0:L.toLowerCase().includes(v))||((D=w.sharedByName)==null?void 0:D.toLowerCase().includes(v))});return e.jsx("div",{className:"min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6 overflow-x-hidden",children:e.jsxs("div",{className:"max-w-7xl mx-auto w-full",children:[e.jsxs("div",{className:"mb-4 sm:mb-6",children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900 mb-1 sm:mb-2",children:"Shared Summaries"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600",children:"View summaries of closed requests shared with you"})]}),e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs("div",{className:"relative",children:[e.jsx(Ss,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ce,{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(Qe,{className:"h-8 w-8 animate-spin text-blue-600"})}),!n&&y.length===0&&e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 p-6 sm:p-12 text-center",children:[e.jsx(Ie,{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&&y.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-3 sm:gap-4 mb-4 sm:mb-6",children:y.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:()=>b(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(Rb,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}):e.jsx(St,{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(dt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",et(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(St,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",et(new Date(w.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(M,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:v=>{v.stopPropagation(),b(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(M,{variant:"outline",size:"sm",onClick:()=>j(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(M,{variant:"outline",size:"sm",onClick:()=>j(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function Kk(){const{sharedSummaryId:t}=_a(),s=ys(),[a,r]=h.useState(null),[n,i]=h.useState(!0);h.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var m,p;try{i(!0);try{await n0(t)}catch(u){console.warn("Failed to mark as viewed:",u)}const x=await Hc(t);r(x)}catch(x){console.error("Failed to fetch summary details:",x),X.error(((p=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:p.message)||"Failed to load summary"),s("/shared-summaries")}finally{i(!1)}})()},[t,s]);const l=d=>{const m=d.toLowerCase();return m==="approved"?e.jsx(Oe,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(At,{className:"h-4 w-4 text-red-600"}):m==="pending"||m==="in progress"?e.jsx(st,{className:"h-4 w-4 text-orange-600"}):e.jsx(Ie,{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(Qe,{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(M,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(Cs,{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(ae,{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(_s,{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:et(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:et(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(ae,{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(_s,{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(Ie,{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(M,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function Qk(){const{requestId:t}=_a(),s=ys(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(Xt,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(r0,{requestId:t||""})})})}function j0({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(ae,{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 ta({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:l,testId:o="stats-card",onClick:c}){return e.jsx(q,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":o,onClick:c,children:e.jsx(ee,{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 Xk({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(ta,{label:"Total",value:t.total,icon:Ie,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(ta,{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(ta,{label:"Paused",value:t.paused,icon:dr,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(ta,{label:"Approved",value:t.approved,icon:Oe,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(ta,{label:"Rejected",value:t.rejected,icon:At,iconColor:"text-red-600",gradient:"bg-gradient-to-br from-red-50 to-red-100 border-red-200",textColor:"text-red-700",valueColor:"text-red-900",testId:"stat-rejected",onClick:s?()=>a("rejected"):void 0}),e.jsx(ta,{label:"Draft",value:t.draft,icon:el,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(ta,{label:"Closed",value:t.closed,icon:tl,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 Jk({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,onSearchChange:n,onStatusChange:i,onPriorityChange:l,onTemplateTypeChange:o}){return e.jsx(q,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(ee,{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(Ss,{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(Ce,{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(He,{value:s,onValueChange:i,children:[e.jsx(Ge,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"status-filter",children:e.jsx(We,{placeholder:"Status"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"draft",children:"Draft"}),e.jsx(J,{value:"pending",children:"Pending"}),e.jsx(J,{value:"paused",children:"Paused"}),e.jsx(J,{value:"approved",children:"Approved"}),e.jsx(J,{value:"rejected",children:"Rejected"}),e.jsx(J,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:a,onValueChange:l,children:[e.jsx(Ge,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"priority-filter",children:e.jsx(We,{placeholder:"Priority"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Priority"}),e.jsx(J,{value:"express",children:"Express"}),e.jsx(J,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:r,onValueChange:o,children:[e.jsx(Ge,{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(We,{placeholder:"Template Type"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]})]})]})})})}function Zk(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ca,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:qt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:qt,iconColor:"text-gray-600"}}}function qk(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Oe,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:At,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Oe,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:el,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ze,iconColor:"text-gray-600"}}}const e4=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 t4({request:t,index:s,onViewRequest:a}){var o;const r=qk(t.status),n=Zk(t.priority),i=r.icon,l=n.icon;return e.jsx(Ht.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(q,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(ee,{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(ae,{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(ae,{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(dr,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ae,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(l,{className:"w-3 h-3 mr-1"}),t.priority]}),(()=>{const c=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",d=(c==null?void 0:c.toUpperCase())||"";let m="Non-Templatized",p="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Dealer Claim",p="bg-blue-100 !text-blue-700 border-blue-200"):d==="FORM_16"?(m="Form 16",p="bg-emerald-100 !text-emerald-700 border-emerald-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(ae,{variant:"outline",className:`${p} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:m})})()]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 line-clamp-2 leading-relaxed","data-testid":"request-description",children:e4(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:"})," ",wa(t.submittedDate)]})]})]}),e.jsx(fs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400 group-hover:text-blue-600 transition-colors flex-shrink-0 mt-1"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-4 pt-3 border-t border-gray-100",children:[e.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4",children:((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16"?e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ws,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-emerald-600 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm font-medium text-emerald-700","data-testid":"form16-ocr-flow",children:"Form 16 OCR FLOW"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(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(Ws,{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: ",wa(t.submittedDate)]})]})]})]})})})})}function s4({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(q,{"data-testid":"loading-state",children:e.jsx(ee,{className:"p-6 text-sm text-gray-600",children:"Loading your requests…"})});if(t.length===0){const l=a||r!=="all"||n!=="all";return e.jsx(q,{"data-testid":"empty-state",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(Ie,{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(t4,{request:l,index:o,onViewRequest:i},l.id))})}function a4(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 y0(t){return Array.isArray(t)?t.map(a4):[]}function r4({itemsPerPage:t=10}={}){const[s,a]=h.useState([]),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=h.useCallback(async(m=1,p)=>{try{m===1&&(n(!0),a([]));const x=await Gs.listMyInitiatedWorkflows({page:m,limit:t,search:p==null?void 0:p.search,status:p==null?void 0:p.status,priority:p==null?void 0:p.priority,templateType:p==null?void 0:p.templateType}),u=Array.isArray(x==null?void 0:x.data)?x.data:[],g=y0(u);a(g),l(!0);const f=x==null?void 0:x.pagination;f&&c({currentPage:f.page||1,totalPages:f.totalPages||1,totalRecords:f.total||0,itemsPerPage:t})}catch(x){console.error("[MyRequests] Error fetching requests:",x),a([]),l(!0)}finally{n(!1)}},[t]);return{requests:s,loading:r,hasFetchedFromApi:i,pagination:o,fetchMyRequests:d}}const n4={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",currentPage:1},v0=on({name:"myRequests",initialState:n4,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:i4,setStatusFilter:l4,setPriorityFilter:o4,setTemplateTypeFilter:c4,setCurrentPage:d4,clearFilters:m4}=v0.actions;function u4({onFiltersChange:t,debounceMs:s=500}={}){const a=Gn(),r=h.useRef(null),n=h.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d}=dn(j=>j.myRequests),m=h.useCallback(j=>a(i4(j)),[a]),p=h.useCallback(j=>a(l4(j)),[a]),x=h.useCallback(j=>a(o4(j)),[a]),u=h.useCallback(j=>a(c4(j)),[a]),g=h.useCallback(j=>a(d4(j)),[a]),f=h.useCallback(()=>({search:i,status:l,priority:o,templateType:c}),[i,l,o,c]);h.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const j=setTimeout(()=>{t&&t(f())},i?s:0);return r.current=j,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,t,f,s]);const b=h.useCallback(()=>{a(m4())},[a]);return{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d,setSearchTerm:m,setStatusFilter:p,setPriorityFilter:x,setTemplateTypeFilter:u,setCurrentPage:g,getFilters:f,resetFilters:b}}function x4({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=cs(),r=r4({itemsPerPage:10}),n=h.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=u4(),l=h.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}),o=h.useRef(!1);h.useEffect(()=>{const j=i.currentPage||1;n.current(j,{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},[]),h.useEffect(()=>{if(!o.current)return;const j=l.current;if(!(j.searchTerm!==i.searchTerm||j.statusFilter!==i.statusFilter||j.priorityFilter!==i.priorityFilter||j.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!==j.searchTerm?500:0);return()=>clearTimeout(w)},[i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter]);const[c,d]=h.useState(null),[m,p]=h.useState(!1),x=h.useCallback(async()=>{if(a!=null&&a.userId)try{p(!0);const j=await Mt.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:j.totalRequests||0,pending:j.openRequests||0,paused:j.pausedRequests||0,approved:j.approvedRequests||0,rejected:j.rejectedRequests||0,draft:j.draftRequests||0,closed:j.closedRequests||0})}catch(j){console.error("Failed to fetch backend stats:",j),d(null)}finally{p(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter,i.templateTypeFilter]);h.useEffect(()=>{const j=setTimeout(()=>{x()},i.searchTerm?500:0);return()=>clearTimeout(j)},[i.searchTerm,i.priorityFilter,i.templateTypeFilter,x]);const u=y0(s),g=r.hasFetchedFromApi?r.requests:u,f=h.useMemo(()=>c?{total:c.total||0,pending:c.pending||0,paused:c.paused||0,approved:c.approved||0,rejected:c.rejected||0,draft:c.draft||0,closed:c.closed||0}:{total:0,pending:0,paused:0,approved:0,rejected:0,draft:0,closed:0},[c]),b=h.useCallback(j=>{j>=1&&j<=r.pagination.totalPages&&(i.setCurrentPage(j),r.fetchMyRequests(j,{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(j0,{icon:Ie,title:"My Requests",description:"Track and manage all your submitted requests",badge:{value:`${f.total} total`,label:"requests",loading:r.loading||m},testId:"my-requests-header"}),e.jsx(Xk,{stats:f,onStatusFilter:j=>{i.setStatusFilter(j)}}),e.jsx(Jk,{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(s4,{requests:g,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(Mr,{currentPage:i.currentPage||r.pagination.currentPage,totalPages:r.pagination.totalPages,totalRecords:r.pagination.totalRecords,itemsPerPage:r.pagination.itemsPerPage,onPageChange:b,loading:r.loading,itemLabel:"requests",testIdPrefix:"my-requests-pagination"})]})}function N0({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(j0,{icon:Ie,title:i(),description:l(),testId:"requests-header"}),e.jsx(ae,{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(M,{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(Ut,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function w0({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(ta,{label:"Total",value:t.total,icon:Ie,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(ta,{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(ta,{label:"Paused",value:t.paused,icon:dr,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(ta,{label:"Approved",value:t.approved,icon:Oe,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(ta,{label:"Rejected",value:t.rejected,icon:At,iconColor:"text-red-600",gradient:"bg-gradient-to-br from-red-50 to-red-100 border-red-200",textColor:"text-red-700",valueColor:"text-red-900",testId:"stat-rejected",onClick:s?()=>a("rejected"):void 0}),e.jsx(ta,{label:"Closed",value:t.closed,icon:tl,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 h4=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ca,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:qt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:qt,iconColor:"text-gray-600"}}},Sx=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:Oe,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected",icon:At,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending",icon:st,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"closed",icon:Oe,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"draft",icon:el,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:Ze,iconColor:"text-gray-600"}}},p4=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 g4(t){return t==null?"—":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function f4({request:t,index:s,onViewRequest:a}){var p;const r=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",n=t==null?void 0:t.form16Submission,i=n==null?void 0:n.displayStatus,l=i&&/balance mismatch|failed/i.test(String(i)),o=r&&i?{color:l?"bg-red-100 !text-red-800 border-red-200":i==="Completed"?"bg-green-100 !text-green-800 border-green-200":"bg-gray-100 !text-gray-700 border-gray-200",icon:Sx(t.status).icon,label:i}:Sx(t.status),c=h4(t.priority),d=o.icon,m=c.icon;return e.jsx(Ht.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(q,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(ee,{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(ae,{variant:"outline",className:`${o.color} border font-medium text-xs shrink-0`,"data-testid":"status-badge",children:[e.jsx(d,{className:"w-3 h-3 mr-1"}),e.jsx("span",{className:"capitalize",children:o.label})]}),(((p=t.pauseInfo)==null?void 0:p.isPaused)||t.isPaused)&&e.jsxs(ae,{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(dr,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ae,{variant:"outline",className:`${c.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(m,{className:"w-3 h-3 mr-1"}),t.priority]}),(()=>{const x=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",u=(x==null?void 0:x.toUpperCase())||"";let g="Non-Templatized",f="bg-purple-100 !text-purple-600 border-purple-200";return u==="DEALER CLAIM"?(g="Dealer Claim",f="bg-blue-100 !text-blue-700 border-blue-200"):u==="FORM_16"?(g="Form 16",f="bg-emerald-100 !text-emerald-700 border-emerald-200"):u==="TEMPLATE"&&(g="Template"),e.jsx(ae,{variant:"outline",className:`${f} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:g})})(),t.department&&e.jsx(ae,{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:p4(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:"})," ",wa(t.submittedDate)]}),r&&n&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"truncate","data-testid":"form16-total-amount",children:[e.jsx("span",{className:"font-medium",children:"Total amount:"})," ",n.totalAmount!=null?g4(n.totalAmount):"—"]}),e.jsxs("span",{className:"truncate","data-testid":"form16-credit-note",children:[e.jsx("span",{className:"font-medium",children:"Credit note:"})," ",n.creditNoteNumber||"—"]})]})]})]}),e.jsx(fs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400 group-hover:text-blue-600 transition-colors flex-shrink-0 mt-1"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-4 pt-3 border-t border-gray-100",children:[e.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4",children:((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16"?e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ws,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-emerald-600 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm font-medium text-emerald-700","data-testid":"form16-ocr-flow",children:"Form 16 OCR FLOW"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(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(Ws,{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: ",wa(t.submittedDate)]})]})]})]})})})})}function C0({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(q,{"data-testid":"loading-state",children:e.jsx(ee,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(q,{"data-testid":"empty-state",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(Ie,{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(f4,{request:n,index:i,onViewRequest:r},n.id))})}const b4={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",requestTypeFilter:"all",form16FinancialYear:"all",form16Quarter:"all",slaComplianceFilter:"all",departmentFilter:"all",initiatorFilter:"all",approverFilter:"all",approverFilterType:"current",dateRange:"all",customStartDate:void 0,customEndDate:void 0,showCustomDatePicker:!1,currentPage:1},S0=on({name:"requests",initialState:b4,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setTemplateTypeFilter:(t,s)=>{t.templateTypeFilter=s.payload,s.payload!=="FORM_16"&&(t.form16FinancialYear="all",t.form16Quarter="all")},setRequestTypeFilter:(t,s)=>{t.requestTypeFilter=s.payload,s.payload!=="form_16"&&(t.form16FinancialYear="all",t.form16Quarter="all")},setForm16FinancialYear:(t,s)=>{t.form16FinancialYear=s.payload},setForm16Quarter:(t,s)=>{t.form16Quarter=s.payload},setSlaComplianceFilter:(t,s)=>{t.slaComplianceFilter=s.payload},setDepartmentFilter:(t,s)=>{t.departmentFilter=s.payload},setInitiatorFilter:(t,s)=>{t.initiatorFilter=s.payload},setApproverFilter:(t,s)=>{t.approverFilter=s.payload},setApproverFilterType:(t,s)=>{t.approverFilterType=s.payload},setDateRange:(t,s)=>{t.dateRange=s.payload},setCustomStartDate:(t,s)=>{t.customStartDate=s.payload},setCustomEndDate:(t,s)=>{t.customEndDate=s.payload},setShowCustomDatePicker:(t,s)=>{t.showCustomDatePicker=s.payload},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.templateTypeFilter="all",t.requestTypeFilter="all",t.form16FinancialYear="all",t.form16Quarter="all",t.slaComplianceFilter="all",t.departmentFilter="all",t.initiatorFilter="all",t.approverFilter="all",t.approverFilterType="current",t.dateRange="all",t.customStartDate=void 0,t.customEndDate=void 0,t.showCustomDatePicker=!1,t.currentPage=1}}}),{setSearchTerm:j4,setStatusFilter:y4,setPriorityFilter:v4,setTemplateTypeFilter:N4,setRequestTypeFilter:w4,setForm16FinancialYear:C4,setForm16Quarter:S4,setSlaComplianceFilter:A4,setDepartmentFilter:T4,setInitiatorFilter:k4,setApproverFilter:R4,setApproverFilterType:D4,setDateRange:Ax,setCustomStartDate:Kl,setCustomEndDate:Ql,setShowCustomDatePicker:di,setCurrentPage:F4,clearFilters:I4}=S0.actions;function A0(){const t=Gn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,requestTypeFilter:i,form16FinancialYear:l,form16Quarter:o,slaComplianceFilter:c,departmentFilter:d,initiatorFilter:m,approverFilter:p,approverFilterType:x,dateRange:u,customStartDate:g,customEndDate:f,showCustomDatePicker:b,currentPage:j}=dn(Z=>Z.requests),y=h.useCallback(Z=>t(j4(Z)),[t]),w=h.useCallback(Z=>t(y4(Z)),[t]),v=h.useCallback(Z=>t(v4(Z)),[t]),C=h.useCallback(Z=>t(N4(Z)),[t]),A=h.useCallback(Z=>t(w4(Z)),[t]),L=h.useCallback(Z=>t(C4(Z)),[t]),D=h.useCallback(Z=>t(S4(Z)),[t]),R=h.useCallback(Z=>t(A4(Z)),[t]),N=h.useCallback(Z=>t(T4(Z)),[t]),_=h.useCallback(Z=>t(k4(Z)),[t]),S=h.useCallback(Z=>t(R4(Z)),[t]),U=h.useCallback(Z=>t(D4(Z)),[t]),F=h.useCallback(Z=>t(Ax(Z)),[t]),$=h.useCallback(Z=>t(Kl(Z)),[t]),P=h.useCallback(Z=>t(Ql(Z)),[t]),T=h.useCallback(Z=>t(di(Z)),[t]),k=h.useCallback(Z=>t(F4(Z)),[t]),B=h.useCallback(()=>n==="FORM_16"?{templateType:"FORM_16",financialYear:l!=="all"?l:void 0,quarter:o!=="all"?o:void 0}:{search:s||void 0,status:a!=="all"?a:void 0,priority:r!=="all"?r:void 0,templateType:n!=="all"?n:void 0,slaCompliance:c!=="all"?c:void 0,department:d!=="all"?d:void 0,initiator:m!=="all"?m:void 0,approver:p!=="all"?p:void 0,approverType:p!=="all"?x:void 0,dateRange:u,startDate:g,endDate:f},[s,a,r,n,l,o,c,d,m,p,x,u,g,f]),I=h.useCallback(()=>{t(I4())},[t]),E=h.useCallback(Z=>{const O=Z;t(Ax(O)),O!=="custom"?(t(Kl(void 0)),t(Ql(void 0)),t(di(!1))):t(di(!0))},[t]),W=h.useCallback(()=>{g&&f&&(g>f&&(t(Kl(f)),t(Ql(g))),t(di(!1)))},[g,f,t]),V=n==="FORM_16";return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,requestTypeFilter:i,form16FinancialYear:l,form16Quarter:o,isForm16:V,slaComplianceFilter:c,departmentFilter:d,initiatorFilter:m,approverFilter:p,approverFilterType:x,dateRange:u,customStartDate:g,customEndDate:f,showCustomDatePicker:b,currentPage:j,hasActiveFilters:V?n==="FORM_16"&&(l!=="all"||o!=="all"):!!(s||a!=="all"||r!=="all"||n!=="all"||i!=="all"||i==="form_16"&&(l!=="all"||o!=="all")||c!=="all"||d!=="all"||m!=="all"||p!=="all"||u!=="all"||g||f),setSearchTerm:y,setStatusFilter:w,setPriorityFilter:v,setTemplateTypeFilter:C,setRequestTypeFilter:A,setForm16FinancialYear:L,setForm16Quarter:D,setSlaComplianceFilter:R,setDepartmentFilter:N,setInitiatorFilter:_,setApproverFilter:S,setApproverFilterType:U,setDateRange:F,setCustomStartDate:$,setCustomEndDate:P,setShowCustomDatePicker:T,setCurrentPage:k,getFilters:B,clearFilters:I,handleDateRangeChange:E,handleApplyCustomDate:W}}function Ui({filterValue:t,onFilterChange:s,source:a="default"}){const[r,n]=h.useState(""),[i,l]=h.useState([]),[o,c]=h.useState(!1),[d,m]=h.useState(null),[p,x]=h.useState(!1),u=h.useRef(null);h.useEffect(()=>{async function j(){if(t!=="all"&&!d)try{const y=await sa.getUserById(t);y&&(m(y),n(y.displayName||y.email))}catch(y){console.error("Failed to fetch user detail for search:",y)}else t==="all"&&(m(null),n(""))}j()},[t]),h.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const g=h.useCallback(j=>{if(n(j),u.current&&clearTimeout(u.current),!j||j.trim().length<2){l([]),c(!1);return}u.current=setTimeout(async()=>{var y;x(!0);try{const v=((y=(await sa.searchUsers(j.trim(),10,a)).data)==null?void 0:y.data)||[];l(v),c(v.length>0)}catch(w){console.error("Search API failed:",w),l([]),c(!1)}finally{x(!1)}},400)},[a]),f=h.useCallback(j=>{m(j),s(j.userId),n(j.displayName||j.email),c(!1),l([])},[s]),b=h.useCallback(()=>{m(null),s("all"),n(""),c(!1),l([])},[s]);return{searchQuery:r,searchResults:i,showResults:o,selectedUser:d,searching:p,handleSearch:g,handleSelect:f,handleClear:b,setShowResults:c}}function P4(t){var d,m,p,x,u,g,f;const s=t.submittedAt||t.submitted_at||t.createdAt||t.created_at,a=(t.priority||"").toString().toLowerCase(),r=(t.status||"").toString().toUpperCase();let n="—",i="—";const l=t.currentApprover||t.current_approver||t.currentApproverData;if(l)n=l.name||l.approverName||l.displayName||l.email||l.approverEmail||"—";else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const b=t.approvals.find(j=>{const y=(j.status||"").toString().toUpperCase();return y==="PENDING"||y==="IN_PROGRESS"});if(b)n=b.approverName||((d=b.approver)==null?void 0:d.name)||((m=b.approver)==null?void 0:m.displayName)||b.approverEmail||((p=b.approver)==null?void 0:p.email)||"—";else{const y=[...t.approvals].sort((w,v)=>{const C=w.levelNumber||w.level_number||0;return(v.levelNumber||v.level_number||0)-C})[0];y&&(n=y.approverName||((x=y.approver)==null?void 0:x.name)||((u=y.approver)==null?void 0:u.displayName)||y.approverEmail||((g=y.approver)==null?void 0:g.email)||"—")}}const o=t.currentLevel||t.current_level||t.currentLevelNumber||t.current_level_number,c=t.totalLevels||t.total_levels||t.totalLevelsCount||t.total_levels_count;if(o&&c)i=`${o} of ${c}`;else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const b=t.approvals.find(j=>{const y=(j.status||"").toString().toUpperCase();return y==="PENDING"||y==="IN_PROGRESS"});if(b){const j=b.levelNumber||b.level_number||0,y=c||t.approvals.length;i=`${j} of ${y}`}else c&&(i=`${c} of ${c}`)}else t.currentStep&&t.totalSteps&&(i=`${t.currentStep} of ${t.totalSteps}`);return{id:t.requestNumber||t.request_number||t.requestId||t.id||t.request_id,requestId:t.requestId||t.id||t.request_id,displayId:t.requestNumber||t.request_number||t.id,title:t.title,description:t.description,status:r.toLowerCase().replace("_","-"),priority:a,department:t.department||((f=t.initiator)==null?void 0:f.department),submittedDate:t.submittedAt||(t.createdAt?new Date(t.createdAt).toISOString().split("T")[0]:void 0),createdAt:s,currentApprover:n,approverLevel:i,templateType:t.templateType||t.template_type,workflowType:t.workflowType||t.workflow_type,templateName:t.templateName||t.template_name,form16Submission:t.form16Submission??null}}function T0(t){return Array.isArray(t)?t.map(P4):[]}function E4(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,p=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:p}}else return s&&a?{total:a.total,pending:a.pending,paused:a.paused||0,approved:a.approved,rejected:a.rejected,draft:a.draft,closed:a.closed}:{total:n||i.length,pending:i.filter(o=>o.status==="pending"||o.status==="in-progress").length,paused:i.filter(o=>o.status==="paused").length,approved:i.filter(o=>o.status==="approved").length,rejected:i.filter(o=>o.status==="rejected").length,draft:i.filter(o=>o.status==="draft").length,closed:i.filter(o=>o.status==="closed").length}}var k0={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Vi,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(k0);var _4=k0.exports;const R0=zi(_4);var D0={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Vi,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(D0);var M4=D0.exports;const F0=zi(M4);ss.extend(F0);ss.extend(R0);function L4(t,s){let a=[...t];if(s.search){const r=s.search.toLowerCase();a=a.filter(n=>{var i,l,o,c;return((i=n.title)==null?void 0:i.toLowerCase().includes(r))||((l=n.description)==null?void 0:l.toLowerCase().includes(r))||((o=n.requestNumber)==null?void 0:o.toLowerCase().includes(r))||((c=n.request_number)==null?void 0:c.toLowerCase().includes(r))})}if(s.status&&s.status!=="all")if(s.status.toLowerCase()==="pending")a=a.filter(r=>{var l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return(n==="PENDING"||n==="IN_PROGRESS")&&!i});else if(s.status.toLowerCase()==="paused")a=a.filter(r=>{var l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return n==="PAUSED"||i});else{const r=s.status.toUpperCase().replace("-","_");a=a.filter(n=>{var o;const i=(n.status||"").toString().toUpperCase(),l=((o=n.pauseInfo)==null?void 0:o.isPaused)||n.isPaused||!1;return r==="IN_PROGRESS"||r==="IN-PROGRESS"?i==="IN_PROGRESS"&&!l:i===r&&!l})}if(s.priority&&s.priority!=="all"&&(a=a.filter(r=>{var n;return(r.priority||"").toString().toLowerCase()===((n=s.priority)==null?void 0:n.toLowerCase())})),s.department&&s.department!=="all"&&(a=a.filter(r=>{var i;return(r.department||((i=r.initiator)==null?void 0:i.department)||"")===s.department})),s.initiator&&s.initiator!=="all"&&(a=a.filter(r=>{var i,l;return(r.initiatorId||r.initiator_id||((i=r.initiator)==null?void 0:i.userId)||((l=r.initiator)==null?void 0:l.user_id)||(r.initiator&&typeof r.initiator=="object"&&"userId"in r.initiator?r.initiator.userId:null))===s.initiator})),s.approver&&s.approver!=="all"&&((s.approverType||"current")==="current"?a=a.filter(n=>{var l,o,c,d,m,p;return(((l=n.currentApprover)==null?void 0:l.userId)||((o=n.currentApprover)==null?void 0:o.user_id)||((d=(c=n.approvals)==null?void 0:c.find(x=>{const u=(x.status||"").toString().toUpperCase();return u==="IN_PROGRESS"||u==="PENDING"}))==null?void 0:d.approverId)||((p=(m=n.approvals)==null?void 0:m.find(x=>{const u=(x.status||"").toString().toUpperCase();return u==="IN_PROGRESS"||u==="PENDING"}))==null?void 0:p.approver_id)||n.currentApproverId||n.current_approver_id)===s.approver}):a=a.filter(n=>{var l,o;const i=[];return(l=n.currentApprover)!=null&&l.userId&&i.push(n.currentApprover.userId),(o=n.currentApprover)!=null&&o.user_id&&i.push(n.currentApprover.user_id),Array.isArray(n.approvals)&&n.approvals.forEach(c=>{c.approverId&&i.push(c.approverId),c.approver_id&&i.push(c.approver_id)}),i.includes(s.approver||"")})),s.slaCompliance&&s.slaCompliance!=="all"&&(a=a.filter(r=>{var c,d,m,p,x,u,g,f,b,j,y,w;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const v=(r.status||"").toString().toUpperCase();if(!(v==="APPROVED"||v==="REJECTED"||v==="CLOSED"))return!1;const A=((c=r.currentLevelSLA)==null?void 0:c.status)||((m=(d=r.currentApprover)==null?void 0:d.sla)==null?void 0:m.status)||((p=r.sla)==null?void 0:p.status)||((u=(x=r.summary)==null?void 0:x.sla)==null?void 0:u.status);return A?A!=="breached"&&A.toLowerCase()!=="breached":!0}const i=((g=r.currentLevelSLA)==null?void 0:g.status)||((b=(f=r.currentApprover)==null?void 0:f.sla)==null?void 0:b.status)||((j=r.sla)==null?void 0:j.status)||((w=(y=r.summary)==null?void 0:y.sla)==null?void 0:w.status);if(!i)return n==="on-track"||n==="on_track";const 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=ss(s.startDate).startOf("day").toDate(),n=ss(s.endDate).endOf("day").toDate();else{const i=ss();switch(s.dateRange){case"today":r=i.startOf("day").toDate(),n=i.endOf("day").toDate();break;case"week":r=i.startOf("week").toDate(),n=i.endOf("week").toDate();break;case"month":r=i.startOf("month").toDate(),n=i.endOf("month").toDate();break}}r&&n&&(a=a.filter(i=>{const l=i.submittedAt||i.submission_date||i.submitted_at;if(!l){const m=i.createdAt||i.created_at||i.created_date;if(!m)return!1;const p=ss(m).startOf("day").toDate(),x=ss(r).startOf("day").toDate(),u=ss(n).endOf("day").toDate();return p>=x&&p<=u}const o=ss(l).startOf("day").toDate(),c=ss(r).startOf("day").toDate(),d=ss(n).endOf("day").toDate();return o>=c&&o<=d}))}return a}ss.extend(R0);ss.extend(F0);function O4(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return et(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function I0(t,s){const a=L4(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var y,w,v,C,A;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),p=((y=c.initiator)==null?void 0:y.displayName)||((w=c.initiator)==null?void 0:w.email)||c.initiatorName||"N/A",x=c.department||((v=c.initiator)==null?void 0:v.department)||"N/A",u=((C=c.currentApprover)==null?void 0:C.displayName)||((A=c.currentApprover)==null?void 0:A.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",f=O4(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),b=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),j=[c.requestNumber||c.request_number||"",`"${(c.title||"").replace(/"/g,'""')}"`,d,m,`"${p.replace(/"/g,'""')}"`,`"${x.replace(/"/g,'""')}"`,`"${u.replace(/"/g,'""')}"`,g,f,`"${b}"`];r.push(j.join(","))});const n=r.join(` +This is an automated message.`,p=o||m;return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-2xl lg:max-w-[1000px] max-w-2xl",children:[e.jsx(pt,{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(fa,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ut,{className:"text-lg leading-none font-semibold",children:"Email Notification Template"}),e.jsxs(_t,{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(fa,{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(Ji,{className:"w-5 h-5 text-purple-600"}),e.jsx("span",{className:"font-semibold text-gray-900",children:"Royal Enfield"})]}),e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("pre",{className:"whitespace-pre-wrap font-sans text-sm text-gray-700 leading-relaxed bg-transparent p-0 border-0",children:p})}),e.jsx("div",{className:"pt-3 border-t border-gray-200",children:e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx(dt,{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(ae,{className:"bg-blue-50 text-blue-700 border-blue-200",children:["Step ",a]}),e.jsx(ae,{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(M,{variant:"outline",onClick:s,className:"h-9",children:[e.jsx(jt,{className:"w-4 h-4 mr-2"}),"Close"]})})]})})}function R5({isOpen:t,onClose:s,onApprove:a,onReject:r,onRequestRevision:n,proposalData:i,dealerName:l="Dealer",activityName:o="Activity",requestId:c,request:d,previousProposalData:m,taxationType:p}){const x=h.useMemo(()=>p==="Non GST"||p==="Non-GST",[p]),[u,g]=h.useState(""),[f,b]=h.useState(!1),[j,y]=h.useState(null),[w,v]=h.useState(!1),C=h.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const I=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(I)?I.reduce((E,W)=>{const V=typeof W=="object"&&W.amount||0,Y=typeof W=="object"&&W.quantity||1,Z=V*Y,O=typeof W=="object"&&W.gstAmt||0,z=W.totalAmt||Z+O;return E+(Number(z)||0)},0):0},[i]),A=h.useMemo(()=>{if(!(i!=null&&i.costBreakup))return 0;const I=Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[];return Array.isArray(I)?I.reduce((E,W)=>{const V=typeof W=="object"&&W.amount||0,Y=typeof W=="object"&&W.quantity||1;return E+Number(V)*Number(Y)},0):0},[i]),L=h.useMemo(()=>{const I=(d==null?void 0:d.internalOrders)||(d==null?void 0:d.internal_orders)||[];if(Array.isArray(I)&&I.length>0)return I.reduce((W,V)=>{const Y=Number(V.ioBlockedAmount||V.io_blocked_amount||0);return W+Y},0);const E=(d==null?void 0:d.internalOrder)||(d==null?void 0:d.internal_order);return Number((E==null?void 0:E.ioBlockedAmount)||(E==null?void 0:E.io_blocked_amount)||0)},[d==null?void 0:d.internalOrders,d==null?void 0:d.internal_orders,d==null?void 0:d.internalOrder,d==null?void 0:d.internal_order]),D=L>=A-.01,R=Math.max(0,A-L),[N,_]=h.useState(null),S=I=>{if(!I)return"—";try{return new Date(I).toLocaleDateString("en-IN",{year:"numeric",month:"long",day:"numeric"})}catch{return I}},U=I=>{if(!I.name)return!1;const E=I.name.toLowerCase();return E.endsWith(".pdf")||E.endsWith(".jpg")||E.endsWith(".jpeg")||E.endsWith(".png")||E.endsWith(".gif")||E.endsWith(".webp")},F=I=>{let E=I.url||I.storageUrl||"";const W=I.id||I.documentId||"";if(!W&&!E){X.error("Document preview not available");return}if(E&&!E.startsWith("http")&&!E.startsWith("blob:")){const V="https://reflow-uat.royalenfield.com",Y=V.endsWith("/")?V.slice(0,-1):V,Z=E.startsWith("/")?E:`/${E}`;E=`${Y}${Z}`}_({name:I.name||"Document",url:E||(W?mn(W):""),type:(I.name||"").toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg",id:W})};h.useEffect(()=>()=>{N!=null&&N.url&&N.url.startsWith("blob:")&&window.URL.revokeObjectURL(N.url)},[N]);const $=async()=>{if(!u.trim()){X.error("Please provide approval comments");return}try{b(!0),y("approve"),await a(u),k(),s()}catch(I){console.error("Failed to approve proposal:",I),X.error("Failed to approve proposal. Please try again.")}finally{b(!1),y(null)}},P=async()=>{if(!u.trim()){X.error("Please provide rejection reason");return}try{b(!0),y("reject"),await r(u),k(),s()}catch(I){console.error("Failed to reject proposal:",I),X.error("Failed to reject proposal. Please try again.")}finally{b(!1),y(null)}},T=async()=>{if(!u.trim()){X.error("Please provide reasons for requesting a revision");return}if(!n){X.error("Revision feature is not available");return}try{b(!0),y("revision"),await n(u),k(),s()}catch(I){console.error("Failed to request revision:",I),X.error("Failed to request revision. Please try again.")}finally{b(!1),y(null)}},k=()=>{g(""),y(null)},B=()=>{f||(k(),s())};return t?e.jsxs(ht,{open:t,onOpenChange:B,children:[e.jsxs(mt,{className:"dealer-proposal-modal overflow-hidden flex flex-col",children:[e.jsxs(pt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(ut,{className:"flex items-center gap-2 text-lg lg:text-xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{className:"w-4 h-4 lg:w-5 lg:h-5 text-green-600"}),"Requestor Evaluation & Confirmation"]}),p&&e.jsx(ae,{className:`ml-2 border-none shadow-sm ${x?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:x?"Non-GST Claim":"GST Claim"})]}),e.jsx(_t,{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(!w),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(Ie,{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(ae,{variant:"secondary",className:"bg-amber-200 text-amber-800 text-[10px]",children:["₹",Number(m.totalEstimatedBudget||m.totalBudget||0).toLocaleString("en-IN")]})]}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-amber-700",children:w?e.jsx(Vo,{className:"w-4 h-4"}):e.jsx(bs,{className:"w-4 h-4"})})]}),w&&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(dt,{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:U({name:m.documentUrl})?e.jsxs(e.Fragment,{children:[e.jsx(St,{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(Rt,{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(or,{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((I,E)=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"p-2 text-gray-800",children:I.description}),e.jsxs("td",{className:"p-2 text-right text-gray-800 font-medium",children:["₹",Number(I.amount).toLocaleString("en-IN")]})]},E)),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(Ie,{className:"w-3 h-3"}),"Supporting Documents"]}),e.jsx("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:m.otherDocuments.map((I,E)=>e.jsx(Er,{document:{documentId:I.documentId||I.id||"",name:I.originalFileName||I.fileName||I.name||"Supporting Document",fileType:(I.originalFileName||I.fileName||I.name||"").split(".").pop()||"file",uploadedAt:I.uploadedAt||new Date().toISOString()},onPreview:U({name:I.originalFileName||I.fileName||I.name||""})?()=>F(I):void 0,onDownload:async W=>{if(W)await Ls(W);else{let V=I.storageUrl||I.documentUrl;if(V&&!V.startsWith("http")){const Y="https://reflow-uat.royalenfield.com",Z=Y.endsWith("/")?Y.slice(0,-1):Y,O=V.startsWith("/")?V:`/${V}`;V=`${Z}${O}`}V&&window.open(V,"_blank")}}},E))})]}),(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(Hs,{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(Ie,{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(Ie,{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 ",S(i.submittedAt)]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:i.proposalDocument.id&&e.jsxs(e.Fragment,{children:[U(i.proposalDocument)&&e.jsx("button",{type:"button",onClick:()=>F(i.proposalDocument),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(St,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{var I;try{(I=i.proposalDocument)!=null&&I.id&&await Ls(i.proposalDocument.id)}catch(E){console.error("Failed to download document:",E),X.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Rt,{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(Ie,{className:"w-4 h-4 text-gray-600"}),"Other Supporting Documents"]}),e.jsxs(ae,{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((I,E)=>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(Ie,{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:I.name,children:I.name})]}),I.id&&e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[U(I)&&e.jsx("button",{type:"button",onClick:()=>F(I),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Preview document",children:e.jsx(St,{className:"w-5 h-5 text-blue-600"})}),e.jsx("button",{type:"button",onClick:async()=>{try{I.id&&await Ls(I.id)}catch(W){console.error("Failed to download document:",W),X.error("Failed to download document")}},className:"p-2 hover:bg-gray-200 rounded-lg transition-colors",title:"Download document",children:e.jsx(Rt,{className:"w-5 h-5 text-gray-600"})})]})]},E))})]})]}),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(or,{className:"w-4 h-4 text-green-600"}),"Cost Breakup"]})}),(()=>{const I=i!=null&&i.costBreakup?Array.isArray(i.costBreakup)?i.costBreakup:typeof i.costBreakup=="string"?JSON.parse(i.costBreakup):[]:[];return I&&Array.isArray(I)&&I.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden max-h-[200px] lg:max-h-[180px] overflow-y-auto",children:[e.jsx("div",{className:"bg-gray-50 px-3 lg:px-4 py-2 border-b sticky top-0",children:e.jsxs("div",{className:`grid ${x?"grid-cols-3":"grid-cols-4"} gap-4 text-xs lg:text-sm font-semibold text-gray-700`,children:[e.jsx("div",{className:"col-span-1",children:"Item Description"}),e.jsx("div",{className:"text-right",children:"Base"}),!x&&e.jsx("div",{className:"text-right",children:"GST"}),e.jsx("div",{className:"text-right",children:"Total"})]})}),e.jsx("div",{className:"divide-y",children:I.map((E,W)=>{var V,Y;return e.jsxs("div",{className:`px-3 lg:px-4 py-2 lg:py-3 grid ${x?"grid-cols-3":"grid-cols-4"} gap-4`,children:[e.jsxs("div",{className:"col-span-1 text-xs lg:text-sm text-gray-700",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[e.jsx("span",{className:"font-medium",children:(V=E==null?void 0:E.description)!=null&&V.startsWith("[ADDITIONAL]")?E.description.replace("[ADDITIONAL]","").trim():(E==null?void 0:E.description)||"N/A"}),I.some(Z=>{var O;return(O=Z==null?void 0:Z.description)==null?void 0:O.startsWith("[ADDITIONAL]")})&&((Y=E==null?void 0:E.description)!=null&&Y.startsWith("[ADDITIONAL]")?e.jsx(ae,{className:"text-[9px] h-3.5 px-1 bg-amber-100 text-amber-700 hover:bg-amber-100 border-none leading-none",children:"ADDITIONAL"}):e.jsx(ae,{className:"text-[9px] h-3.5 px-1 bg-gray-100 text-gray-600 hover:bg-gray-100 border-none leading-none",children:"ORIGINAL"}))]}),!x&&(E!=null&&E.gstRate)?e.jsxs("span",{className:"block text-[10px] text-gray-400",children:[E.gstRate,"% GST"]}):null]}),e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number(E==null?void 0:E.amount)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),!x&&e.jsxs("div",{className:"text-xs lg:text-sm text-gray-900 text-right",children:["₹",(Number(E==null?void 0:E.gstAmt)||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),e.jsxs("div",{className:"text-xs lg:text-sm font-semibold text-gray-900 text-right",children:["₹",(Number((E==null?void 0:E.totalAmt)||((E==null?void 0:E.amount)||0)*((E==null?void 0:E.quantity)||1)+((E==null?void 0:E.gstAmt)||0))||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]},(E==null?void 0:E.id)||(E==null?void 0:E.description)||W)})})]}),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(or,{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:["₹",C.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(dt,{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?S(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(Hs,{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(is,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:u,onChange:I=>g(I.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:[u.length," characters"]})]})]})}),!u.trim()&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-2 flex items-start gap-2 lg:col-span-2",children:[e.jsx(At,{className:"w-3.5 h-3.5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-amber-800",children:"Please provide comments before making a decision. Comments are required and will be visible to all participants."})]})]})]}),e.jsxs(Et,{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(M,{variant:"outline",onClick:B,disabled:f,className:"border-2 w-full sm:w-auto",children:"Cancel"}),e.jsxs("div",{className:"flex flex-col gap-2 w-full sm:w-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(M,{onClick:T,disabled:!u.trim()||f,variant:"secondary",className:"bg-amber-100 hover:bg-amber-200 text-amber-900 border border-amber-200 w-full sm:w-auto",children:f&&j==="revision"?"Requesting...":e.jsxs(e.Fragment,{children:[e.jsx(Hs,{className:"w-4 h-4 mr-2"}),"Request Revised Quotation"]})}),e.jsx(M,{onClick:P,disabled:!u.trim()||f,variant:"destructive",className:"bg-red-600 hover:bg-red-700 w-full sm:w-auto",children:f&&j==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),"Reject (Cancel Request)"]})}),e.jsx(M,{onClick:$,disabled:!u.trim()||!D||f,className:"bg-green-600 hover:bg-green-700 text-white disabled:opacity-50 disabled:cursor-not-allowed w-full sm:w-auto",title:D?"":"Please block IO budget before approving",children:f&&j==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Oe,{className:"w-4 h-4 mr-2"}),"Approve (Continue to Dept Lead)"]})})]}),!D&&e.jsx("p",{className:"text-xs text-red-600 text-center sm:text-left font-medium",children:L>0?`Pending block: ₹${R.toLocaleString("en-IN",{minimumFractionDigits:2})} more needs to be blocked in the IO Tab.`:"Please block IO budget in the IO Tab before approving."})]})]})]}),N&&e.jsx(Lr,{fileName:N.name,fileType:N.type||"",fileUrl:N.url,fileSize:N.size,attachmentId:N.id,onDownload:Ls,open:!!N,onClose:()=>_(null)})]}):null}function D5({isOpen:t,onClose:s,snapshot:a,type:r,title:n}){const[i,l]=h.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)},p=u=>{var f;const g=(f=(u||"").split(".").pop())==null?void 0:f.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"),f=u.documentId||"",b=g.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let j="";if(f)j=mn(f);else if(j=u.storageUrl||u.documentUrl||"",j&&!j.startsWith("http")){const y="https://reflow-uat.royalenfield.com",w=y.endsWith("/")?y.slice(0,-1):y,v=j.startsWith("/")?j:`/${j}`;j=`${w}${v}`}l({fileName:g,fileType:b,documentId:f,fileUrl:j,fileSize:u.sizeBytes})};return e.jsxs(e.Fragment,{children:[e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"max-w-2xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden",children:[e.jsxs(pt,{className:"px-6 py-4 border-b",children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[o?e.jsx(Ie,{className:"w-5 h-5 text-blue-600"}):e.jsx(Pt,{className:"w-5 h-5 text-green-600"}),n||(o?"Proposal Snapshot Details":"Completion Snapshot Details")]}),e.jsxs(_t,{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(dt,{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(Er,{document:{documentId:"",name:o?"Proposal Document":"Completion Document",fileType:p(a.documentUrl),uploadedAt:new Date().toISOString()},onPreview:m(a.documentUrl)?()=>x({fileName:o?"Proposal Document":"Completion Document",documentUrl:a.documentUrl}):void 0,onDownload:async()=>{let u=a.documentUrl;if(!u.startsWith("http")){const g="https://reflow-uat.royalenfield.com",f=g.endsWith("/")?g.slice(0,-1):g,b=u.startsWith("/")?u:`/${u}`;u=`${f}${b}`}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(ae,{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(Er,{document:{documentId:u.documentId||"",name:u.originalFileName||u.fileName||"Supporting Document",fileType:p(u.originalFileName||u.fileName||""),uploadedAt:u.uploadedAt||new Date().toISOString()},onPreview:m(u.originalFileName||u.fileName||"")?()=>x(u):void 0,onDownload:u.documentId?Ls:async()=>{let f=u.storageUrl||u.documentUrl;if(f&&!f.startsWith("http")){const b="https://reflow-uat.royalenfield.com",j=b.endsWith("/")?b.slice(0,-1):b,y=f.startsWith("/")?f:`/${f}`;f=`${j}${y}`}f&&window.open(f,"_blank")}},g))})]}),(a.costItems||a.expenses)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-gray-900 border-b pb-1",children:o?"Cost Breakdown":"Expenses Breakdown"}),e.jsx("div",{className:"border rounded-md overflow-hidden text-sm",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-600 text-xs uppercase",children:e.jsxs("tr",{children:[e.jsx("th",{className:"p-3 font-medium",children:"Description"}),e.jsx("th",{className:"p-3 font-medium text-right",children:"Amount"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-100",children:[(a.costItems||a.expenses).length>0?(a.costItems||a.expenses).map((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(rh,{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(M,{onClick:s,children:"Close"})})]})}),i&&e.jsx(Lr,{fileName:i.fileName,fileType:i.fileType,fileUrl:i.fileUrl,fileSize:i.fileSize,attachmentId:i.documentId,onDownload:Ls,open:!!i,onClose:()=>l(null)})]})}async function F5(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 I5(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 P5(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 E5(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 _5(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 f0(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 M5(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 L5(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 O5(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}}async function $5(t){var s;try{const a=await je.post(`/dealer-claims/${t}/wfm/retrigger`);return((s=a.data)==null?void 0:s.data)||a.data}catch(a){throw console.error("[DealerClaimAPI] Error re-triggering WFM push:",a),a}}const Br=t=>{if(!t)return"";try{return gs(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}}},U5=t=>{switch(t){case"approved":return e.jsx(Oe,{className:"w-5 h-5 text-green-600"});case"skipped":return e.jsx(Oe,{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(Oe,{className:"w-5 h-5 text-red-600"});default:return e.jsx(st,{className:"w-5 h-5 text-gray-400"})}},B5=t=>{switch(t){case"approved":return"bg-green-100 text-green-800 border-green-200";case"skipped":return"bg-green-50 text-green-700 border-green-200";case"pending":return"bg-purple-100 text-purple-800 border-purple-200";case"rejected":return"bg-red-100 text-red-800 border-red-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}},V5=(t,s)=>s&&(t==="pending"||t==="in_progress")?"border-purple-500 bg-purple-50 shadow-md":t==="approved"||t==="skipped"?"border-green-500 bg-green-50":t==="rejected"?"border-red-500 bg-red-50":"border-gray-200 bg-white",z5=t=>{switch(t){case"approved":return"bg-green-100";case"skipped":return"bg-green-100";case"pending":return"bg-purple-100";case"rejected":return"bg-red-100";default:return"bg-gray-100"}};function H5({request:t,user:s,isInitiator:a,onSkipApprover:r,onRefresh:n,documentPolicy:i}){var fr,Xa,Ta,Ja,Za,qa,er,tr,Gt,Ts,yt,xs,Os,ks,Oa,ja,sr,pn,gn,fn,Qc,Xc,Jc,Zc,qc,ed,td,sd,ad,rd,nd,id,ld,od,cd,dd,md,ud,xd,hd,pd,gd,fd,bd,jd,yd,vd,Nd,wd,Cd,Sd,Ad,Td,kd,Rd,Dd,Fd,Id,Pd,Ed,_d,Md,Ld,Od,$d,Ud,Bd,Vd,zd,Hd,Wd,Gd,Yd,Kd,Qd,Xd,Jd,Zd,qd,em,tm,sm,am,rm,nm,im,lm,om,cm,dm,mm,um,xm,hm,pm,gm,fm,bm,jm,ym,vm,Nm,wm;const[l,o]=h.useState(!1),[c,d]=h.useState(!1),[m,p]=h.useState(!1),[x,u]=h.useState(!1),[g,f]=h.useState(!1),[b,j]=h.useState(!1),[y,w]=h.useState(!1),[v,C]=h.useState(null),[A,L]=h.useState(!1),[D,R]=h.useState(null),[N,_]=h.useState([]),[S,U]=h.useState(!1),[F,$]=h.useState(new Set),[P,T]=h.useState(null),[k,B]=h.useState(null),[I,E]=h.useState(!1),[W,V]=h.useState(!1),[Y,Z]=h.useState([]),[O,z]=h.useState(0);h.useEffect(()=>{(async()=>{if(t!=null&&t.id||t!=null&&t.requestId){const Le=t.id||t.requestId;try{const be=await Es(Le),me=(be==null?void 0:be.approvalLevels)||(be==null?void 0:be.approvals)||[];if(me&&me.length>0){const fe=me.map(ue=>{var ke;return{step:ue.levelNumber||ue.level_number||0,levelNumber:ue.levelNumber||ue.level_number||0,levelName:ue.levelName||ue.level_name,approver:ue.approverName||ue.approver_name||"",approverEmail:(ue.approverEmail||ue.approver_email||"").toLowerCase(),status:((ke=ue.status)==null?void 0:ke.toLowerCase())||"waiting",tatHours:ue.tatHours||ue.tat_hours||24,elapsedHours:ue.elapsedHours||ue.elapsed_hours,approvedAt:ue.actionDate||ue.action_date,comment:ue.comments||ue.comment,levelId:ue.levelId||ue.level_id}}).sort((ue,ke)=>(ue.levelNumber||0)-(ke.levelNumber||0));Z(ue=>ue.length!==fe.length||ue.some((De,we)=>{const vt=fe[we];return!vt||De.levelNumber!==vt.levelNumber||De.levelName!==vt.levelName||De.approverEmail!==vt.approverEmail||De.status!==vt.status})?fe:ue)}else Z([])}catch(be){console.warn("Failed to load approval flows from API:",be),t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&Z(t.approvalFlow)}}else t!=null&&t.approvalFlow&&t.approvalFlow.length>0&&Z(t.approvalFlow)})()},[t==null?void 0:t.id,t==null?void 0:t.requestId,t==null?void 0:t.totalLevels,O]),h.useEffect(()=>{if(t!=null&&t.id||t!=null&&t.requestId){const H=t.id||t.requestId;(async()=>{try{const be=await Es(H),me=(be==null?void 0:be.approvalLevels)||(be==null?void 0:be.approvals)||[];if(me&&me.length>0){const fe=me.map(ue=>{var ke;return{step:ue.levelNumber||ue.level_number||0,levelNumber:ue.levelNumber||ue.level_number||0,levelName:ue.levelName||ue.level_name,approver:ue.approverName||ue.approver_name||"",approverEmail:(ue.approverEmail||ue.approver_email||"").toLowerCase(),status:((ke=ue.status)==null?void 0:ke.toLowerCase())||"waiting",tatHours:ue.tatHours||ue.tat_hours||24,elapsedHours:ue.elapsedHours||ue.elapsed_hours,approvedAt:ue.actionDate||ue.action_date,comment:ue.comments||ue.comment,levelId:ue.levelId||ue.level_id}}).sort((ue,ke)=>(ue.levelNumber||0)-(ke.levelNumber||0));Z(fe)}}catch(be){console.warn("Failed to load approval flows from API:",be)}})()}},[t==null?void 0:t.currentStep,t==null?void 0:t.totalLevels]);const K=async()=>{z(H=>H+1),await new Promise(H=>setTimeout(H,500)),n==null||n(),re()},re=async()=>{if(t!=null&&t.id||t!=null&&t.requestId)try{const Le=[...await _w(t.id||t.requestId)||[]].sort((be,me)=>new Date(me.createdAt).getTime()-new Date(be.createdAt).getTime());_(Le)}catch(H){console.warn("Failed to load version history:",H)}};h.useEffect(()=>{re()},[t==null?void 0:t.id,t==null?void 0:t.requestId,O]);const G=(H,Le,be)=>{var ue;const me=((t==null?void 0:t.totalLevels)||0)>5||(((ue=t==null?void 0:t.approvalLevels)==null?void 0:ue.length)||0)>5;if(Le&&Le.trim()&&(Le.toLowerCase().includes("additional approver")||!/^step\s+\d+$/i.test(Le)))return Le;const fe=me?{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 fe[H]?fe[H]:be&&be!=="Unknown"&&be!=="System"?`Additional Approver - ${be}`:`Additional Approver - Step ${H}`},se=(H,Le,be)=>{var ke;if(Le&&Le.toLowerCase().includes("additional approver"))return be&&be!=="Unknown"&&be!=="System"?`${be} will review and approve this request as an additional approver.`:"Additional approver will review and approve this request.";const fe=((t==null?void 0:t.totalLevels)||0)>5||(((ke=t==null?void 0:t.approvalLevels)==null?void 0:ke.length)||0)>5;if(Le&&Le.trim()){const De=Le.toLowerCase();if(De.includes("dealer")&&De.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(De.includes("requestor")&&(De.includes("evaluation")||De.includes("confirmation")))return"Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)";if(De.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(De.includes("activity creation"))return"Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.";if(De.includes("dealer")&&(De.includes("completion")||De.includes("documents")))return"Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description";if(De.includes("requestor")&&(De.includes("claim")||De.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(De.includes("e-invoice")||De.includes("invoice generation")||De.includes("dms"))return"E-Invoice will be generated upon settlement initiation.";if(De.includes("credit note")||De.includes("sap"))return"Got credit note from SAP. Review and send to dealer to complete the claim management process."}const ue=fe?{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 ue[H]?ue[H]:be&&be!=="Unknown"&&be!=="System"?`${be} will review and approve this request.`:`Step ${H} approval required.`},ve=H=>{if(!N||N.length===0||!H)return{current:null,previous:null};const me=[...N.filter(ke=>{var De;return!!(ke.levelName&&ke.levelName.trim()===H.trim()||(De=ke.snapshotData)!=null&&De.levelName&&ke.snapshotData.levelName.trim()===H.trim())})].sort((ke,De)=>{if(De.version!==ke.version)return De.version-ke.version;const we=ke.snapshotType==="APPROVE"?1:ke.snapshotType==="PROPOSAL"||ke.snapshotType==="COMPLETION"?2:3,vt=De.snapshotType==="APPROVE"?1:De.snapshotType==="PROPOSAL"||De.snapshotType==="COMPLETION"?2:3;return we-vt}).filter((ke,De,we)=>ke.snapshotType==="WORKFLOW"?!we.some(Ct=>Ct.snapshotType==="APPROVE"&&Ct.levelName===ke.levelName&&Ct.version>=ke.version):!0),fe=me.length>0?me[0]:null,ue=me.length>1?me[1]:null;return{current:fe,previous:ue,all:me}},Te=(t==null?void 0:t.currentLevel)||(t==null?void 0:t.current_level)||(t==null?void 0:t.currentStep),Ke=Te!=null?Number(Te):null,Je=((t==null?void 0:t.status)||"").toUpperCase(),Pe=Je==="REJECTED",$e=Je==="CLOSED",ne=!Pe&&!$e&&(Je==="PENDING"||Je==="IN_PROGRESS"||Je==="IN-PROGRESS"),he=Y.find(H=>{var me,fe;const Le=H.levelId||H.level_id,be=(me=t==null?void 0:t.approvals)==null?void 0:me.find(ue=>ue.levelId===Le);return((fe=be==null?void 0:be.status)==null?void 0:fe.toLowerCase())==="rejected"}),Ne=he?Number(he.levelNumber||he.level_number||he.step||0):null,Ae=Y.map((H,Le)=>{var ya,Fs,xe,ft,zt,Ns,Tt;const be=Number(H.levelNumber||H.level_number||H.step||Le+1),me=H.levelName||H.level_name,fe=(ya=t==null?void 0:t.approvals)==null?void 0:ya.find(Ue=>Ue.levelId===H.levelId);let ue;if(me&&me.toLowerCase().includes("department lead")||be===3){const Ue=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order);(Ue!=null&&Ue.ioNumber||Ue!=null&&Ue.io_number)&&(ue={ioNumber:Ue.ioNumber||Ue.io_number||"",blockedAmount:Ue.ioBlockedAmount||Ue.io_blocked_amount||0,availableBalance:Ue.ioAvailableBalance||Ue.io_available_balance||0,remainingBalance:Ue.ioRemainingBalance||Ue.io_remaining_balance||0,organizedBy:((Fs=Ue.organizer)==null?void 0:Fs.displayName)||((xe=Ue.organizer)==null?void 0:xe.name)||Ue.organizedBy||H.approver||"N/A",organizedAt:Ue.organizedAt||Ue.organized_at||H.approvedAt||(t==null?void 0:t.updatedAt)||""})}let De;be===6&&(fe!=null&&fe.dmsDetails?De={dmsNumber:fe.dmsDetails.dmsNumber||"",dmsRemarks:fe.dmsDetails.dmsRemarks||"",pushedBy:fe.dmsDetails.pushedBy||H.approver,pushedAt:fe.dmsDetails.pushedAt||H.approvedAt||""}:t!=null&&t.dmsNumber&&(De={dmsNumber:t.dmsNumber||"",dmsRemarks:t.dmsRemarks||((ft=t.dmsDetails)==null?void 0:ft.dmsRemarks)||"",pushedBy:H.approver,pushedAt:H.approvedAt||t.updatedAt||""}));let we;if(Pe||$e)((zt=fe==null?void 0:fe.status)==null?void 0:zt.toLowerCase())==="rejected"?we="rejected":Ne!==null&&be>Ne?we="waiting":((Ns=fe==null?void 0:fe.status)==null?void 0:Ns.toLowerCase())==="approved"?we="approved":Ne!==null&&beKe,we="waiting");else if(ne&&Ke!==null&&Ke>0)if(be>Ke)we="waiting";else if(beLe.step===Ke):null;Q=H&&(H.status==="pending"||H.status==="in_progress")?H:Ae.find(Le=>{var me;const be=((me=Le.status)==null?void 0:me.toLowerCase())||"";return be==="pending"||be==="in_progress"||be==="in-review"||be==="in_review"}),le=Q?Q.step:Ke||(t==null?void 0:t.currentStep)||1}else le=Ke||(t==null?void 0:t.currentStep)||1;const pe=((fr=s==null?void 0:s.email)==null?void 0:fr.toLowerCase())||"",ge=((Xa=t==null?void 0:t.dealerEmail)==null?void 0:Xa.toLowerCase())||((Ja=(Ta=t==null?void 0:t.dealer)==null?void 0:Ta.email)==null?void 0:Ja.toLowerCase())||((qa=(Za=t==null?void 0:t.claimDetails)==null?void 0:Za.dealerEmail)==null?void 0:qa.toLowerCase())||((tr=(er=t==null?void 0:t.claimDetails)==null?void 0:er.dealer_email)==null?void 0:tr.toLowerCase())||"",Fe=ge&&pe===ge,_e=Y.find(H=>(H.step||H.levelNumber||H.level_number)===le),Xe=((_e==null?void 0:_e.approverEmail)||"").toLowerCase(),lt=Xe&&pe===Xe,Nt=((Ts=(Gt=t==null?void 0:t.initiator)==null?void 0:Gt.email)==null?void 0:Ts.toLowerCase())||((yt=t==null?void 0:t.initiatorEmail)==null?void 0:yt.toLowerCase())||"",wt=Y.find(H=>{const Le=(H.approverEmail||"").toLowerCase(),be=(H.levelName||"").toLowerCase();return Nt&&Le===Nt||be.includes("requestor evaluation")||be.includes("requestor")&&be.includes("confirmation")}),As=wt&&(wt.step||wt.levelNumber||wt.level_number)||2,ie=wt||Y.find(H=>(H.step||H.levelNumber||H.level_number)===2),Re=((ie==null?void 0:ie.approverEmail)||"").toLowerCase(),ce=Re&&pe===Re,Ve=Y.find(H=>(H.step||H.levelNumber||H.level_number)===1),Be=((Ve==null?void 0:Ve.approverEmail)||"").toLowerCase(),tt=Be&&pe===Be,ze=Y.find(H=>(H.levelName||"").toLowerCase().includes("department lead")),rt=((ze==null?void 0:ze.approverEmail)||"").toLowerCase(),qe=rt&&pe===rt,ot=async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId;H.proposalDocument&&await Rn(H.proposalDocument,me,"APPROVAL");for(const ue of H.otherDocuments)await Rn(ue,me,"SUPPORTING");const fe=H.costBreakup.reduce((ue,ke)=>ue+(ke.totalAmt||ke.amount||0),0);await P5(me,{proposalDocument:H.proposalDocument||void 0,costBreakup:H.costBreakup.map(ue=>({description:ue.description,amount:ue.amount,gstRate:ue.gstRate,gstAmt:ue.gstAmt,cgstRate:ue.cgstRate,cgstAmt:ue.cgstAmt,sgstRate:ue.sgstRate,sgstAmt:ue.sgstAmt,igstRate:ue.igstRate,igstAmt:ue.igstAmt,utgstRate:ue.utgstRate,utgstAmt:ue.utgstAmt,cessRate:ue.cessRate,cessAmt:ue.cessAmt,totalAmt:ue.totalAmt,quantity:ue.quantity,hsnCode:ue.hsnCode,isService:ue.isService})),totalEstimatedBudget:fe,expectedCompletionDate:H.expectedCompletionDate,dealerComments:H.dealerComments}),X.success("Proposal submitted successfully"),K()}catch(me){console.error("Failed to submit proposal:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to submit proposal. Please try again.";throw X.error(fe),me}},Us=async H=>{var Le,be,me,fe,ue;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ke=t.id||t.requestId,De=await Es(ke),we=(De==null?void 0:De.approvalLevels)||(De==null?void 0:De.approvals)||[],vt=((be=(Le=t==null?void 0:t.initiator)==null?void 0:Le.email)==null?void 0:be.toLowerCase())||((me=t==null?void 0:t.initiatorEmail)==null?void 0:me.toLowerCase())||"",Ct=we.find(kt=>{const ya=(kt.approverEmail||kt.approver_email||"").toLowerCase(),Fs=(kt.levelName||kt.level_name||"").toLowerCase(),xe=kt.levelNumber||kt.level_number;return vt&&ya===vt||Fs.includes("requestor evaluation")||Fs.includes("requestor")&&Fs.includes("confirmation")||xe===As})||we.find(kt=>(kt.levelNumber||kt.level_number)===2);if(!(Ct!=null&&Ct.levelId)&&!(Ct!=null&&Ct.level_id))throw new Error("Initiator approval level not found");const Rs=Ct.levelId||Ct.level_id;await Tn(ke,Rs,H),X.success("Proposal approved successfully"),K()}catch(ke){console.error("Failed to approve proposal:",ke);const De=((ue=(fe=ke==null?void 0:ke.response)==null?void 0:fe.data)==null?void 0:ue.message)||(ke==null?void 0:ke.message)||"Failed to approve proposal. Please try again.";throw X.error(De),ke}},rs=async H=>{var Le,be,me,fe,ue;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ke=t.id||t.requestId,De=await Es(ke),we=(De==null?void 0:De.approvalLevels)||(De==null?void 0:De.approvals)||[],vt=((be=(Le=t==null?void 0:t.initiator)==null?void 0:Le.email)==null?void 0:be.toLowerCase())||((me=t==null?void 0:t.initiatorEmail)==null?void 0:me.toLowerCase())||"",Ct=we.find(kt=>{const ya=(kt.approverEmail||kt.approver_email||"").toLowerCase(),Fs=(kt.levelName||kt.level_name||"").toLowerCase(),xe=kt.levelNumber||kt.level_number;return vt&&ya===vt||Fs.includes("requestor evaluation")||Fs.includes("requestor")&&Fs.includes("confirmation")||xe===As})||we.find(kt=>(kt.levelNumber||kt.level_number)===2);if(!(Ct!=null&&Ct.levelId)&&!(Ct!=null&&Ct.level_id))throw new Error("Initiator approval level not found");const Rs=Ct.levelId||Ct.level_id;await wr(ke,Rs,"Proposal rejected by requestor",H),X.success("Proposal rejected. Request has been cancelled."),K()}catch(ke){console.error("Failed to reject proposal:",ke);const De=((ue=(fe=ke==null?void 0:ke.response)==null?void 0:fe.data)==null?void 0:ue.message)||(ke==null?void 0:ke.message)||"Failed to reject proposal. Please try again.";throw X.error(De),ke}},gt=async H=>{var Le,be,me,fe,ue;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const ke=t.id||t.requestId,De=await Es(ke),we=(De==null?void 0:De.approvalLevels)||(De==null?void 0:De.approvals)||[],vt=((be=(Le=t==null?void 0:t.initiator)==null?void 0:Le.email)==null?void 0:be.toLowerCase())||((me=t==null?void 0:t.initiatorEmail)==null?void 0:me.toLowerCase())||"",Ct=we.find(kt=>{const ya=(kt.approverEmail||kt.approver_email||"").toLowerCase(),Fs=(kt.levelName||kt.level_name||"").toLowerCase(),xe=kt.levelNumber||kt.level_number;return vt&&ya===vt||Fs.includes("requestor evaluation")||Fs.includes("requestor")&&Fs.includes("confirmation")||xe===As})||we.find(kt=>(kt.levelNumber||kt.level_number)===2);if(!(Ct!=null&&Ct.levelId)&&!(Ct!=null&&Ct.level_id))throw new Error("Initiator approval level not found");const Rs=Ct.levelId||Ct.level_id;await wr(ke,Rs,"Revised Quotation Requested",H),X.success("Revision requested. Request returned to dealer."),K()}catch(ke){console.error("Failed to request revision:",ke);const De=((ue=(fe=ke==null?void 0:ke.response)==null?void 0:fe.data)==null?void 0:ue.message)||(ke==null?void 0:ke.message)||"Failed to request revision. Please try again.";throw X.error(De),ke}},ct=async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=await Es(me),ke=((fe==null?void 0:fe.approvalLevels)||(fe==null?void 0:fe.approvals)||[]).find(we=>{const vt=(we.levelName||we.level_name||"").toLowerCase();return vt.includes("requestor claim")||vt.includes("requestor - claim")});if(!(ke!=null&&ke.levelId)&&!(ke!=null&&ke.level_id))throw new Error("Claim approval level not found");const De=ke.levelId||ke.level_id;await wr(me,De,"Revised Quotation Requested",H),X.success("Re-quotation requested. Request returned to dealer."),K()}catch(me){console.error("Failed to request re-quotation:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to request re-quotation. Please try again.";throw X.error(fe),me}},Dt=async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=await Es(me),ue=(fe==null?void 0:fe.approvalLevels)||(fe==null?void 0:fe.approvals)||[],ke=ue.find(we=>(we.levelName||we.level_name||"").toLowerCase().includes("department lead"))||ue.find(we=>(we.levelNumber||we.level_number)===3);if(!(ke!=null&&ke.levelId)&&!(ke!=null&&ke.level_id))throw new Error("Department Lead approval level not found");const De=ke.levelId||ke.level_id;await f0(me,{ioNumber:H.ioNumber}),await Tn(me,De,H.comments),X.success("Request approved and IO organized successfully"),K()}catch(me){console.error("Failed to approve and organize IO:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to approve request. Please try again.";throw X.error(fe),me}},vs=async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=H.closedExpenses.map(ue=>({description:ue.description,amount:ue.amount,gstRate:ue.gstRate,gstAmt:ue.gstAmt,cgstRate:ue.cgstRate,cgstAmt:ue.cgstAmt,sgstRate:ue.sgstRate,sgstAmt:ue.sgstAmt,igstRate:ue.igstRate,igstAmt:ue.igstAmt,utgstRate:ue.utgstRate,utgstAmt:ue.utgstAmt,cessRate:ue.cessRate,cessAmt:ue.cessAmt,totalAmt:ue.totalAmt,quantity:ue.quantity,hsnCode:ue.hsnCode,isService:ue.isService}));if(await E5(me,{activityCompletionDate:H.activityCompletionDate,numberOfParticipants:H.numberOfParticipants,closedExpenses:fe,totalClosedExpenses:H.totalClosedExpenses,completionDocuments:H.completionDocuments,activityPhotos:H.activityPhotos,completionDescription:H.completionDescription}),H.invoicesReceipts&&H.invoicesReceipts.length>0)for(const ue of H.invoicesReceipts)await Rn(ue,me,"SUPPORTING");H.attendanceSheet&&await Rn(H.attendanceSheet,me,"SUPPORTING"),X.success("Completion documents submitted successfully"),K()}catch(me){console.error("Failed to submit completion documents:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to submit completion documents. Please try again.";throw X.error(fe),me}},ts=async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=new Date().toISOString().slice(0,10);await M5(me,{eInvoiceDate:fe}),X.success("E-Invoice generation initiated successfully."),K()}catch(me){console.error("[DealerClaimWorkflowTab] Error generating e-invoice:",me);let ue=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"E-Invoice generation failed. Please try again.";throw ue.length>300&&(ue=ue.substring(0,300)+"..."),X.error(ue),me}},Sa=async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=await Es(me),ue=(fe==null?void 0:fe.approvalLevels)||(fe==null?void 0:fe.approvals)||[],ke=ue.find(we=>(we.levelName||we.level_name||"").toLowerCase().includes("department lead"))||ue.find(we=>(we.levelNumber||we.level_number)===3);if(!(ke!=null&&ke.levelId)&&!(ke!=null&&ke.level_id))throw new Error("Department Lead approval level not found");const De=ke.levelId||ke.level_id;await wr(me,De,"Dept Lead rejected - More clarification required",H),X.success("Request rejected. Request has been cancelled."),K()}catch(me){console.error("Failed to reject request:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to reject request. Please try again.";throw X.error(fe),me}},[Ma,Aa]=h.useState(null);h.useEffect(()=>{if(!t){Aa(null);return}(async()=>{try{const Le=t.id||t.requestId;if(!Le){Aa(null);return}const be=await Es(Le),me=(be==null?void 0:be.documents)||[],fe=t.proposalDetails||(be==null?void 0:be.proposalDetails)||{},ue=me.find(we=>we.category==="APPROVAL"||we.type==="proposal"||we.documentCategory==="APPROVAL"),ke=me.filter(we=>we.category==="SUPPORTING"||we.type==="supporting"||we.documentCategory==="SUPPORTING");let De=fe.costBreakup||[];if(typeof De=="string")try{De=JSON.parse(De)}catch(we){console.warn("Failed to parse costBreakup JSON:",we),De=[]}Array.isArray(De)||(De=[]),Aa({proposalDocument:ue?{name:ue.fileName||ue.file_name||ue.name,id:ue.documentId||ue.document_id||ue.id}:void 0,costBreakup:De,expectedCompletionDate:fe.expectedCompletionDate||"",otherDocuments:ke.map(we=>({name:we.fileName||we.file_name||we.name,id:we.documentId||we.document_id||we.id})),dealerComments:fe.dealerComments||"",submittedAt:fe.submittedAt})}catch(Le){console.warn("Failed to load proposal data:",Le);const be=t.proposalDetails||{};let me=be.costBreakup||[];if(typeof me=="string")try{me=JSON.parse(me)}catch(fe){console.warn("Failed to parse costBreakup JSON:",fe),me=[]}Array.isArray(me)||(me=[]),Aa({proposalDocument:void 0,costBreakup:me,expectedCompletionDate:be.expectedCompletionDate||"",otherDocuments:[],dealerComments:be.dealerComments||"",submittedAt:be.submittedAt})}})()},[t]);const[Ya,Ft]=h.useState(null);h.useEffect(()=>{if(!t){Ft(null);return}(async()=>{try{const Le=t.id||t.requestId;if(!Le){Ft(null);return}const be=await Es(Le),me=(be==null?void 0:be.documents)||[],fe=[],ue=[],ke=[];let De=null;me.forEach(we=>{const vt=(we.category||we.documentCategory||we.type||"").toUpperCase(),Ct=(we.fileName||we.file_name||we.name||"").toLowerCase(),Rs={name:we.fileName||we.file_name||we.name,id:we.documentId||we.document_id||we.id,url:we.url||we.storageUrl||we.storage_url};vt==="COMPLETION"||vt==="COMPLETION_DOCUMENT"?fe.push(Rs):vt==="ACTIVITY_PHOTO"||vt==="PHOTO"||vt==="IMAGE"?ue.push(Rs):vt==="ATTENDANCE"||vt==="ATTENDANCE_SHEET"?De=Rs:(vt==="SUPPORTING"||vt==="INVOICE"||vt==="RECEIPT")&&(!De&&(Ct.includes("attendance")||Ct.includes("participant"))?De=Rs:ke.push(Rs))}),fe.length===0&&ue.length===0&&t.completionDetails,Ft({completionDocuments:fe,activityPhotos:ue,invoicesReceipts:ke,attendanceSheet:De})}catch(Le){console.warn("Failed to load completion documents:",Le),Ft(null)}})()},[t]);const La=async()=>{try{X.loading("Retriggering WFM push...",{id:"wfm-retrigger"}),await $5(t.id),X.success("WFM push re-triggered successfully",{id:"wfm-retrigger"}),n?n():window.location.reload()}catch(H){console.error("Error retriggering WFM push:",H),X.error(H.message||"Failed to re-trigger WFM push",{id:"wfm-retrigger"})}},Bs=async()=>{try{const H=t.id||t.requestId;if(!H){X.error("Request ID not found");return}const be=await fetch(`https://reflow-uat.royalenfield.com/api/v1//dealer-claims/${H}/e-invoice/csv`,{headers:{Authorization:`Bearer ${at.getAccessToken()||""}`},credentials:"include"});if(!be.ok)throw new Error("Failed to download CSV");const me=await be.blob(),fe=window.URL.createObjectURL(me),ue=document.createElement("a");ue.href=fe,ue.download=`Invoice_${t.requestNumber||"Export"}.csv`,document.body.appendChild(ue),ue.click(),window.URL.revokeObjectURL(fe),document.body.removeChild(ue),X.success("CSV downloaded successfully")}catch(H){console.error("Error downloading CSV:",H),X.error("Failed to download CSV")}},Or=async()=>{try{const H=t.id||t.requestId;if(!H){X.error("Request ID not found");return}if(!t.invoice&&!t.irn){X.error("Invoice not generated yet");return}V(!0),E(!0);const be=await fetch(`https://reflow-uat.royalenfield.com/api/v1//dealer-claims/${H}/e-invoice/pdf`,{headers:{Authorization:`Bearer ${at.getAccessToken()||""}`},credentials:"include"});if(!be.ok)throw new Error("Failed to fetch invoice PDF");const me=await be.blob(),fe=window.URL.createObjectURL(me);k&&window.URL.revokeObjectURL(k),B(fe)}catch(H){console.error("Failed to preview invoice:",H),X.error("Failed to load invoice preview"),E(!1)}finally{V(!1)}},pr=()=>{E(!1),k&&(window.URL.revokeObjectURL(k),B(null))},$r=()=>{if(k){const H=document.createElement("a");H.href=k,H.download=`Invoice_${t.requestNumber||"Download"}.pdf`,document.body.appendChild(H),H.click(),document.body.removeChild(H),X.success("Invoice PDF downloaded")}},Ka=((xs=t==null?void 0:t.claimDetails)==null?void 0:xs.dealerName)||((Os=t==null?void 0:t.dealerInfo)==null?void 0:Os.name)||"Dealer",gr=((ks=t==null?void 0:t.claimDetails)==null?void 0:ks.dealerGstin)||((Oa=t==null?void 0:t.dealerInfo)==null?void 0:Oa.gstin)||((ja=t==null?void 0:t.dealerInfo)==null?void 0:ja.dealerGSTIN),Qa=((sr=t==null?void 0:t.claimDetails)==null?void 0:sr.activityName)||((pn=t==null?void 0:t.activityInfo)==null?void 0:pn.activityName)||(t==null?void 0:t.title)||"Activity";return e.jsxs(e.Fragment,{children:[e.jsxs(q,{children:[e.jsx(oe,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Ws,{className:"w-5 h-5 text-purple-600"}),"Claim Management Workflow"]}),e.jsx(ye,{className:"mt-2",children:"Approval process for dealer claim management"})]})})}),e.jsxs(ee,{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(es,{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:Ae.map((H,Le)=>{var Ct,Rs,kt,ya,Fs;const me=(((Ct=H.status)==null?void 0:Ct.toLowerCase())||"")==="in_progress",fe=H.step===le,ue=ne&&me&&fe,ke=H.status==="approved"||H.status==="skipped",De=Y.find(xe=>(xe.step||xe.levelNumber||xe.level_number)===H.step),we=De!=null&&De.levelId?(Rs=t==null?void 0:t.approvals)==null?void 0:Rs.find(xe=>xe.levelId===De.levelId||xe.level_id===De.levelId):null,vt=(we==null?void 0:we.status)==="PAUSED"||((kt=t==null?void 0:t.pauseInfo)==null?void 0:kt.isPaused)&&(((ya=t==null?void 0:t.pauseInfo)==null?void 0:ya.levelId)===(we==null?void 0:we.levelId)||((Fs=t==null?void 0:t.pauseInfo)==null?void 0:Fs.level_id)===(we==null?void 0:we.levelId));return e.jsx("div",{className:`relative p-5 rounded-lg border-2 transition-all ${V5(H.status,ue)}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`p-3 rounded-xl ${z5(H.status)}`,children:U5(H.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:H.title}),e.jsx(ae,{className:B5(H.status),children:H.status.toLowerCase()}),H.emailTemplateUrl&&H.status==="approved"&&e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-blue-100",title:"View email template",onClick:()=>{C({stepNumber:H.step,stepName:H.title}),w(!0)},children:e.jsx(fa,{className:"w-3.5 h-3.5 text-blue-600"})}),H.step===7&&H.einvoiceUrl&&ke&&e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-green-100",title:"Download E-Invoice",onClick:()=>window.open(H.einvoiceUrl,"_blank"),children:e.jsx(Rt,{className:"w-3.5 h-3.5 text-green-600"})}),(()=>{const xe=(H.levelName||H.title||"").toLowerCase().includes("requestor claim")||(H.levelName||H.title||"").toLowerCase().includes("requestor - claim"),ft=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&H.status==="approved";return xe&&ft&&e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-amber-100",title:"Preview Invoice",onClick:Or,children:e.jsx(Pt,{className:"w-3.5 h-3.5 text-amber-600"})})})(),(()=>{var Tt,Ue,ws,Bt;const xe=(H.levelName||H.title||"").toLowerCase().includes("requestor claim")||(H.levelName||H.title||"").toLowerCase().includes("requestor - claim"),ft=(t==null?void 0:t.invoice)||(t==null?void 0:t.irn)&&H.status==="approved",zt=((Tt=t==null?void 0:t.invoice)==null?void 0:Tt.wfmPushStatus)||((Ue=t==null?void 0:t.invoice)==null?void 0:Ue.wfmPushStatus),Ns=((ws=t==null?void 0:t.invoice)==null?void 0:ws.wfmPushError)||((Bt=t==null?void 0:t.invoice)==null?void 0:Bt.wfmPushError);return xe&&ft&&e.jsxs("div",{className:"flex items-center gap-1 ml-1",children:[e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-emerald-100",title:"Export CSV",onClick:Bs,children:e.jsx(uh,{className:"w-3.5 h-3.5 text-emerald-600"})}),zt==="SUCCESS"?e.jsx("div",{title:"Pushed to WFM successfully",children:e.jsx(us,{className:"w-3.5 h-3.5 text-green-500"})}):zt==="FAILED"?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{title:`WFM Push Failed: ${Ns||"Unknown error"}`,children:e.jsx(At,{className:"w-3.5 h-3.5 text-red-500"})}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-5 px-1.5 text-[10px] text-red-600 hover:text-red-700 hover:bg-red-50 border border-red-200 h-auto py-0",onClick:La,children:"Retry Push"})]}):e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{title:"WFM Push Pending",children:e.jsx(st,{className:"w-3.5 h-3.5 text-amber-500"})}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-5 px-1.5 text-[10px] text-amber-600 hover:text-amber-700 hover:bg-amber-50 border border-amber-200 h-auto py-0",onClick:La,children:"Push Now"})]})]})})()]}),e.jsx("p",{className:"text-sm text-gray-600",children:H.approver}),e.jsx("p",{className:"text-sm text-gray-500 mt-2 italic",children:H.description})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["TAT: ",Kt(H.tatHours)]}),H.elapsedHours&&(ue||ke)&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:["Elapsed: ",Kt(H.elapsedHours)]})]})]}),H.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:H.comment})}),H.versionHistory&&H.versionHistory.all&&H.versionHistory.all.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsxs(M,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs text-amber-700 hover:text-amber-800 hover:bg-amber-50",onClick:()=>{const xe=new Set(F);xe.has(H.step)?xe.delete(H.step):xe.add(H.step),$(xe)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ph,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"font-medium",children:"Version History"}),H.versionHistory.all&&H.versionHistory.all.length>0&&e.jsxs(ae,{className:"bg-amber-100 text-amber-800 text-[10px] px-1.5 py-0",children:[H.versionHistory.all.length," Versions"]})]}),F.has(H.step)?e.jsx(Hi,{className:"w-4 h-4"}):e.jsx(rn,{className:"w-4 h-4"})]}),F.has(H.step)&&H.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:H.versionHistory.all.map((xe,ft)=>{var zt,Ns,Tt,Ue;return e.jsxs("div",{className:`space-y-2 ${ft>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(ae,{className:`${ft===0?"bg-amber-500":"bg-gray-400"} text-white text-[10px] px-2 py-0.5`,children:[ft===0?"Current":"Previous",": v",xe.version]}),e.jsx("span",{className:"text-[10px] text-gray-600 font-medium",children:Br(xe.createdAt)})]})}),e.jsx("p",{className:"text-xs text-gray-700 font-medium",children:xe.changeReason||"Version Update"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:`w-3 h-3 rounded-full ${ft===0?"bg-blue-100":"bg-gray-100"} flex items-center justify-center`,children:e.jsx("span",{className:`text-[8px] font-bold ${ft===0?"text-blue-600":"text-gray-600"}`,children:((Ns=(zt=xe.changer)==null?void 0:zt.displayName)==null?void 0:Ns.charAt(0))||"U"})}),e.jsxs("span",{className:"text-[10px] text-gray-600",children:["By ",((Tt=xe.changer)==null?void 0:Tt.displayName)||((Ue=xe.changer)==null?void 0:Ue.email)||"Unknown User"]})]}),xe.snapshotType==="PROPOSAL"&&xe.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(xe.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:xe.snapshotData,type:"PROPOSAL",title:`Proposal (v${xe.version})`}),children:[e.jsx(St,{className:"w-3 h-3"}),"View Details"]})]}),xe.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",xe.snapshotData.comments]})]}),xe.snapshotType==="INTERNAL_ORDER"&&xe.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: ",xe.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["Blocked Amount: ₹",Number(xe.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),xe.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-[10px] text-gray-600",children:["SAP Doc: ",xe.snapshotData.sapDocumentNumber]})]}),xe.snapshotType==="COMPLETION"&&xe.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(xe.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:xe.snapshotData,type:"COMPLETION",title:`Completion (v${xe.version})`}),children:[e.jsx(St,{className:"w-3 h-3"}),"View Details"]})]}),xe.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1 line-clamp-2",children:["Comments: ",xe.snapshotData.comments]})]}),xe.snapshotType==="APPROVE"&&xe.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:[xe.snapshotData.action==="APPROVE"?"Approval":"Rejection"," Snapshot:"]}),e.jsxs("p",{className:"text-[10px] text-gray-600",children:["By: ",xe.snapshotData.approverName||xe.snapshotData.approverEmail||"Unknown"]}),xe.snapshotData.comments&&e.jsxs("p",{className:"text-[10px] text-gray-600 mt-1",children:["Comments: ",xe.snapshotData.comments.substring(0,100),xe.snapshotData.comments.length>100?"...":""]}),xe.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-[10px] text-red-600 mt-1",children:["Rejection Reason: ",xe.snapshotData.rejectionReason.substring(0,100),xe.snapshotData.rejectionReason.length>100?"...":""]})]}),xe.snapshotType==="WORKFLOW"&&xe.snapshotData&&xe.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:[xe.snapshotData.comments.substring(0,100),xe.snapshotData.comments.length>100?"...":""]})]})]},ft)})})]}),ue&&(we==null?void 0:we.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:we.sla.deadline?wa(we.sla.deadline,!0):"Not set"})]}),e.jsxs("div",{className:`border rounded-lg p-3 ${vt?"bg-gray-100 border-gray-300":(we.sla.percentageUsed||0)>=100?"bg-red-50 border-red-200":(we.sla.percentageUsed||0)>=75?"bg-orange-50 border-orange-200":(we.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 ",vt&&"(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:we.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:[we.sla.elapsedText||"0 hours"," / ",Kt(H.tatHours)," allocated"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[(()=>{const xe=we.sla.percentageUsed||0,ft=()=>vt?"bg-gray-500":xe>=100?"bg-red-600":xe>=75?"bg-orange-500":xe>=50?"bg-amber-500":"bg-green-600",zt=()=>vt?"text-gray-600":xe>=100?"text-red-600":xe>=75?"text-orange-600":xe>=50?"text-amber-600":"text-green-600";return e.jsxs(e.Fragment,{children:[e.jsx(qs,{value:xe,className:"h-3",indicatorClassName:ft()}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`text-xs font-semibold ${zt()}`,children:["Progress: ",Math.min(100,xe),"% of TAT used"]}),e.jsxs("span",{className:"text-xs font-medium text-gray-700",children:[we.sla.remainingText||"0 hours"," remaining"]})]})]})})(),we.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(Di,{className:"w-4 h-4"}),"Deadline Breached"]}),we.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(es,{className:"w-4 h-4"}),"Approaching Deadline"]})]})]})]}),(()=>{const xe=H.levelName||H.level_name;return(xe&&xe.toLowerCase().includes("department lead")||H.title&&H.title.toLowerCase().includes("department lead"))&&H.status==="approved"&&H.ioDetails&&H.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(Pt,{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:H.ioDetails.ioNumber})]}),H.ioDetails.blockedAmount!==void 0&&H.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:["₹",H.ioDetails.blockedAmount.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),H.ioDetails.remainingBalance!==void 0&&H.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:["₹",H.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 ",H.ioDetails.organizedBy||H.approver||"N/A"," on"," ",H.ioDetails.organizedAt?Br(H.ioDetails.organizedAt):H.approvedAt?Br(H.approvedAt):"N/A"]})]})]})})(),H.step===6&&H.dmsDetails&&H.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($t,{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:H.dmsDetails.dmsNumber})]}),H.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:H.dmsDetails.dmsRemarks})]}),H.dmsDetails.pushedAt&&e.jsxs("div",{className:"pt-1.5 border-t border-purple-100 text-xs text-gray-500",children:["Initiated by ",H.dmsDetails.pushedBy," on"," ",Br(H.dmsDetails.pushedAt)]})]})]}),(()=>{const xe=Y.find(Ue=>(Ue.step||Ue.levelNumber||Ue.level_number)===H.step),ft=((xe==null?void 0:xe.approverEmail)||"").toLowerCase(),zt=ft&&pe===ft,Ns=H.step===1||(xe==null?void 0:xe.levelName)&&xe.levelName.toLowerCase().includes("dealer");return ue&&(zt||Ns&&Fe)})()&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[(()=>{const xe=((De==null?void 0:De.levelName)||H.title||"").toLowerCase();return(H.step===1||xe.includes("proposal")||xe.includes("submission"))&&(Fe||tt)})()&&e.jsxs(M,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{o(!0)},children:[e.jsx(js,{className:"w-4 h-4 mr-2"}),"Submit Proposal"]}),(()=>{const xe=((De==null?void 0:De.levelName)||H.title||"").toLowerCase();return(xe.includes("requestor evaluation")||xe.includes("confirmation")||H.step===As)&&(a||ce)})()&&e.jsxs(M,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{d(!0)},children:[e.jsx(Oe,{className:"w-4 h-4 mr-2"}),"Review Request"]}),(()=>{const xe=Y.find(Ue=>(Ue.step||Ue.levelNumber||Ue.level_number)===H.step);if(!((xe==null?void 0:xe.levelName)||H.title||"").toLowerCase().includes("initiator action")||!(a||pe===Nt))return null;const Tt=async Ue=>{var ws,Bt;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Is=t.requestId||t.id;await mp(Is,Ue,{reason:""}),X.success(`Action "${Ue==="REVISE"?"Revision Requested":"Request Reopened"}" performed successfully`),K()}catch(Is){console.error("Failed to perform initiator action:",Is);const O0=((Bt=(ws=Is==null?void 0:Is.response)==null?void 0:ws.data)==null?void 0:Bt.message)||(Is==null?void 0:Is.message)||"Failed to perform action";X.error(O0)}};return e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(M,{variant:"outline",className:"border-orange-500 text-orange-600 hover:bg-orange-50",onClick:()=>Tt("REVISE"),children:[e.jsx(Ut,{className:"w-4 h-4 mr-2"}),"Request Re-quotation"]}),e.jsxs(M,{variant:"outline",className:"border-blue-500 text-blue-600 hover:bg-blue-50",onClick:()=>Tt("REOPEN"),children:[e.jsx(oh,{className:"w-4 h-4 mr-2"}),"Reopen"]})]})})(),(()=>{const xe=Y.find(Bt=>(Bt.levelName||"").toLowerCase().includes("department lead"));if(!(xe&&H.step===(xe.step||xe.levelNumber||xe.level_number)))return null;const zt=((xe==null?void 0:xe.approverEmail)||"").toLowerCase();if(!(zt&&pe===zt||qe||lt))return null;const Tt=(t==null?void 0:t.internalOrder)||(t==null?void 0:t.internal_order),Ue=(Tt==null?void 0:Tt.ioNumber)||(Tt==null?void 0:Tt.io_number)||(t==null?void 0:t.ioNumber)||"",ws=Ue&&Ue.trim()!=="";return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(M,{className:"bg-green-600 hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>{p(!0)},disabled:!ws,children:[e.jsx(Oe,{className:"w-4 h-4 mr-2"}),"Review and Approve"]}),!ws&&e.jsx("p",{className:"text-xs text-amber-600",children:"Please add an IO number in the IO tab before approving this step."})]})})(),(()=>{const xe=Y.find(Ue=>(Ue.step||Ue.levelNumber||Ue.level_number)===H.step),ft=((xe==null?void 0:xe.approverEmail)||"").toLowerCase(),zt=Fe&&ft===ge,Ns=((xe==null?void 0:xe.levelName)||H.title||"").toLowerCase(),Tt=Ns.includes("dealer completion")||Ns.includes("completion documents");return zt&&Tt})()&&e.jsxs(M,{className:"bg-purple-600 hover:bg-purple-700",onClick:()=>{u(!0)},children:[e.jsx(js,{className:"w-4 h-4 mr-2"}),"Upload Completion Docs"]}),(()=>{const xe=Y.find(Tt=>{const Ue=(Tt.levelName||"").toLowerCase();return Ue.includes("requestor claim")||Ue.includes("requestor - claim")});if(!(xe&&H.step===(xe.step||xe.levelNumber||xe.level_number)))return null;const zt=((xe==null?void 0:xe.approverEmail)||"").toLowerCase();return a||zt&&pe===zt?e.jsxs(M,{className:"bg-indigo-600 hover:bg-indigo-700",onClick:()=>{f(!0)},children:[e.jsx($t,{className:"w-4 h-4 mr-2"}),"Generate E-Invoice & Sync"]}):null})(),(()=>{var ws;const xe=((De==null?void 0:De.levelName)||H.title||"").toLowerCase(),ft=xe.includes("credit note")||xe.includes("sap")||H.step===8&&!xe.includes("additional"),zt=((De==null?void 0:De.approverEmail)||"").toLowerCase(),Ns=zt&&pe===zt,Tt=((ws=s==null?void 0:s.role)==null?void 0:ws.toUpperCase())||"";return ft&&(Ns||(Tt==="FINANCE"||Tt==="ADMIN"))})()&&e.jsxs(M,{className:"bg-green-600 hover:bg-green-700",onClick:()=>{j(!0)},children:[e.jsx(Pt,{className:"w-4 h-4 mr-2"}),"View & Send Credit Note"]}),(()=>{const xe=Y.find(Tt=>(Tt.step||Tt.levelNumber||Tt.level_number)===H.step),ft=((xe==null?void 0:xe.levelName)||H.title||"").toLowerCase(),zt=ft.includes("additional approver"),Ns=H.step===1||ft.includes("proposal")||ft.includes("submission")||ft.includes("requestor evaluation")||ft.includes("confirmation")||ft.includes("department lead")||ft.includes("dealer completion")||ft.includes("completion documents")||ft.includes("requestor claim")||ft.includes("requestor - claim")||ft.includes("credit note")||ft.includes("sap");if(zt||!Ns){const Tt=(xe==null?void 0:xe.levelId)||(xe==null?void 0:xe.level_id);if(Tt){const Ue=(xe==null?void 0:xe.levelName)||(xe==null?void 0:xe.level_name)||H.title||"Approval Level",ws=(xe==null?void 0:xe.approverName)||(xe==null?void 0:xe.approver_name)||H.approver||"Approver";return e.jsxs(M,{className:"bg-blue-600 hover:bg-blue-700",onClick:()=>{R({levelId:Tt,levelName:Ue,approverName:ws}),L(!0)},children:[e.jsx(Oe,{className:"w-4 h-4 mr-2"}),"Review Request"]})}return e.jsxs(e.Fragment,{children:[e.jsxs(M,{className:"bg-green-600 hover:bg-green-700",onClick:async()=>{var Ue,ws;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Bt=t.id||t.requestId;if(!Tt){X.error("Approval level not found");return}await Tn(Bt,Tt,""),X.success("Request approved successfully"),K()}catch(Bt){console.error("Failed to approve:",Bt);const Is=((ws=(Ue=Bt==null?void 0:Bt.response)==null?void 0:Ue.data)==null?void 0:ws.message)||(Bt==null?void 0:Bt.message)||"Failed to approve request. Please try again.";X.error(Is)}},children:[e.jsx(Oe,{className:"w-4 h-4 mr-2"}),"Approve"]}),e.jsxs(M,{variant:"destructive",onClick:async()=>{var Ue,ws;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const Bt=t.id||t.requestId;if(!Tt){X.error("Approval level not found");return}const Is=prompt("Please provide a reason for rejection:");if(Is===null)return;await wr(Bt,Tt,"Request rejected",Is),X.success("Request rejected successfully"),K()}catch(Bt){console.error("Failed to reject:",Bt);const Is=((ws=(Ue=Bt==null?void 0:Bt.response)==null?void 0:Ue.data)==null?void 0:ws.message)||(Bt==null?void 0:Bt.message)||"Failed to reject request. Please try again.";X.error(Is)}},children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),"Reject"]})]})}return null})()]}),H.approvedAt&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Approved on ",Br(H.approvedAt)]})]})]})},Le)})})]})]}),e.jsx(S5,{isOpen:l,onClose:()=>o(!1),onSubmit:ot,dealerName:Ka,dealerGSTIN:gr,activityName:Qa,defaultGstRate:(gn=t==null?void 0:t.claimDetails)==null?void 0:gn.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),previousProposalData:(fn=N==null?void 0:N.find(H=>H.snapshotType==="PROPOSAL"))==null?void 0:fn.snapshotData,documentPolicy:i,taxationType:(Qc=t==null?void 0:t.claimDetails)==null?void 0:Qc.taxationType,totalBlockedAmount:((t==null?void 0:t.internalOrders)||[]).reduce((H,Le)=>H+Number(Le.ioBlockedAmount||Le.io_blocked_amount||Le.blockedAmount||0),0)}),e.jsx(R5,{isOpen:c,onClose:()=>{d(!1)},onApprove:Us,onReject:rs,onRequestRevision:gt,proposalData:Ma,dealerName:Ka,activityName:Qa,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),request:t,previousProposalData:(()=>{const H=(N==null?void 0:N.filter(Le=>Le.snapshotType==="PROPOSAL"))||[];return H.length>1?H[1].snapshotData:null})(),taxationType:(Xc=t==null?void 0:t.claimDetails)==null?void 0:Xc.taxationType}),e.jsx(A5,{isOpen:m,onClose:()=>p(!1),onApprove:Dt,onReject:Sa,requestTitle:t==null?void 0:t.title,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),preFilledIONumber:((Jc=t==null?void 0:t.internalOrder)==null?void 0:Jc.ioNumber)||((Zc=t==null?void 0:t.internalOrder)==null?void 0:Zc.io_number)||((qc=t==null?void 0:t.internal_order)==null?void 0:qc.ioNumber)||((ed=t==null?void 0:t.internal_order)==null?void 0:ed.io_number)||void 0,preFilledBlockedAmount:((td=t==null?void 0:t.internalOrder)==null?void 0:td.ioBlockedAmount)||((sd=t==null?void 0:t.internalOrder)==null?void 0:sd.io_blocked_amount)||((ad=t==null?void 0:t.internal_order)==null?void 0:ad.ioBlockedAmount)||((rd=t==null?void 0:t.internal_order)==null?void 0:rd.io_blocked_amount)||void 0,preFilledRemainingBalance:((nd=t==null?void 0:t.internalOrder)==null?void 0:nd.ioRemainingBalance)||((id=t==null?void 0:t.internalOrder)==null?void 0:id.io_remaining_balance)||((ld=t==null?void 0:t.internal_order)==null?void 0:ld.ioRemainingBalance)||((od=t==null?void 0:t.internal_order)==null?void 0:od.io_remaining_balance)||void 0,taxationType:(cd=t==null?void 0:t.claimDetails)==null?void 0:cd.taxationType}),e.jsx(C5,{isOpen:x,onClose:()=>u(!1),onSubmit:vs,dealerName:Ka,dealerGSTIN:gr,activityName:Qa,defaultGstRate:(dd=t==null?void 0:t.claimDetails)==null?void 0:dd.defaultGstRate,requestId:(t==null?void 0:t.id)||(t==null?void 0:t.requestId),documentPolicy:i,taxationType:(md=t==null?void 0:t.claimDetails)==null?void 0:md.taxationType}),e.jsx(T5,{isOpen:g,onClose:()=>f(!1),onPush:ts,completionDetails:{activityCompletionDate:((ud=t==null?void 0:t.completionDetails)==null?void 0:ud.activityCompletionDate)||((xd=t==null?void 0:t.completionDetails)==null?void 0:xd.activity_completion_date),numberOfParticipants:((hd=t==null?void 0:t.completionDetails)==null?void 0:hd.numberOfParticipants)||((pd=t==null?void 0:t.completionDetails)==null?void 0:pd.number_of_participants),closedExpenses:(t==null?void 0:t.completionExpenses)||(t==null?void 0:t.completion_expenses)||((gd=t==null?void 0:t.completionDetails)==null?void 0:gd.closedExpenses)||((fd=t==null?void 0:t.completionDetails)==null?void 0:fd.closed_expenses),totalClosedExpenses:((bd=t==null?void 0:t.budgetTracking)==null?void 0:bd.closedExpenses)||((jd=t==null?void 0:t.budgetTracking)==null?void 0:jd.closed_expenses)||((yd=t==null?void 0:t.completionDetails)==null?void 0:yd.totalClosedExpenses)||((vd=t==null?void 0:t.completionDetails)==null?void 0:vd.total_closed_expenses),completionDescription:((Nd=t==null?void 0:t.completionDetails)==null?void 0:Nd.completionDescription)||((wd=t==null?void 0:t.completionDetails)==null?void 0:wd.completion_description)},ioDetails:{ioNumber:((Cd=t==null?void 0:t.internalOrder)==null?void 0:Cd.ioNumber)||((Sd=t==null?void 0:t.internalOrder)==null?void 0:Sd.io_number)||((Ad=t==null?void 0:t.internal_order)==null?void 0:Ad.ioNumber)||((Td=t==null?void 0:t.internal_order)==null?void 0:Td.io_number),blockedAmount:((kd=t==null?void 0:t.internalOrder)==null?void 0:kd.ioBlockedAmount)||((Rd=t==null?void 0:t.internalOrder)==null?void 0:Rd.io_blocked_amount)||((Dd=t==null?void 0:t.internal_order)==null?void 0:Dd.ioBlockedAmount)||((Fd=t==null?void 0:t.internal_order)==null?void 0:Fd.io_blocked_amount),availableBalance:((Id=t==null?void 0:t.internalOrder)==null?void 0:Id.ioAvailableBalance)||((Pd=t==null?void 0:t.internalOrder)==null?void 0:Pd.io_available_balance)||((Ed=t==null?void 0:t.internal_order)==null?void 0:Ed.ioAvailableBalance)||((_d=t==null?void 0:t.internal_order)==null?void 0:_d.io_available_balance),remainingBalance:((Md=t==null?void 0:t.internalOrder)==null?void 0:Md.ioRemainingBalance)||((Ld=t==null?void 0:t.internalOrder)==null?void 0:Ld.io_remaining_balance)||((Od=t==null?void 0:t.internal_order)==null?void 0:Od.ioRemainingBalance)||(($d=t==null?void 0:t.internal_order)==null?void 0:$d.io_remaining_balance)},completionDocuments:Ya,requestTitle:t==null?void 0:t.title,requestNumber:(t==null?void 0:t.requestNumber)||(t==null?void 0:t.request_number)||(t==null?void 0:t.id),taxationType:(Ud=t==null?void 0:t.claimDetails)==null?void 0:Ud.taxationType,onReQuotation:ct}),e.jsx(b5,{isOpen:b,onClose:()=>j(!1),taxationType:(Bd=t==null?void 0:t.claimDetails)==null?void 0:Bd.taxationType,onDownload:async()=>{X.info("Download functionality will be implemented")},onSendToDealer:async()=>{var H,Le;try{const be=(t==null?void 0:t.requestId)||(t==null?void 0:t.id);if(!be){X.error("Request ID not found");return}await L5(be),X.success("Credit note sent to dealer successfully. Step 8 has been approved."),n&&n()}catch(be){console.error("Failed to send credit note to dealer:",be);const me=((Le=(H=be==null?void 0:be.response)==null?void 0:H.data)==null?void 0:Le.message)||(be==null?void 0:be.message)||"Failed to send credit note to dealer";X.error(me)}},creditNoteData:{creditNoteNumber:((Vd=t==null?void 0:t.creditNote)==null?void 0:Vd.creditNoteNumber)||((zd=t==null?void 0:t.creditNote)==null?void 0:zd.credit_note_number)||((Wd=(Hd=t==null?void 0:t.claimDetails)==null?void 0:Hd.creditNote)==null?void 0:Wd.creditNoteNumber)||((Gd=t==null?void 0:t.claimDetails)==null?void 0:Gd.creditNoteNumber)||((Yd=t==null?void 0:t.claimDetails)==null?void 0:Yd.credit_note_number),creditNoteDate:((Kd=t==null?void 0:t.creditNote)==null?void 0:Kd.creditNoteDate)||((Qd=t==null?void 0:t.creditNote)==null?void 0:Qd.credit_note_date)||((Jd=(Xd=t==null?void 0:t.claimDetails)==null?void 0:Xd.creditNote)==null?void 0:Jd.creditNoteDate)||((Zd=t==null?void 0:t.claimDetails)==null?void 0:Zd.creditNoteDate)||((qd=t==null?void 0:t.claimDetails)==null?void 0:qd.credit_note_date),creditNoteAmount:(em=t==null?void 0:t.creditNote)!=null&&em.creditNoteAmount?Number((tm=t==null?void 0:t.creditNote)==null?void 0:tm.creditNoteAmount):(sm=t==null?void 0:t.creditNote)!=null&&sm.credit_note_amount?Number((am=t==null?void 0:t.creditNote)==null?void 0:am.credit_note_amount):(nm=(rm=t==null?void 0:t.claimDetails)==null?void 0:rm.creditNote)!=null&&nm.creditNoteAmount?Number((lm=(im=t==null?void 0:t.claimDetails)==null?void 0:im.creditNote)==null?void 0:lm.creditNoteAmount):(om=t==null?void 0:t.claimDetails)!=null&&om.creditNoteAmount?Number((cm=t==null?void 0:t.claimDetails)==null?void 0:cm.creditNoteAmount):(dm=t==null?void 0:t.claimDetails)!=null&&dm.credit_note_amount?Number((mm=t==null?void 0:t.claimDetails)==null?void 0:mm.credit_note_amount):void 0,status:((um=t==null?void 0:t.creditNote)==null?void 0:um.status)||((hm=(xm=t==null?void 0:t.claimDetails)==null?void 0:xm.creditNote)==null?void 0:hm.status)||((pm=t==null?void 0:t.creditNote)!=null&&pm.creditNoteNumber?"CONFIRMED":"PENDING")},dealerInfo:{dealerName:((gm=t==null?void 0:t.claimDetails)==null?void 0:gm.dealerName)||((fm=t==null?void 0:t.claimDetails)==null?void 0:fm.dealer_name),dealerCode:((bm=t==null?void 0:t.claimDetails)==null?void 0:bm.dealerCode)||((jm=t==null?void 0:t.claimDetails)==null?void 0:jm.dealer_code),dealerEmail:((ym=t==null?void 0:t.claimDetails)==null?void 0:ym.dealerEmail)||((vm=t==null?void 0:t.claimDetails)==null?void 0:vm.dealer_email)},activityName:((Nm=t==null?void 0:t.claimDetails)==null?void 0:Nm.activityName)||((wm=t==null?void 0:t.claimDetails)==null?void 0:wm.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(k5,{isOpen:y,onClose:()=>{w(!1),C(null)},stepNumber:(v==null?void 0:v.stepNumber)||4,stepName:(v==null?void 0:v.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(f5,{isOpen:A,onClose:()=>{L(!1),R(null)},onApprove:async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=D.levelId;if(!fe){X.error("Approval level not found");return}await Tn(me,fe,H),X.success("Request approved successfully"),K(),L(!1),R(null)}catch(me){console.error("Failed to approve:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to approve request. Please try again.";throw X.error(fe),me}},onReject:async H=>{var Le,be;try{if(!(t!=null&&t.id)&&!(t!=null&&t.requestId))throw new Error("Request ID not found");const me=t.id||t.requestId,fe=D.levelId;if(!fe){X.error("Approval level not found");return}await wr(me,fe,"Request rejected",H),X.success("Request rejected successfully"),K(),L(!1),R(null)}catch(me){console.error("Failed to reject:",me);const fe=((be=(Le=me==null?void 0:me.response)==null?void 0:Le.data)==null?void 0:be.message)||(me==null?void 0:me.message)||"Failed to reject request. Please try again.";throw X.error(fe),me}},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(q,{className:"mt-6 border-amber-100 bg-amber-50/30",children:[e.jsxs(oe,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(de,{className:"text-sm font-bold flex items-center gap-2 text-amber-900",children:[e.jsx($t,{className:"w-4 h-4"}),"Revision History & Audit Trail"]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>U(!S),className:"text-amber-700 hover:text-amber-800 hover:bg-amber-100",children:S?"Hide History":"View History"})]}),e.jsx(ye,{className:"text-xs text-amber-700",children:"Records of all revisions and actions taken on this request"})]}),S&&e.jsx(ee,{children:e.jsx("div",{className:"space-y-4",children:N.map((H,Le)=>{var be,me,fe,ue;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 ",H.version]}),H.snapshotType&&e.jsx(ae,{className:"bg-blue-100 text-blue-700 text-[9px] px-1.5 py-0",children:H.snapshotType}),H.levelNumber&&e.jsxs(ae,{className:"bg-gray-100 text-gray-600 text-[9px] px-1.5 py-0",children:["Step ",H.levelNumber]})]}),e.jsx("span",{className:"text-[10px] text-amber-600 font-medium bg-amber-100 px-2 py-0.5 rounded-full",children:Br(H.createdAt)})]}),e.jsx("p",{className:"text-xs font-medium text-gray-800",children:H.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:((me=(be=H.changer)==null?void 0:be.displayName)==null?void 0:me.charAt(0))||"U"})}),e.jsxs("span",{className:"text-xs text-gray-500",children:["By ",((fe=H.changer)==null?void 0:fe.displayName)||((ue=H.changer)==null?void 0:ue.email)||"Unknown User"]})]}),H.snapshotType==="PROPOSAL"&&H.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:"}),H.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(M,{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:H.snapshotData,type:"PROPOSAL",title:`Historical Proposal (Version ${H.version})`}),children:["View Details",e.jsx(St,{className:"w-2 h-2"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Budget: ₹",Number(H.snapshotData.totalBudget||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),H.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",H.snapshotData.comments.substring(0,80),H.snapshotData.comments.length>80?"...":""]})]}),H.snapshotType==="COMPLETION"&&H.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:"}),H.snapshotData.documentUrl&&e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsxs(M,{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:H.snapshotData,type:"COMPLETION",title:`Historical Completion (Version ${H.version})`}),children:["View Details",e.jsx(St,{className:"w-3 h-3"})]})}),e.jsxs("p",{className:"text-gray-600",children:["Total Expenses: ₹",Number(H.snapshotData.totalExpenses||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),H.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",H.snapshotData.comments.substring(0,80),H.snapshotData.comments.length>80?"...":""]})]}),H.snapshotType==="INTERNAL_ORDER"&&H.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: ",H.snapshotData.ioNumber||"N/A"]}),e.jsxs("p",{className:"text-gray-600",children:["Blocked: ₹",Number(H.snapshotData.blockedAmount||0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]}),H.snapshotData.sapDocumentNumber&&e.jsxs("p",{className:"text-gray-600",children:["SAP Doc: ",H.snapshotData.sapDocumentNumber]})]}),H.snapshotType==="APPROVE"&&H.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:[H.snapshotData.action==="APPROVE"?"Approval":"Rejection",":"]}),e.jsxs("p",{className:"text-gray-600",children:["By: ",H.snapshotData.approverName||H.snapshotData.approverEmail||"Unknown"]}),H.snapshotData.levelName&&e.jsxs("p",{className:"text-gray-600",children:["Level: ",H.snapshotData.levelName]}),H.snapshotData.comments&&e.jsxs("p",{className:"text-gray-600 mt-1",children:["Comments: ",H.snapshotData.comments.substring(0,80),H.snapshotData.comments.length>80?"...":""]}),H.snapshotData.rejectionReason&&e.jsxs("p",{className:"text-red-600 mt-1",children:["Rejection Reason: ",H.snapshotData.rejectionReason.substring(0,80),H.snapshotData.rejectionReason.length>80?"...":""]})]}),H.snapshotType==="WORKFLOW"&&H.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: ",H.snapshotData.status||"N/A"]}),H.snapshotData.currentLevel&&e.jsxs("p",{className:"text-gray-600",children:["Current Level: ",H.snapshotData.currentLevel]})]})]})]},H.historyId||Le)})})})]}),e.jsx(D5,{isOpen:!!P,onClose:()=>T(null),snapshot:P==null?void 0:P.data,type:(P==null?void 0:P.type)||"PROPOSAL",title:P==null?void 0:P.title}),I&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/60",onClick:pr}),e.jsxs("div",{className:"relative w-[95vw] max-w-5xl h-[90vh] bg-white rounded-xl shadow-2xl flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b bg-gray-50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-5 h-5 text-amber-600"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Invoice Preview"}),e.jsx(ae,{className:"bg-amber-100 text-amber-800 text-xs",children:t.requestNumber})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[k&&e.jsxs(M,{variant:"outline",size:"sm",onClick:$r,className:"gap-1.5 text-xs",children:[e.jsx(Rt,{className:"w-3.5 h-3.5"}),"Download"]}),e.jsx(M,{variant:"ghost",size:"icon",onClick:pr,className:"h-8 w-8 hover:bg-gray-200",children:e.jsx(jt,{className:"w-4 h-4"})})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden",children:W?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3",children:[e.jsx(Qe,{className:"w-8 h-8 text-amber-600 animate-spin"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading invoice..."})]}):k?e.jsx("iframe",{src:k,className:"w-full h-full border-0",title:"Invoice PDF Preview"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Failed to load invoice"})})})]})]})]})}function W5({request:t,apiRequest:s,onRefresh:a}){const{user:r}=cs(),n=(s==null?void 0:s.requestId)||(t==null?void 0:t.requestId),i=(s==null?void 0:s.proposalDetails)||{},l=(s==null?void 0:s.claimDetails)||s||{},c=h.useMemo(()=>{const _=(i==null?void 0:i.costBreakup)||(l==null?void 0:l.costBreakup)||[],S=Array.isArray(_)?_:typeof _=="string"?JSON.parse(_):[];return!Array.isArray(S)||S.length===0?Number((l==null?void 0:l.totalProposedTaxableAmount)||(i==null?void 0:i.totalEstimatedBudget)||(i==null?void 0:i.total_estimated_budget)||0):S.reduce((U,F)=>{const $=typeof F=="object"&&F.amount||0,P=typeof F=="object"&&F.quantity||1;return U+Number($)*Number(P)},0)},[i==null?void 0:i.costBreakup,l==null?void 0:l.costBreakup,l==null?void 0:l.totalProposedTaxableAmount,i==null?void 0:i.totalEstimatedBudget]),d=(s==null?void 0:s.budgetTracking)||(t==null?void 0:t.budgetTracking)||{},m=(d==null?void 0:d.budgetStatus)||(d==null?void 0:d.budget_status)||"",p=(s==null?void 0:s.internalOrders)||(s==null?void 0:s.internal_orders)||(t==null?void 0:t.internalOrders)||[],x=m==="PROPOSED"&&p.length>0,[u,g]=h.useState(""),[f,b]=h.useState(!1),[j,y]=h.useState(null),[w,v]=h.useState(""),[C,A]=h.useState([]),[L,D]=h.useState(!1);h.useEffect(()=>{if(p.length>0){const _=p.map(S=>{const U=S.organizer||null,F=(U==null?void 0:U.displayName)||(U==null?void 0:U.display_name)||(U==null?void 0:U.name)||(U!=null&&U.firstName&&(U!=null&&U.lastName)?`${U.firstName} ${U.lastName}`.trim():null)||(U==null?void 0:U.email)||"Unknown User";return{ioNumber:S.ioNumber||S.io_number,blockedAmount:Number(S.ioBlockedAmount||S.io_blocked_amount||0),availableBalance:Number(S.ioAvailableBalance||S.io_available_balance||0),remainingBalance:Number(S.ioRemainingBalance||S.io_remaining_balance||0),blockedDate:S.organizedAt||S.organized_at||new Date().toISOString(),blockedBy:F,sapDocumentNumber:S.sapDocumentNumber||S.sap_document_number||"",status:S.status==="BLOCKED"?"blocked":S.status==="RELEASED"?"released":S.status==="PENDING"?"pending":"blocked"}});A(_),!x&&_.length>0&&g(_[_.length-1].ioNumber)}},[s,t,x,p]);const R=async()=>{var _,S;if(!u.trim()){X.error("Please enter an IO number");return}if(!n){X.error("Request ID not found");return}b(!0);try{const U=await _5(n,u.trim());if(U.isValid&&U.availableBalance>0){y(U.availableBalance);const F=C.reduce((P,T)=>P+T.blockedAmount,0),$=Math.max(0,c-F);$>0?v(String($.toFixed(2))):c>0&&F===0?v(String(c.toFixed(2))):v(String(U.availableBalance.toFixed(2))),X.success(`IO fetched from SAP. Available balance: ₹${U.availableBalance.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`)}else X.error("Invalid IO number or no available balance found"),y(null),v("")}catch(U){console.error("Failed to fetch IO budget:",U);const F=((S=(_=U==null?void 0:U.response)==null?void 0:_.data)==null?void 0:S.message)||(U==null?void 0:U.message)||"Failed to validate IO number or fetch budget from SAP";X.error(F),y(null)}finally{b(!1)}},N=async()=>{var $,P;if(!u.trim()||j===null){X.error("Please fetch IO amount first");return}if(!n){X.error("Request ID not found");return}const _=parseFloat(w);if(!w||isNaN(_)||_<=0){X.error("Please enter a valid amount to block");return}const S=parseFloat(_.toFixed(2));if(S>j){X.error("Amount to block exceeds available IO budget");return}const F=C.reduce((T,k)=>T+k.blockedAmount,0)+S;if(c>0){const T=parseFloat(c.toFixed(2)),k=parseFloat(F.toFixed(2));if(Math.abs(k-T)>.01){X.error(`Total blocked amount (₹${k.toLocaleString("en-IN")}) must be exactly equal to the estimated budget (₹${T.toLocaleString("en-IN")})`);return}}D(!0);try{const T=parseFloat(j.toFixed(2)),k=parseFloat((T-S).toFixed(2)),B={ioNumber:u.trim(),ioAvailableBalance:T,ioBlockedAmount:S,ioRemainingBalance:k};await f0(n,B);const I=await I5(n),E=(I==null?void 0:I.internalOrder)||(I==null?void 0:I.internal_order);if(E){const W=Number(E.ioBlockedAmount||E.io_blocked_amount||S),V=Number(E.ioRemainingBalance||E.io_remaining_balance||0),Y=j-W;Math.abs(W-S)>.01&&console.warn("[IOTab] ⚠️ Amount mismatch! Sent:",S,"Saved:",W),Math.abs(V-Y)>.01&&console.warn("[IOTab] ⚠️ Remaining balance calculation issue detected!",{availableBalance:j,blockedAmount:W,expectedRemaining:Y,backendRemaining:V,difference:V-Y});const Z=r,O=(Z==null?void 0:Z.displayName)||(Z==null?void 0:Z.display_name)||(Z==null?void 0:Z.name)||(Z!=null&&Z.firstName&&(Z!=null&&Z.lastName)?`${Z.firstName} ${Z.lastName}`.trim():null)||(Z==null?void 0:Z.email)||"Current User",z={ioNumber:E.ioNumber||E.io_number||u,blockedAmount:W,availableBalance:j,remainingBalance:V,blockedDate:E.organizedAt||E.organized_at||new Date().toISOString(),blockedBy:O,sapDocumentNumber:E.sapDocumentNumber||E.sap_document_number||"",status:"blocked"};A(K=>[...K,z]),v(""),y(null),X.success("IO budget blocked successfully in SAP"),a==null||a()}else X.error("IO blocked but failed to fetch updated details"),a==null||a()}catch(T){console.error("Failed to block IO budget:",T);const k=((P=($=T==null?void 0:T.response)==null?void 0:$.data)==null?void 0:P.message)||(T==null?void 0:T.message)||"Failed to block IO budget in SAP";X.error(k)}finally{D(!1)}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"w-5 h-5 text-[#2d4a3e]"}),"IO Budget Management"]}),e.jsx(ye,{children:"Enter IO number to fetch available budget from SAP"})]}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(te,{htmlFor:"ioNumber",children:"IO Number *"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ce,{id:"ioNumber",placeholder:"Enter IO number (e.g., IO-2024-12345)",value:u,onChange:_=>g(_.target.value),disabled:f||C.length>0&&!x,className:"flex-1"}),e.jsxs(M,{onClick:R,disabled:!u.trim()||f||C.length>0&&!x,className:"bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(Rt,{className:"w-4 h-4 mr-2"}),f?"Fetching...":"Fetch Amount"]})]})]}),!j&&C.length===0&&u.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.']})}),j!==null&&(C.length===0||x)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-green-50 border-2 border-green-200 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600 uppercase tracking-wide mb-1",children:"Available Amount"}),e.jsxs("p",{className:"text-2xl font-bold text-green-700",children:["₹",j.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),e.jsx(Oe,{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:"})," ",u]}),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(te,{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(Ce,{type:"number",id:"blockAmount",placeholder:"Enter amount to block",min:"0",step:"0.01",value:w,onChange:_=>v(_.target.value),className:"pl-8"})]}),c>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:["₹",c.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]}),e.jsxs(M,{onClick:N,disabled:L||!w||parseFloat(w)<=0||parseFloat(w)>j||c>0&&Math.abs(C.reduce((_,S)=>_+S.blockedAmount,0)+parseFloat(w)-c)>.01,className:"w-full bg-[#2d4a3e] hover:bg-[#1f3329]",children:[e.jsx(qt,{className:"w-4 h-4 mr-2"}),L?"Blocking in SAP...":"Block IO in SAP"]})]})]})]}),e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Oe,{className:"w-5 h-5 text-green-600"}),"IO Blocked Details"]}),e.jsx(ye,{children:"Details of IO blocked in SAP system"})]}),e.jsx(ee,{children:C.length>0?e.jsxs("div",{className:"space-y-6",children:[x&&e.jsx("div",{className:"bg-amber-50 border-2 border-amber-500 rounded-lg p-4 animate-pulse",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ze,{className:"w-6 h-6 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-amber-900",children:"Additional Budget Blocking Required"}),e.jsxs("p",{className:"text-sm text-amber-700 mt-1",children:["Actual expenses exceed the previously blocked amount. Please block an additional ₹",(c-C.reduce((_,S)=>_+S.blockedAmount,0)).toLocaleString("en-IN",{minimumFractionDigits:2}),"."]})]})]})}),C.slice().reverse().map((_,S)=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:`p-3 flex justify-between items-center ${S===0?"bg-green-50":"bg-gray-50"}`,children:[e.jsxs("span",{className:"font-semibold text-sm",children:["IO: ",_.ioNumber]}),e.jsx(ae,{className:_.status==="blocked"?"bg-green-100 text-green-800":_.status==="pending"?"bg-amber-100 text-amber-800":"bg-blue-100 text-blue-800",children:_.status==="blocked"?"Blocked":_.status==="pending"?"Provisioned":"Released"})]}),e.jsxs("div",{className:"grid grid-cols-2 divide-x divide-y",children:[e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Amount"}),e.jsxs("p",{className:"text-sm font-bold text-green-700",children:["₹",_.blockedAmount.toLocaleString("en-IN")]})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"SAP Doc"}),e.jsx("p",{className:"text-sm font-medium",children:_.sapDocumentNumber||"N/A"})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Blocked By"}),e.jsx("p",{className:"text-xs",children:_.blockedBy})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Date"}),e.jsx("p",{className:"text-[10px]",children:new Date(_.blockedDate).toLocaleString()})]})]})]},S)),e.jsxs("div",{className:"mt-4 p-4 bg-[#2d4a3e] text-white rounded-lg flex justify-between items-center",children:[e.jsx("span",{className:"font-bold",children:"Total Blocked:"}),e.jsxs("span",{className:"text-xl font-bold",children:["₹",C.reduce((_,S)=>_+S.blockedAmount,0).toLocaleString("en-IN",{minimumFractionDigits:2})]})]})]}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ha,{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 G5(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)}}async function Y5(t){var s;try{const a=await je.get(`/dealers-external/search/${t}`);return((s=a.data)==null?void 0:s.data)||a.data||null}catch(a){return console.error("[DealerAPI] Error searching external dealer:",a),null}}const Ks=[{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 K5({formData:t,updateFormData:s,onValidationError:a,currentUserEmail:r="",currentUserId:n="",currentUserName:i="",onValidate:l,maxApprovalLevels:o,onPolicyViolation:c}){const{userSearchResults:d,userSearchLoading:m,searchUsersForIndex:p,clearSearchForIndex:x}=Xg(),[u,g]=h.useState(!1),[f,b]=h.useState(""),[j,y]=h.useState(24),[w,v]=h.useState("hours"),[C,A]=h.useState(3),[L,D]=h.useState([]),[R,N]=h.useState(!1),[_,S]=h.useState(null),U=h.useRef(null),F=()=>{const O=t.approvers||[],z=[];return Ks.forEach(K=>{if(K.isAuto||K.approverType==="dealer"||K.approverType==="initiator")return;const re=O.find(G=>G.level===K.level);(!re||!re.email||!re.userId||!re.tat)&&z.push(`${K.name}`)}),{isValid:z.length===0,missingSteps:z}};h.useEffect(()=>{if(l){const O=F();l(O.isValid)}},[t.approvers]),h.useEffect(()=>{const O=t.approvers||[];if(O.length>0){const z=[],K=O.filter(G=>G.isAdditional);Ks.forEach(G=>{const se=O.find(ve=>ve.originalStepLevel===G.level||!ve.originalStepLevel&&!ve.isAdditional&&ve.level===G.level);if(se)z.push(se);else if(G.isAuto){const ve=G.level===8?"finance@royalenfield.com":"system@royalenfield.com",Te=G.level===8?"System/Finance":"System";z.push({email:ve,name:Te,level:G.level,tat:G.defaultTat,tatType:"hours",originalStepLevel:G.level})}else G.approverType==="dealer"?z.push({email:t.dealerEmail||"",name:t.dealerName||"",level:G.level,tat:G.defaultTat,tatType:"hours",originalStepLevel:G.level}):G.approverType==="initiator"?z.push({email:r||"",name:i||r||"User",userId:n,level:G.level,tat:G.defaultTat,tatType:"hours",originalStepLevel:G.level}):z.push({email:"",name:"",level:G.level,tat:G.defaultTat,tatType:"hours",originalStepLevel:G.level})}),K.forEach(G=>{z.push(G)}),z.sort((G,se)=>G.level-se.level),JSON.stringify(O.map(G=>({level:G.level,originalStepLevel:G.originalStepLevel})))!==JSON.stringify(z.map(G=>({level:G.level,originalStepLevel:G.originalStepLevel})))&&s("approvers",z)}else{const z=[];Ks.forEach(K=>{K.isAuto||(K.approverType==="dealer"?z.push({email:t.dealerEmail||"",name:t.dealerName||"",level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level}):K.approverType==="initiator"?z.push({email:r||"",name:i||r||"User",userId:n,level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level}):z.push({email:"",name:"",level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level}))}),s("approvers",z)}},[t.dealerEmail,t.dealerName,r,n,i]);const $=(O,z)=>{const K=[...t.approvers||[]],re=K.findIndex(G=>G.originalStepLevel===O||!G.originalStepLevel&&G.level===O&&!G.isAdditional);if(re===-1){const G=Ks.find(se=>se.level===O);K.push({email:z,name:"",level:O,tat:(G==null?void 0:G.defaultTat)||48,tatType:"hours",originalStepLevel:O})}else{const G=K[re];if(G){const se=G.email;K[re]={...G,email:z,name:z!==se?"":G.name,userId:z!==se?void 0:G.userId}}}if(s("approvers",K),!z||!z.startsWith("@")||z.length<2){x(O-1);return}p(O-1,z,10)},P=async(O,z)=>{var K,re;try{const G=Ks.find(Pe=>Pe.level===O);if(G&&!G.isAuto&&G.approverType!=="initiator"&&((K=z.email)==null?void 0:K.toLowerCase())===(r==null?void 0:r.toLowerCase())){X.error(`You cannot assign yourself as ${G.name} approver.`),a&&a({type:"self-assign",email:z.email,message:`You cannot assign yourself as ${G.name} approver.`});return}if((t.approvers||[]).some(Pe=>{var $e,ne;return Pe.level!==O&&(Pe.userId===z.userId||(($e=Pe.email)==null?void 0:$e.toLowerCase())===((ne=z.email)==null?void 0:ne.toLowerCase()))})){X.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 Te=await ga({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}),Ke=[...t.approvers||[]],Je=Ke.findIndex(Pe=>Pe.originalStepLevel===O||!Pe.originalStepLevel&&Pe.level===O&&!Pe.isAdditional);if(Je===-1){const Pe=Ks.find($e=>$e.level===O);Ke.push({email:z.email,name:z.displayName||[z.firstName,z.lastName].filter(Boolean).join(" "),userId:Te.userId,level:O,tat:(Pe==null?void 0:Pe.defaultTat)||48,tatType:"hours",originalStepLevel:O})}else{const Pe=Ke[Je];Pe&&(Ke[Je]={...Pe,email:z.email,name:z.displayName||[z.firstName,z.lastName].filter(Boolean).join(" "),userId:Te.userId,originalStepLevel:Pe.originalStepLevel||O})}s("approvers",Ke),x(O-1),X.success(`Approver for ${(re=Ks.find(Pe=>Pe.level===O))==null?void 0:re.name} selected successfully.`)}catch(G){console.error("Failed to ensure user exists:",G),X.error("Failed to validate user. Please try again."),a&&a({type:"error",email:z.email,message:"Failed to validate user. Please try again."})}},T=(O,z)=>{const K=[...t.approvers||[]],re=K.findIndex(G=>G.originalStepLevel===O||!G.originalStepLevel&&G.level===O&&!G.isAdditional);if(re!==-1){const G=K[re];G&&(K[re]={...G,tat:z},s("approvers",K))}},k=(O,z)=>{const K=[...t.approvers||[]],re=K.findIndex(G=>G.originalStepLevel===O||!G.originalStepLevel&&G.level===O&&!G.isAdditional);if(re!==-1){const G=K[re];G&&(K[re]={...G,tatType:z,tat:""},s("approvers",K))}},B=O=>{if(b(O),_&&_.email.toLowerCase()!==O.toLowerCase()&&S(null),U.current&&clearTimeout(U.current),!O||!O.startsWith("@")||O.length<2){D([]),N(!1);return}N(!0),U.current=setTimeout(async()=>{var z;try{const K=O.slice(1),G=((z=(await ba(K,10)).data)==null?void 0:z.data)||[];D(G)}catch(K){console.error("Search failed:",K),D([])}finally{N(!1)}},300)},I=async O=>{try{await ga({userId:O.userId,email:O.email,displayName:O.displayName,firstName:O.firstName,lastName:O.lastName,department:O.department,phone:O.phone,mobilePhone:O.mobilePhone,designation:O.designation,jobTitle:O.jobTitle,manager:O.manager,employeeId:O.employeeId,employeeNumber:O.employeeNumber,secondEmail:O.secondEmail,location:O.location}),b(O.email),S(O),D([]),N(!1)}catch(z){console.error("Failed to ensure user exists:",z),X.error("Failed to verify user. Please try again.")}},E=async()=>{var $e,ne;const O=f.trim().toLowerCase();if(!O){X.error("Please enter an email address");return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(O)){X.error("Please enter a valid email address");return}const K=typeof j=="string"?Number(j):j;if(!K||K<=0||isNaN(K)){X.error("Please enter valid TAT (minimum 1)");return}const re=w==="days"?30:720;if((w==="days"?K*24:K)>720){X.error(`TAT cannot exceed ${re} ${w==="days"?"days":"hours"}`);return}const se=Ks.find(he=>he.name==="Requestor Claim Approval");if(se&&C>=se.level){X.error('Additional approvers cannot be added after "Requestor Claim Approval" as it is considered final.');return}if(O===(r==null?void 0:r.toLowerCase())){X.error("You cannot add yourself as an additional approver.");return}const ve=t.approvers||[];if(ve.some(he=>{var Ne;return he.userId&&(_==null?void 0:_.userId)&&he.userId===_.userId||((Ne=he.email)==null?void 0:Ne.toLowerCase())===O})){X.error("This user is already assigned as an approver.");return}const Ke=ve.find(he=>he.originalStepLevel===C||!he.originalStepLevel&&!he.isAdditional&&he.level===C),Pe=(Ke?Ke.level:C)+1;if(o){const Ne=new Set(ve.map(Ae=>Ae.level)).size+1;if(Ne>o){const Ae=[{type:"max_approval_levels",message:`Adding this approver would create ${Ne} approval levels, which exceeds the maximum allowed (${o}). Please remove some approvers before adding a new one.`,currentValue:Ne,maxValue:o}];c?c(Ae):X.error((($e=Ae[0])==null?void 0:$e.message)||"Maximum approval levels exceeded");return}}if(!_||_.email.toLowerCase()!==O)try{const Ne=((ne=(await ba(O,1)).data)==null?void 0:ne.data)||[];if(Ne.length===0){X.error("User not found in organization directory. Please use @ to search for users.");return}const Ae=Ne[0];await ga({userId:Ae.userId,email:Ae.email,displayName:Ae.displayName,firstName:Ae.firstName,lastName:Ae.lastName,department:Ae.department,phone:Ae.phone,mobilePhone:Ae.mobilePhone,designation:Ae.designation,jobTitle:Ae.jobTitle,manager:Ae.manager,employeeId:Ae.employeeId,employeeNumber:Ae.employeeNumber,secondEmail:Ae.secondEmail,location:Ae.location});const Q={email:Ae.email,name:Ae.displayName||[Ae.firstName,Ae.lastName].filter(Boolean).join(" "),userId:Ae.userId,level:Pe,tat:typeof j=="string"?Number(j):j,tatType:w,isAdditional:!0,insertAfterLevel:C,stepName:`Additional Approver - ${Ae.displayName||Ae.email}`},le=ve.map(pe=>pe.level>=Pe?{...pe,level:pe.level+1}:pe);le.push(Q),le.sort((pe,ge)=>pe.level-ge.level),s("approvers",le),X.success("Additional approver added and subsequent steps shifted")}catch(he){console.error("Failed to validate approver:",he),X.error("Failed to validate user. Please try again.");return}else{const he={email:_.email,name:_.displayName||[_.firstName,_.lastName].filter(Boolean).join(" "),userId:_.userId,level:Pe,tat:j,tatType:w,isAdditional:!0,insertAfterLevel:C,stepName:`Additional Approver - ${_.displayName||_.email}`},Ne=ve.map(Ae=>Ae.level>=Pe?{...Ae,level:Ae.level+1}:Ae);Ne.push(he),Ne.sort((Ae,Q)=>Ae.level-Q.level),s("approvers",Ne),X.success("Additional approver added and subsequent steps shifted")}b(""),y(24),v("hours"),A(3),S(null),D([]),g(!1)},W=O=>{const z=[...t.approvers||[]];if(!z.find(se=>se.level===O))return;const G=z.filter(se=>se.level!==O).map(se=>se.level>O&&!se.isAdditional?{...se,level:se.level-1}:se);G.sort((se,ve)=>se.level-ve.level),s("approvers",G),X.success("Additional approver removed and subsequent steps shifted back")},V=()=>[...t.approvers||[]].sort((z,K)=>z.level-K.level),Y=t.approvers||[],Z=V();return e.jsxs(Ht.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(Jt,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Approver Selection"}),e.jsx("p",{className:"text-gray-600",children:"Assign approvers for workflow steps with TAT (Turn Around Time)"})]}),e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(q,{className:"border-2 border-blue-200 bg-blue-50",children:e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2 text-blue-900",children:[e.jsx(_r,{className:"w-5 h-5"}),"Workflow Steps Information"]}),e.jsxs(ye,{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 O=t.approvers||[],K=new Set(O.map(re=>re.level)).size;return K>0?e.jsxs("span",{children:[" (",K,"/",o,")"]}):null})()]})]})]})}),e.jsxs(q,{className:"border-2",children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-5 h-5"}),"Approval Hierarchy"]}),e.jsx(ye,{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(ee,{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 O=t.approvers||[],K=new Set(O.map(re=>re.level)).size;return K>0?e.jsxs("span",{children:[" (",K,"/",o,")"]}):null})()]}),e.jsxs(M,{type:"button",variant:"outline",onClick:()=>g(!0),className:"flex items-center gap-2",children:[e.jsx(bs,{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(ae,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-xs text-blue-700",children:"Creates and submits the request"})]})]})}),(()=>{const O=Z.filter(K=>K.isAdditional&&K.insertAfterLevel===0);let z=O.length;return Ks.filter(K=>!K.isAuto).map((K,re,G)=>{const se=Y.find($e=>$e.originalStepLevel===K.level||!$e.originalStepLevel&&$e.level===K.level&&!$e.isAdditional)||{email:"",name:"",level:K.level,tat:K.defaultTat,tatType:"hours",originalStepLevel:K.level},ve=re===G.length-1,Te=K.isAuto||K.approverType==="dealer"||K.approverType==="initiator",Ke=!K.isAuto,Je=Z.filter($e=>$e.isAdditional&&$e.insertAfterLevel===K.level).sort(($e,ne)=>$e.level-ne.level),Pe=z+1;return z++,z+=Je.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"})}),re===0&&O.map(($e,ne)=>{const he=ne+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:he})}),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(ae,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",onClick:()=>W($e.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(jt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:$e.name||$e.email}),e.jsxs("div",{className:"text-xs text-gray-500",children:[e.jsxs("div",{children:["Email: ",$e.email]}),e.jsxs("div",{children:["TAT: ",$e.tat," ",$e.tatType]})]})]})]})})]},`additional-${$e.level}`)}),e.jsx("div",{className:`p-3 rounded-lg border-2 transition-all ${se.email&&se.userId?"border-green-200 bg-green-50":Te?"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 ${se.email&&se.userId?"bg-green-600":Te?"bg-blue-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold text-sm",children:Pe})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-sm",children:K.name}),ve&&e.jsx(ae,{variant:"destructive",className:"text-xs",children:"FINAL"}),Te&&e.jsx(ae,{variant:"outline",className:"text-xs",children:"PRE-FILLED"})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:K.description}),Ke&&(()=>{var he,Ne;const $e=!!(se.email&&se.userId),ne=!se.email&&!Te;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(te,{htmlFor:`approver-${K.level}`,className:`text-xs font-bold ${ne?"text-blue-900":$e?"text-green-900":"text-gray-900"}`,children:["Approver Email ",!Te&&"*",ne&&e.jsx("span",{className:"ml-2 text-[10px] font-semibold italic text-blue-600",children:"(Required)"})]}),$e&&e.jsxs(ae,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Oe,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ce,{id:`approver-${K.level}`,type:"text",placeholder:Te?se.email:"@username or email...",value:se.email||"",onChange:Ae=>{const Q=Ae.target.value;Te||$(K.level,Q)},disabled:Te||K.isAuto,className:`h-9 border-2 transition-all mt-1 w-full text-sm ${Te?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":$e?"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"}`}),!Te&&!K.isAuto&&(m[K.level-1]||(((he=d[K.level-1])==null?void 0:he.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:m[K.level-1]?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:(Ne=d[K.level-1])==null?void 0:Ne.map(Ae=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>P(K.level,Ae),children:[e.jsx("div",{className:"font-medium text-gray-900",children:Ae.displayName||Ae.email}),e.jsx("div",{className:"text-xs text-gray-600",children:Ae.email}),Ae.department&&e.jsx("div",{className:"text-xs text-gray-500",children:Ae.department})]},Ae.userId))})})]}),se.name&&e.jsxs("p",{className:"text-xs text-green-600 mt-1",children:["Selected: ",e.jsx("span",{className:"font-semibold",children:se.name})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:`tat-${K.level}`,className:`text-xs font-bold ${ne?"text-blue-900":$e?"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(Ce,{id:`tat-${K.level}`,type:"number",placeholder:se.tatType==="days"?"7":"24",min:"1",max:se.tatType==="days"?"30":"720",value:se.tat||"",onChange:Ae=>T(K.level,parseInt(Ae.target.value)||""),disabled:K.isAuto,className:`h-9 border-2 transition-all flex-1 text-sm ${Te?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium":$e?"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(He,{value:se.tatType||"hours",onValueChange:Ae=>k(K.level,Ae),disabled:K.isAuto,children:[e.jsx(Ge,{className:`w-20 h-9 border-2 transition-all text-sm ${Te?"bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed":$e?"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(We,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"hours",children:"Hours"}),e.jsx(J,{value:"days",children:"Days"})]})]})]})]})]})})()]})]})}),Je.map(($e,ne)=>{const he=Pe+ne+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:he})}),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:$e.stepName||"Additional Approver"}),e.jsx(ae,{variant:"outline",className:"text-xs bg-purple-50 text-purple-700 border-purple-300",children:"ADDITIONAL"}),$e.email&&$e.userId&&e.jsxs(ae,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Oe,{className:"w-3 h-3 mr-1"}),"Verified"]}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",onClick:()=>W($e.level),className:"h-6 w-6 p-0 text-red-600 hover:text-red-700 hover:bg-red-50",children:e.jsx(jt,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:$e.name||$e.email||"No approver assigned"}),$e.email&&e.jsxs("div",{className:"text-xs text-gray-500 space-y-1",children:[e.jsxs("div",{children:["Email: ",$e.email]}),$e.tat&&e.jsxs("div",{children:["TAT: ",$e.tat," ",$e.tatType]})]})]})]})})]},`additional-${$e.level}`)})]},K.level)})})()]})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(st,{className:"w-5 h-5"}),"TAT Summary"]})}),e.jsx(ee,{children:e.jsx("div",{className:"space-y-3",children:Z.map(O=>{const z=O.originalStepLevel?Ks.find(se=>se.level===O.originalStepLevel):Ks.find(se=>se.level===O.level&&!O.isAdditional);if(z!=null&&z.isAuto)return null;const K=Number(O.tat||0),G=(O.tatType||"hours")==="days"?K*24:K;if(!K)return null;if(O.isAdditional){const se=Ks.find(ve=>ve.level===O.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:O.stepName||`Additional Approver (after "${(se==null?void 0:se.name)||"Unknown"}")`}),e.jsxs("span",{className:"text-sm text-gray-600",children:[G," hours"]})]},O.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:[G," hours"]})]},O.level)})})})]})]}),e.jsx(ht,{open:u,onOpenChange:g,children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(bs,{className:"w-5 h-5 text-blue-600"}),"Add Additional Approver"]}),e.jsx(_t,{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(te,{className:"text-sm font-medium",children:"Insert After Step *"}),e.jsxs(He,{value:C.toString(),onValueChange:O=>A(Number(O)),children:[e.jsx(Ge,{className:"h-11 border-gray-300",children:e.jsx(We,{placeholder:"Select step"})}),e.jsx(Ye,{children:Ks.filter(O=>{if(O.isAuto)return!1;const z=Ks.find(K=>K.name==="Requestor Claim Approval");return!(z&&O.level>=z.level)}).map(O=>e.jsx(J,{value:O.level.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:O.name})]})},O.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 O=t.approvers||[],K=new Set(O.map(re=>re.level)).size;return K>0?e.jsxs("span",{children:[" (",K,"/",o,")"]}):null})()]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ce,{type:"number",min:"1",max:w==="days"?"30":"720",value:j,onChange:O=>{const z=O.target.value;if(z==="")y("");else{const K=Number(z);!isNaN(K)&&K>=0&&y(K)}},onBlur:O=>{const z=O.target.value;(!z||z===""||Number(z)<=0)&&y(24)},className:"h-11 border-gray-300 flex-1",placeholder:"24"}),e.jsxs(He,{value:w,onValueChange:O=>v(O),children:[e.jsx(Ge,{className:"w-24 h-11 border-gray-300",children:e.jsx(We,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"hours",children:"Hours"}),e.jsx(J,{value:"days",children:"Days"})]})]})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Maximum time for this approver to respond (1-",w==="days"?"30 days":"720 hours",")"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-sm font-medium",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Xi,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Ce,{type:"text",placeholder:"@username or user@example.com",value:f,onChange:O=>B(O.target.value),className:"pl-10 h-11 border-gray-300",autoFocus:!0}),(R||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 max-h-60 overflow-auto",children:R?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):L.length>0?e.jsx("ul",{className:"divide-y",children:L.map(O=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>I(O),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:O.displayName||[O.firstName,O.lastName].filter(Boolean).join(" ")||O.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:O.email}),O.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:O.designation})]})})},O.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(Et,{children:[e.jsx(M,{type:"button",variant:"outline",onClick:()=>{g(!1),b(""),y(24),v("hours"),A(3),S(null),D([])},className:"flex-1",children:"Cancel"}),e.jsxs(M,{type:"button",onClick:E,className:"flex-1 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:!f.trim()||!j,children:[e.jsx(bs,{className:"w-4 h-4 mr-2"}),"Add Approver"]})]})]})})]})}const Gl=[{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"}],Yl=["Claim Details","Approver Selection","Review & Submit"];function Q5({onBack:t,onSubmit:s}){const{user:a}=cs(),[r,n]=h.useState(1),[i,l]=h.useState(!1),[o,c]=h.useState([]),[d,m]=h.useState(!1),[p,x]=h.useState(""),u=h.useRef(null),[g,f]=h.useState(!1),b=h.useRef(null),[j,y]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[w,v]=h.useState({open:!1,violations:[]}),[C,A]=h.useState([]),[L,D]=h.useState(!0);h.useEffect(()=>{(async()=>{try{D(!0);const E=await LA();A(E)}catch(E){console.error("Failed to load activity types:",E),X.error("Failed to load activity types. Please refresh the page.")}finally{D(!1)}})()},[]),h.useEffect(()=>{(async()=>{var E;try{const W=await la("SYSTEM_SETTINGS"),V=await la("WORKFLOW_SHARING"),Y=[...W,...V],Z={};Y.forEach(O=>{Z[O.configKey]=O.configValue}),y({maxApprovalLevels:parseInt(Z.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(Z.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((E=Z.ALLOW_ADD_SPECTATOR)==null?void 0:E.toLowerCase())==="true",maxSpectators:parseInt(Z.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(W){console.error("Failed to load system policy:",W)}})()},[]),h.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const[R,N]=h.useState({activityName:"",activityType:"",dealerCode:"",dealerName:"",dealerEmail:"",dealerPhone:"",dealerAddress:"",activityDate:void 0,location:"",requestDescription:"",periodStartDate:void 0,periodEndDate:void 0,estimatedBudget:"",approvers:[]}),_=Yl.length,S=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 E=await Y5(I);if(E){const W={dealerId:E.dealer||E.dealer_code||I,dealerCode:E.dealer||E.dealer_code||I,dealerName:E["dealer name"]||E.dealer_name||"Unknown Dealer",displayName:E["dealer name"]||E.dealer_name||"Unknown Dealer",email:E["dealer email"]||"",phone:E["dealer phone"]||"",city:E["re city"]||E.city||"",state:E["re state code"]||E.state||"",isLoggedIn:!0};c([W])}else c([])}catch(E){console.error("Error searching external dealer:",E),c([])}finally{m(!1)}},300)},U=(I,E)=>{N(W=>{const V={...W,[I]:E};if(I==="periodStartDate")E&&V.periodEndDate&&E>V.periodEndDate&&(V.periodEndDate=void 0,X.error("End date must be on or after the start date. End date has been cleared."));else if(I==="periodEndDate"&&E&&V.periodStartDate&&E{switch(r){case 1:return R.activityName&&R.activityType&&R.dealerCode&&R.dealerName&&R.activityDate&&R.location&&R.requestDescription;case 2:const E=(R.approvers||[]).find(W=>W.originalStepLevel===3||!W.originalStepLevel&&W.level===3&&!W.isAdditional);return(E==null?void 0:E.email)&&(E==null?void 0:E.userId)&&(E==null?void 0:E.tat);case 3:return!0;default:return!1}},$=()=>{if(r<_){if(!F()){if(r===2){const E=(R.approvers||[]).find(V=>V.originalStepLevel===3||!V.originalStepLevel&&V.level===3&&!V.isAdditional),W=[];(!(E!=null&&E.email)||!(E!=null&&E.userId)||!(E!=null&&E.tat))&&W.push("Department Lead Approval"),W.length>0?X.error(`Please add missing approvers: ${W.join(", ")}`):X.error("Please complete all required approver selections (email, user verification, and TAT) before proceeding.")}else X.error("Please complete all required fields before proceeding.");return}n(r+1)}},P=()=>{r>1&&n(r-1)},T=async I=>{l(!0);try{const E=await G5(I.dealerCode);if(!E.isLoggedIn){X.error(`Dealer "${E.dealerName||E.displayName}" (${E.dealerCode}) is not mapped to the system.`,{duration:5e3}),x(""),c([]),U("dealerCode",""),U("dealerName",""),U("dealerEmail",""),U("dealerPhone",""),U("dealerAddress",""),l(!1);return}U("dealerCode",E.dealerCode),U("dealerName",E.dealerName||E.displayName),U("dealerEmail",E.email||""),U("dealerPhone",E.phone||""),U("dealerAddress",""),x(E.dealerName||E.displayName),c([]),X.success(`Dealer "${E.dealerName||E.displayName}" verified and mapped to the System`)}catch{X.error("Dealer is not mapped to the system",{duration:5e3}),x(""),c([]),U("dealerCode",""),U("dealerName",""),U("dealerEmail",""),U("dealerPhone",""),U("dealerAddress","")}finally{l(!1)}},k=()=>{if(g)return;const E=[...R.approvers||[]].sort((O,z)=>O.level-z.level),W=new Map,V=[];if(E.forEach(O=>{W.has(O.level)?V.push(O.level):W.set(O.level,O)}),V.length>0){X.error(`Duplicate approver levels detected: ${V.join(", ")}. Please refresh and try again.`),console.error("Duplicate levels found:",V,E);return}const Y=E.map(O=>{const z={email:O.email,name:O.name,userId:O.userId,level:O.level,tat:O.tat,tatType:O.tatType};return O.isAdditional&&O.stepName&&(z.stepName=O.stepName,z.isAdditional=!0),O.originalStepLevel&&(z.originalStepLevel=O.originalStepLevel),z}),Z={...R,templateType:"claim-management",submittedAt:new Date().toISOString(),status:"pending",currentStep:"initiator-review",approvers:Y};if(f(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{f(!1),b.current=null},3e4),s)try{s(Z)}catch(O){b.current&&(clearTimeout(b.current),b.current=null),f(!1),console.error("Error submitting claim:",O)}else b.current&&(clearTimeout(b.current),b.current=null),f(!1)},B=()=>{switch(r){case 1:return e.jsxs(Ht.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(Pt,{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(te,{htmlFor:"activityName",className:"text-base font-semibold",children:"Activity Name *"}),e.jsx(Ce,{id:"activityName",placeholder:"e.g., Himalayan Adventure Fest 2024",value:R.activityName,onChange:I=>U("activityName",I.target.value),className:"mt-2 h-12"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"activityType",className:"text-base font-semibold",children:"Activity Type *"}),e.jsxs(He,{value:R.activityType,onValueChange:I=>U("activityType",I),disabled:L,children:[e.jsx(Ge,{className:"mt-2 !h-12 data-[size=default]:!h-12",id:"activityType",children:e.jsx(We,{placeholder:L?"Loading activity types...":"Select activity type"})}),e.jsx(Ye,{children:C.length>0?C.map(I=>e.jsx(J,{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(te,{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(Ce,{placeholder:"Type dealer code, name, or email to search...",value:R.dealerCode?`${R.dealerName} (${R.dealerCode})`:p,onChange:I=>{R.dealerCode?(U("dealerCode",""),U("dealerName",""),U("dealerEmail",""),U("dealerPhone",""),U("dealerAddress",""),x(I.target.value)):S(I.target.value)},onFocus:()=>{p&&p.length>=2&&S(p)},className:"h-12 border-2 border-gray-300 focus:border-blue-500",disabled:i}),R.dealerCode&&e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:e.jsxs(ae,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Oe,{className:"w-3 h-3 mr-1"}),"Verified"]})}),(d||o.length>0)&&!R.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(Oe,{className:"w-4 h-4 text-green-600"}):e.jsx(At,{className:"w-4 h-4 text-red-500"})})]})},I.dealerId))})})]})}),R.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:R.dealerName})," (",R.dealerCode,")"]}),R.dealerEmail&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Email: ",R.dealerEmail]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-base font-semibold",children:"Date *"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(M,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(dt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:R.activityDate?et(R.activityDate,"d MMM yyyy"):"Select date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(gi,{mode:"single",selected:R.activityDate,onSelect:I=>U("activityDate",I),initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"location",className:"text-base font-semibold",children:"Location *"}),e.jsx(Ce,{id:"location",placeholder:"e.g., Mumbai, Maharashtra",value:R.location,onChange:I=>U("location",I.target.value),className:"mt-2 h-12"})]})]}),e.jsxs("div",{children:[e.jsx(te,{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(Xn,{value:R.requestDescription||"",onChange:I=>U("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(te,{className:"text-base font-semibold",children:"Period (If Any)"}),e.jsx(ae,{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(te,{className:"text-sm text-gray-600",children:"Start Date"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(M,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",children:[e.jsx(dt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:R.periodStartDate?et(R.periodStartDate,"d MMM yyyy"):"Start date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(gi,{mode:"single",selected:R.periodStartDate,onSelect:I=>U("periodStartDate",I),initialFocus:!0,toDate:R.periodEndDate||void 0})})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-sm text-gray-600",children:"End Date"}),e.jsxs(ra,{children:[e.jsx(na,{asChild:!0,children:e.jsxs(M,{variant:"outline",className:"w-full justify-start text-left mt-2 h-12 pl-3",disabled:!R.periodStartDate,children:[e.jsx(dt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"flex-1 text-left",children:R.periodEndDate?et(R.periodEndDate,"d MMM yyyy"):"End date"})]})}),e.jsx(ia,{className:"w-auto p-0",align:"start",children:e.jsx(gi,{mode:"single",selected:R.periodEndDate,onSelect:I=>U("periodEndDate",I),initialFocus:!0,fromDate:R.periodStartDate||void 0})})]}),!R.periodStartDate&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Please select start date first"})]})]}),(R.periodStartDate||R.periodEndDate)&&e.jsx("div",{className:"mt-2",children:R.periodStartDate&&R.periodEndDate?e.jsxs("p",{className:"text-xs text-gray-600",children:["Period: ",et(R.periodStartDate,"d MMM yyyy")," - ",et(R.periodEndDate,"d MMM yyyy")]}):e.jsx("p",{className:"text-xs text-gray-500",children:R.periodStartDate?"Please select end date for the period":"Please select start date first"})})]})]})]});case 2:return e.jsx(K5,{formData:R,updateFormData:U,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:j.maxApprovalLevels,onPolicyViolation:I=>v({open:!0,violations:I})});case 3:return e.jsxs(Ht.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(Oe,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Review & Submit"}),e.jsx("p",{className:"text-gray-600",children:"Review your claim details before submission"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-blue-50 to-indigo-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.activityName})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Activity Type"}),e.jsx(ae,{variant:"secondary",className:"mt-1",children:R.activityType})]})]})})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-green-50 to-emerald-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Ji,{className:"w-5 h-5 text-green-600"}),"Dealer Information"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{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:R.dealerCode})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.dealerName})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Email"}),e.jsx("p",{className:"text-gray-900 mt-1",children:R.dealerEmail})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Phone"}),e.jsx("p",{className:"text-gray-900 mt-1",children:R.dealerPhone})]}),R.dealerAddress&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Address"}),e.jsx("p",{className:"text-gray-900 mt-1",children:R.dealerAddress})]})]})})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-purple-50 to-indigo-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Jt,{className:"w-5 h-5 text-purple-600"}),"Selected Approvers"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsx("div",{className:"space-y-3",children:[...R.approvers||[]].filter(E=>{var W,V;return!((W=E.email)!=null&&W.includes("system@"))&&!((V=E.email)!=null&&V.includes("finance@"))}).sort((E,W)=>E.level-W.level).map(E=>{const W=Number(E.tat||0),Y=(E.tatType||"hours")==="days"?W*24:W;let Z="Unknown",O="";if(E.isAdditional){Z=E.stepName||"Additional Approver";const z=Gl.find(K=>K.level===E.insertAfterLevel);O=E.stepName||`Additional Approver (after "${(z==null?void 0:z.name)||"Unknown"}")`}else{const z=E.originalStepLevel?Gl.find(K=>K.level===E.originalStepLevel):Gl.find(K=>K.level===E.level&&!K.isAuto);Z=(z==null?void 0:z.name)||"Unknown",O=Z}return e.jsx("div",{className:`p-3 rounded-lg border ${E.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(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:O}),E.isAdditional&&e.jsx(ae,{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:E.name||E.email||"Not selected"}),E.email&&e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:E.email})]}),e.jsxs("div",{className:"text-right ml-4",children:[e.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:[Y," hours"]}),e.jsx("p",{className:"text-xs text-gray-500",children:"TAT"})]})]})},`${E.level}-${E.email}`)})})})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-purple-50 to-pink-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"w-5 h-5 text-purple-600"}),"Date & Location"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.activityDate?et(R.activityDate,"PPP"):"N/A"})]}),e.jsxs("div",{children:[e.jsx(te,{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(zo,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-gray-900",children:R.location})]})]}),R.estimatedBudget&&e.jsxs("div",{className:"col-span-2",children:[e.jsx(te,{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:R.estimatedBudget})]})]})})]}),e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-orange-50 to-amber-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"w-5 h-5 text-orange-600"}),"Request Details"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{children:[e.jsx(te,{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(_s,{content:R.requestDescription||"",className:"text-sm"})})]})})]}),(R.periodStartDate||R.periodEndDate)&&e.jsxs(q,{className:"border-2",children:[e.jsx(oe,{className:"bg-gradient-to-br from-cyan-50 to-blue-50",children:e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(st,{className:"w-5 h-5 text-cyan-600"}),"Period"]})}),e.jsx(ee,{className:"pt-6 space-y-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"Start Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.periodStartDate?et(R.periodStartDate,"PPP"):"Not specified"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-gray-600 uppercase tracking-wider",children:"End Date"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:R.periodEndDate?et(R.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(_r,{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(M,{variant:"ghost",onClick:t,className:"mb-3 sm:mb-4 gap-2 text-sm sm:text-base",children:[e.jsx(Cs,{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(ae,{variant:"secondary",className:"mb-2 text-xs",children:"Claim Management Template"}),e.jsx("h1",{className:"text-xl sm:text-2xl lg:text-3xl font-bold text-gray-900",children:"New Claim Request"}),e.jsxs("p",{className:"text-sm sm:text-base text-gray-600 mt-1",children:["Step ",r," of ",_,": ",e.jsx("span",{className:"hidden sm:inline",children:Yl[r-1]})]})]})}),e.jsxs("div",{className:"mt-4 sm:mt-6",children:[e.jsx(qs,{value:r/_*100,className:"h-2"}),e.jsx("div",{className:"flex justify-between mt-2 px-1",children:Yl.map((I,E)=>e.jsx("span",{className:`text-xs sm:text-sm ${E+1<=r?"text-blue-600 font-medium":"text-gray-400"}`,children:E+1},E))})]})]}),e.jsx(q,{className:"mb-6 sm:mb-8",children:e.jsx(ee,{className:"p-4 sm:p-6 lg:p-8",children:e.jsx(ll,{mode:"wait",children:B()})})}),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(M,{variant:"outline",onClick:P,disabled:r===1,className:"gap-2 w-full sm:w-auto order-2 sm:order-1",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Previous"]}),r<_?e.jsxs(M,{onClick:$,className:`gap-2 w-full sm:w-auto order-1 sm:order-2 ${F()?"":"opacity-50 cursor-pointer hover:opacity-60"}`,children:["Next",e.jsx(fs,{className:"w-4 h-4"})]}):e.jsx(M,{onClick:k,disabled:!F()||g,className:"gap-2 bg-green-600 hover:bg-green-700 w-full sm:w-auto order-1 sm:order-2",children:g?e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"w-4 h-4 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(za,{className:"w-4 h-4"}),"Submit Claim Request"]})})]})]}),e.jsx(ti,{open:w.open,onClose:()=>v({open:!1,violations:[]}),violations:w.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}const{DocumentsTab:X5,ActivityTab:J5,WorkNotesTab:Z5,SummaryTab:q5,RequestDetailHeader:ek,QuickActionsSidebar:tk,RequestDetailModals:sk}=d0;let ak=class extends h.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(es,{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(M,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(M,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function rk({requestId:t,onBack:s,dynamicRequests:a=[]}){var Za,qa,er,tr,Gt,Ts;const n=_a().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=h.useState(l),[d,m]=h.useState(!1),[p,x]=h.useState(null),[u,g]=h.useState(null),[f,b]=h.useState(!1),[j,y]=h.useState(0),[w,v]=h.useState(!1),[C,A]=h.useState(!1),[L,D]=h.useState(!1),[R,N]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[_,S]=h.useState({open:!1,violations:[]}),{user:U}=cs(),{request:F,apiRequest:$,loading:P,refreshing:T,refreshDetails:k,currentApprovalLevel:B,isSpectator:I,isInitiator:E,existingParticipants:W,accessDenied:V}=Vc(n,a,U),Y=(U==null?void 0:U.userId)||"",Z=(U==null?void 0:U.jobTitle)==="Dealer"||(U==null?void 0:U.designation)==="Dealer",z=((F==null?void 0:F.workflowType)==="CLAIM_MANAGEMENT"||($==null?void 0:$.workflowType)==="CLAIM_MANAGEMENT"||(F==null?void 0:F.templateType)==="claim-management")&&!Z,{mergedMessages:K,unreadWorkNotes:re,workNoteAttachments:G,setWorkNoteAttachments:se}=Jg(n,$,o,U),{uploadingDocument:ve,triggerFileInput:Te,previewDocument:Ke,setPreviewDocument:Je,documentPolicy:Pe,documentError:$e,setDocumentError:ne}=Zg($,k),[he,Ne]=h.useState(null),Ae=he||B,{showApproveModal:Q,setShowApproveModal:le,showRejectModal:pe,setShowRejectModal:ge,showAddApproverModal:Fe,setShowAddApproverModal:_e,showAddSpectatorModal:Xe,setShowAddSpectatorModal:lt,showSkipApproverModal:Nt,setShowSkipApproverModal:wt,showActionStatusModal:As,setShowActionStatusModal:ie,skipApproverData:Re,setSkipApproverData:ce,actionStatus:Ve,setActionStatus:Be,handleApproveConfirm:tt,handleRejectConfirm:ze,handleAddApprover:rt,handleSkipApprover:qe,handleAddSpectator:ot}=e0(n,Ae,k),Us=async yt=>{await tt(yt),Ne(null)},rs=async yt=>{await ze(yt),Ne(null)},gt=((F==null?void 0:F.status)||($==null?void 0:$.status)||"").toLowerCase(),ct=(gt==="approved"||gt==="rejected")&&E,{conclusionRemark:Dt,setConclusionRemark:vs,conclusionLoading:ts,conclusionSubmitting:Sa,aiGenerated:Ma,handleGenerateConclusion:Aa,handleFinalizeConclusion:Ya,generationAttempts:Ft,generationFailed:La,maxAttemptsReached:Bs}=qg(F,n,E,k,s,Be,ie);h.useEffect(()=>{(async()=>{var xs;try{const Os=await la("SYSTEM_SETTINGS"),ks=await la("WORKFLOW_SHARING"),Oa=[...Os,...ks],ja={};Oa.forEach(sr=>{ja[sr.configKey]=sr.configValue}),N({maxApprovalLevels:parseInt(ja.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(ja.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((xs=ja.ALLOW_ADD_SPECTATOR)==null?void 0:xs.toLowerCase())==="true",maxSpectators:parseInt(ja.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(Os){console.error("Failed to load system policy:",Os)}})()},[]),h.useEffect(()=>{const xs=new URLSearchParams(window.location.search).get("tab");xs&&c(xs)},[n]);const Or=()=>{k()},pr=()=>{v(!0)},$r=()=>{A(!0)},Ka=async()=>{await k()},gr=()=>{D(!0)},Qa=async()=>{await k()},fr=async()=>{await k()},Xa=async()=>{if(!($!=null&&$.requestId)){X.error("Request ID not found");return}if(!p){X.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},Ta=(F==null?void 0:F.status)==="closed";h.useEffect(()=>{(async()=>{if(!Ta||!($!=null&&$.requestId)){g(null),x(null);return}try{b(!0);const xs=await i0($.requestId);if(xs!=null&&xs.summaryId){x(xs.summaryId);try{const Os=await Hc(xs.summaryId);g(Os)}catch(Os){console.error("Failed to fetch summary details:",Os),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{b(!1)}})()},[Ta,$==null?void 0:$.requestId]),h.useEffect(()=>{if(!Y||!($!=null&&$.requestId))return;const yt=en();if(!yt)return;Gh(yt,Y);const xs=Os=>{var sr,pn,gn,fn;const ks=Os==null?void 0:Os.notification;if(!ks)return;const Oa=ks.requestId||ks.request_id,ja=((sr=ks.metadata)==null?void 0:sr.requestNumber)||((pn=ks.metadata)==null?void 0:pn.request_number);Oa!==$.requestId&&ja!==n&&ja!==$.requestNumber||((gn=ks.metadata)!=null&&gn.creditNoteNumber||(fn=ks.metadata)!=null&&fn.credit_note_number)&&k()};return yt.on("notification:new",xs),()=>{yt.off("notification:new",xs)}},[Y,$==null?void 0:$.requestId,n,k]);const Ja=((F==null?void 0:F.approvalFlow)||[]).filter(yt=>yt&&typeof yt.step=="number").map(yt=>({levelNumber:yt.step||0,approverName:yt.approver||"Unknown",status:yt.status||"pending",tatHours:yt.tatHours||24}));return P&&!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(Ut,{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..."})]})}):V!=null&&V.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(xh,{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:V.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(M,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(M,{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(ek,{request:F,refreshing:T,onBack:s||(()=>window.history.back()),onRefresh:Or,onShareSummary:Xa,isInitiator:E,slaData:((Za=F==null?void 0:F.summary)==null?void 0:Za.sla)||(F==null?void 0:F.sla)||null,isPaused:((qa=F==null?void 0:F.pauseInfo)==null?void 0:qa.isPaused)||!1}),e.jsxs(si,{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(ai,{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(Lt,{value:"overview",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-overview",children:[e.jsx(hh,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Overview"})]}),Ta&&u&&e.jsxs(Lt,{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(Ho,{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(Lt,{value:"workflow",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-workflow",children:[e.jsx(Ws,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),z&&e.jsxs(Lt,{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(Ha,{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(Lt,{value:"documents",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-documents",children:[e.jsx(Ie,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Docs"})]}),e.jsxs(Lt,{value:"activity",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 col-span-1 sm:col-span-1","data-testid":"tab-activity",children:[e.jsx($t,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Activity"})]}),e.jsxs(Lt,{value:"worknotes",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 relative col-span-2 sm:col-span-1","data-testid":"tab-worknotes",children:[e.jsx(Hs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),re>0&&e.jsx(ae,{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:re>9?"9+":re})]})]})}),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(Ot,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:e.jsx(g5,{request:F,apiRequest:$,currentUserId:Y,isInitiator:E,needsClosure:ct,conclusionRemark:Dt,setConclusionRemark:vs,conclusionLoading:ts,conclusionSubmitting:Sa,aiGenerated:Ma,handleGenerateConclusion:Aa,handleFinalizeConclusion:Ya,generationAttempts:Ft,generationFailed:La,maxAttemptsReached:Bs})}),Ta&&e.jsx(Ot,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(q5,{summary:u,loading:f,onShare:Xa,isInitiator:E})}),e.jsx(Ot,{value:"workflow",className:"mt-0",children:e.jsx(H5,{request:F,user:U,isInitiator:E,onSkipApprover:yt=>{if(!yt.levelId){alert("Level ID not available");return}ce(yt),wt(!0)},onRefresh:k,documentPolicy:Pe})}),z&&e.jsx(Ot,{value:"io",className:"mt-0",children:e.jsx(W5,{request:F,apiRequest:$,onRefresh:k})}),e.jsx(Ot,{value:"documents",className:"mt-0",children:e.jsx(X5,{request:F,workNoteAttachments:G,uploadingDocument:ve,documentPolicy:Pe,triggerFileInput:Te,setPreviewDocument:Je,downloadDocument:Ls})}),e.jsx(Ot,{value:"activity",className:"mt-0",children:e.jsx(J5,{request:F})}),e.jsx(Ot,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(Z5,{requestId:n,requestTitle:F.title,mergedMessages:K,setWorkNoteAttachments:se,isInitiator:E,isSpectator:I,currentLevels:Ja,onAddApprover:rt,maxApprovalLevels:R.maxApprovalLevels,onPolicyViolation:yt=>S({open:!0,violations:yt})})})]}),o!=="worknotes"&&e.jsx(tk,{request:F,isInitiator:E,isSpectator:I,currentApprovalLevel:B,onAddApprover:()=>_e(!0),onAddSpectator:()=>lt(!0),onApprove:()=>le(!0),onReject:()=>ge(!0),onPause:pr,onResume:$r,onRetrigger:gr,summaryId:p,refreshTrigger:j,pausedByUserId:(tr=(er=F==null?void 0:F.pauseInfo)==null?void 0:er.pausedBy)==null?void 0:tr.userId,currentUserId:Y,apiRequest:$,hideApproveReject:Z})]})]})]})}),d&&p&&e.jsx(m0,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(F==null?void 0:F.title)||"N/A",onSuccess:()=>{k(),y(yt=>yt+1)}}),w&&($==null?void 0:$.requestId)&&e.jsx(u0,{isOpen:w,onClose:()=>v(!1),requestId:$.requestId,levelId:(B==null?void 0:B.levelId)||null,onSuccess:Qa}),C&&($==null?void 0:$.requestId)&&e.jsx(x0,{isOpen:C,onClose:()=>A(!1),requestId:$.requestId,onSuccess:Ka}),L&&($==null?void 0:$.requestId)&&e.jsx(h0,{isOpen:L,onClose:()=>D(!1),requestId:$.requestId,approverName:(Ts=(Gt=F==null?void 0:F.pauseInfo)==null?void 0:Gt.pausedBy)==null?void 0:Ts.name,onSuccess:fr}),e.jsx(sk,{showApproveModal:Q,showRejectModal:pe,showAddApproverModal:Fe,showAddSpectatorModal:Xe,showSkipApproverModal:Nt,showActionStatusModal:As,previewDocument:Ke,documentError:$e,request:F,skipApproverData:Re,actionStatus:Ve,existingParticipants:W,currentLevels:Ja,maxApprovalLevels:R.maxApprovalLevels,onPolicyViolation:yt=>S({open:!0,violations:yt}),setShowApproveModal:le,setShowRejectModal:ge,setShowAddApproverModal:_e,setShowAddSpectatorModal:lt,setShowSkipApproverModal:wt,setShowActionStatusModal:ie,setPreviewDocument:Je,setDocumentError:ne,setSkipApproverData:ce,setActionStatus:Be,handleApproveConfirm:Us,handleRejectConfirm:rs,handleAddApprover:rt,handleAddSpectator:ot,handleSkipApprover:qe,downloadDocument:Ls,documentPolicy:Pe}),e.jsx(ti,{open:_.open,onClose:()=>S({open:!1,violations:[]}),violations:_.violations,policyDetails:{maxApprovalLevels:R.maxApprovalLevels,maxParticipants:R.maxParticipants,allowSpectators:R.allowSpectators,maxSpectators:R.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(Ie,{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(M,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(Cs,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(M,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})})}function nk(t){return e.jsx(ak,{children:e.jsx(rk,{...t})})}function ik({onNavigate:t,onNewRequest:s}){const[a,r]=h.useState(!0),[n,i]=h.useState(!1),[l,o]=h.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]=h.useState([]),[m,p]=h.useState("all"),[x,u]=h.useState(),[g,f]=h.useState(),b=async(S=!1)=>{try{S?i(!0):r(!0);const U=await O5(m||"all",x,g);o(U.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(U.categoryData||[])}catch(U){console.error("[DealerDashboard] Error fetching data:",U),X.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)}};h.useEffect(()=>{b()},[]);const j=(S,U=!1)=>{if(S==null||isNaN(S))return"₹0";const F=typeof S=="string"?parseFloat(S):Number(S);return F<=0?"₹0":U||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")}`},y=S=>S.toLocaleString("en-IN"),w=()=>l.totalClaims===0?0:(l.approved/l.totalClaims*100).toFixed(1),v=()=>l.approved===0?0:(l.credited/l.approved*100).toFixed(1),C=h.useMemo(()=>{const S=c.reduce((U,F)=>U+F.raised,0);return S===0?[]:c.map(U=>({name:U.activityType.length>20?U.activityType.substring(0,20)+"...":U.activityType,value:U.raised,fullName:U.activityType,percentage:(U.raised/S*100).toFixed(0)}))},[c]),A=h.useMemo(()=>c.map(S=>({name:S.activityType.length>15?S.activityType.substring(0,15)+"...":S.activityType,fullName:S.activityType,Raised:S.raised,Approved:S.approved,Rejected:S.rejected,Pending:S.pending})),[c]),L=h.useMemo(()=>c.map(S=>({name:S.activityType.length>15?S.activityType.substring(0,15)+"...":S.activityType,fullName:S.activityType,Raised:S.raisedValue,Approved:S.approvedValue,Credited:S.creditedValue})),[c]),D=["#166534","#15803d","#16a34a","#22c55e","#4ade80","#86efac","#bbf7d0"],R=h.useMemo(()=>c.length===0?null:c.reduce((S,U)=>U.approvalRate>((S==null?void 0:S.approvalRate)||0)?U:S),[c]),N=h.useMemo(()=>c.length===0?null:c.reduce((S,U)=>U.raisedValue>((S==null?void 0:S.raisedValue)||0)?U:S),[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(Ut,{className:"w-8 h-8 animate-spin text-blue-600"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading dashboard..."})]})}):l.totalClaims===0&&c.length===0?e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(q,{className:"border-0 shadow-xl relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(ee,{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(ps,{className:"w-8 h-8 text-slate-900"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-4xl text-white font-bold",children:"Claims Analytics Dashboard"}),e.jsx("p",{className:"text-xl text-gray-200 mt-1",children:"Comprehensive insights into approval workflows"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-4 mt-8",children:e.jsxs(M,{onClick:()=>{i(!0),b(!0)},disabled:n,variant:"outline",className:"bg-white/10 hover:bg-white/20 text-white border-white/20",children:[e.jsx(Ut,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh"]})})]})})})]}),e.jsx(q,{className:"shadow-lg",children:e.jsxs(ee,{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(ro,{className:"w-12 h-12 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-semibold text-gray-900 mb-2",children:"No Claims Data Available"}),e.jsx("p",{className:"text-gray-600 text-center max-w-md mb-6",children:"You don't have any claims data yet. Once you create and submit claim requests, your analytics will appear here."}),e.jsx("div",{className:"flex flex-col sm:flex-row gap-4",children:e.jsxs(M,{onClick:()=>{i(!0),b(!0)},disabled:n,variant:"outline",children:[e.jsx(Ut,{className:`w-5 h-5 mr-2 ${n?"animate-spin":""}`}),"Refresh Data"]})})]})})]}):e.jsxs("div",{className:"space-y-6 max-w-[1600px] mx-auto p-4",children:[e.jsxs(q,{className:"border-0 shadow-xl relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(ee,{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(ps,{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(M,{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(M,{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(Ie,{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(Ii,{className:"w-8 h-8 text-yellow-400"})})})})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6 gap-4",children:[e.jsxs(q,{className:"border-l-4 border-l-blue-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Raised Claims"}),e.jsx("div",{className:"p-2 rounded-lg bg-blue-50",children:e.jsx(Ie,{className:"h-4 w-4 text-blue-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.totalClaims)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:j(l.totalValue,!0)})]})]}),e.jsxs(q,{className:"border-l-4 border-l-green-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Approved"}),e.jsx("div",{className:"p-2 rounded-lg bg-green-50",children:e.jsx(Oe,{className:"h-4 w-4 text-green-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.approved)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Ws,{className:"h-3 w-3 text-green-600"}),e.jsxs("p",{className:"text-xs text-green-600",children:[w(),"% approval rate"]})]})]})]}),e.jsxs(q,{className:"border-l-4 border-l-red-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Rejected"}),e.jsx("div",{className:"p-2 rounded-lg bg-red-50",children:e.jsx(At,{className:"h-4 w-4 text-red-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.rejected)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Tb,{className:"h-3 w-3 text-red-600"}),e.jsxs("p",{className:"text-xs text-red-600",children:[l.totalClaims>0?(l.rejected/l.totalClaims*100).toFixed(1):0,"% rejection rate"]})]})]})]}),e.jsxs(q,{className:"border-l-4 border-l-orange-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{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(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.pending)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:j(l.pendingValue)})]})]}),e.jsxs(q,{className:"border-l-4 border-l-emerald-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Credited"}),e.jsx("div",{className:"p-2 rounded-lg bg-emerald-50",children:e.jsx(kb,{className:"h-4 w-4 text-emerald-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.credited)}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Ws,{className:"h-3 w-3 text-emerald-600"}),e.jsxs("p",{className:"text-xs text-emerald-600",children:[v(),"% credit rate"]})]})]})]}),e.jsxs(q,{className:"border-l-4 border-l-amber-500 shadow-lg hover:shadow-xl transition-all duration-300",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-sm text-muted-foreground",children:"Pending Credit"}),e.jsx("div",{className:"p-2 rounded-lg bg-amber-50",children:e.jsx(es,{className:"h-4 w-4 text-amber-600"})})]})}),e.jsxs(ee,{children:[e.jsx("div",{className:"text-2xl text-gray-900",children:y(l.pendingCredit)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:j(l.pendingCreditValue)})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(q,{className:"shadow-lg",children:[e.jsx(oe,{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(ro,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(de,{children:"Claims Distribution by Activity Type"}),e.jsx(ye,{children:"Total claims raised across activity types"})]})]})}),e.jsxs(ee,{children:[e.jsx(Qr,{width:"100%",height:300,children:e.jsxs(Qx,{children:[e.jsx(Xx,{data:C,cx:"50%",cy:"50%",labelLine:!1,label:({name:S,percentage:U})=>`${S}: ${U}%`,outerRadius:80,fill:"#8884d8",dataKey:"value",children:C.map((S,U)=>e.jsx(Jx,{fill:D[U%D.length]},`cell-${U}`))}),e.jsx(Xr,{})]})}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mt-4",children:C.slice(0,3).map((S,U)=>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[U%D.length]}}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-600",children:S.name}),e.jsx("p",{className:"text-sm text-gray-900",children:y(S.value)})]})]},U))})]})]}),e.jsxs(q,{className:"shadow-lg",children:[e.jsx(oe,{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(Ii,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{children:"Claims Status by Activity Type"}),e.jsx(ye,{children:"Count comparison across workflow stages"})]})]})}),e.jsx(ee,{children:e.jsx(Qr,{width:"100%",height:300,children:e.jsxs(to,{data:A,children:[e.jsx(Si,{strokeDasharray:"3 3"}),e.jsx(Ai,{dataKey:"name"}),e.jsx(Ti,{}),e.jsx(Xr,{}),e.jsx(ki,{}),e.jsx(ka,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(ka,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(ka,{dataKey:"Rejected",fill:"#ef4444"}),e.jsx(ka,{dataKey:"Pending",fill:"#f59e0b"})]})})})]})]}),e.jsxs(q,{className:"shadow-lg",children:[e.jsx(oe,{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($t,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(de,{children:"Detailed Activity Type Breakdown"}),e.jsx(ye,{children:"In-depth analysis of claims by type and status"})]})]})}),e.jsx(ee,{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(Qr,{width:"100%",height:350,children:e.jsxs(to,{data:L,children:[e.jsx(Si,{strokeDasharray:"3 3"}),e.jsx(Ai,{dataKey:"name"}),e.jsx(Ti,{tickFormatter:S=>j(S)}),e.jsx(Xr,{formatter:S=>j(S),labelFormatter:S=>S}),e.jsx(ki,{}),e.jsx(ka,{dataKey:"Raised",fill:"#3b82f6"}),e.jsx(ka,{dataKey:"Approved",fill:"#22c55e"}),e.jsx(ka,{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((S,U)=>e.jsxs(q,{className:"shadow-md hover:shadow-lg transition-shadow",children:[e.jsx(oe,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{className:"text-base",children:S.activityType}),e.jsxs(ae,{className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:[S.approvalRate.toFixed(1),"% approved"]})]})}),e.jsxs(ee,{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:[y(S.raised)," (",j(S.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:[y(S.approved)," (",j(S.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:[y(S.rejected)," (",j(S.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:[y(S.pending)," (",j(S.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:[y(S.credited)," (",j(S.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:[y(S.pendingCredit)," (",j(S.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:[S.creditRate.toFixed(1),"%"]})]}),e.jsx(qs,{value:S.creditRate,className:"h-2"})]})]})]},U))})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(q,{className:"border-t-4 border-t-green-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{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(qt,{className:"h-6 w-6 text-green-600"})}),e.jsx(Ws,{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:(R==null?void 0:R.activityType)||"N/A"}),e.jsxs("p",{className:"text-sm text-green-600",children:[(R==null?void 0:R.approvalRate.toFixed(2))||0,"% approval rate"]})]})}),e.jsx(q,{className:"border-t-4 border-t-blue-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{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(Ha,{className:"h-6 w-6 text-blue-600"})}),e.jsx($t,{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?j(N.raisedValue,!0):"₹0"," raised"]})]})}),e.jsx(q,{className:"border-t-4 border-t-emerald-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{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(Gi,{className:"h-6 w-6 text-emerald-600"})}),e.jsx(Oe,{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:[v(),"%"]}),e.jsxs("p",{className:"text-sm text-emerald-600",children:[y(l.credited)," claims credited"]})]})}),e.jsx(q,{className:"border-t-4 border-t-amber-500 shadow-lg hover:shadow-xl transition-shadow",children:e.jsxs(ee,{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(lh,{className:"h-6 w-6 text-amber-600"})}),e.jsx(es,{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:y(l.pendingCredit)}),e.jsxs("p",{className:"text-sm text-amber-600",children:[j(l.pendingCreditValue)," awaiting credit"]})]})})]})]})}function lk({searchTerm:t,sortBy:s,sortOrder:a,onSearchChange:r,onSortByChange:n,onSortOrderChange:i,onClearFilters:l,activeFiltersCount:o,...c}){return e.jsxs(q,{className:"shadow-lg border-0",children:[e.jsx(oe,{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(Pa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ye,{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(M,{variant:"ghost",size:"sm",onClick:l,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(jt,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(ee,{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(Ss,{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(Ce,{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(He,{value:s,onValueChange:d=>n(d),children:[e.jsx(Ge,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(We,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"due",children:"Due Date"}),e.jsx(J,{value:"created",children:"Date Created"}),e.jsx(J,{value:"priority",children:"Priority"}),e.jsx(J,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(M,{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(Zi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(qi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function ok({searchTerm:t,statusFilter:s="all",sortBy:a,sortOrder:r,onSearchChange:n,onStatusChange:i,onSortByChange:l,onSortOrderChange:o,onClearFilters:c,activeFiltersCount:d,...m}){return e.jsxs(q,{className:"shadow-lg border-0","data-testid":"dealer-closed-requests-filters",children:[e.jsx(oe,{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(Pa,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ye,{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(M,{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(jt,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(ee,{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(Ss,{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(Ce,{placeholder:"Search requests, IDs...",value:t,onChange:p=>n(p.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors","data-testid":"dealer-closed-requests-search"})]}),i&&e.jsxs(He,{value:s,onValueChange:i,children:[e.jsx(Ge,{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(We,{placeholder:"Closure Type"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Closures"}),e.jsx(J,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(J,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:a,onValueChange:p=>l(p),children:[e.jsx(Ge,{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(We,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"due",children:"Due Date"}),e.jsx(J,{value:"created",children:"Date Created"}),e.jsx(J,{value:"priority",children:"Priority"})]})]}),e.jsx(M,{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(Zi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(qi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function ck({searchTerm:t,statusFilter:s,initiatorFilter:a,approverFilter:r,approverFilterType:n,dateRange:i,customStartDate:l,customEndDate:o,showCustomDatePicker:c,initiatorSearch:d,approverSearch:m,onSearchChange:p,onStatusChange:x,onInitiatorChange:u,onApproverChange:g,onApproverTypeChange:f,onDateRangeChange:b,onCustomStartDateChange:j,onCustomEndDateChange:y,onShowCustomDatePickerChange:w,onApplyCustomDate:v,onClearFilters:C,hasActiveFilters:A,...L}){return e.jsx(q,{className:"border-gray-200 shadow-md","data-testid":"dealer-user-all-requests-filters",children:e.jsx(ee,{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(Pa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Filters"}),A&&e.jsx(ae,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),A&&e.jsxs(M,{variant:"ghost",size:"sm",onClick:C,className:"gap-2",children:[e.jsx(Ut,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Qt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Ss,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ce,{placeholder:"Search requests...",value:t,onChange:D=>p(D.target.value),className:"pl-10 h-10","data-testid":"dealer-search-input"})]}),e.jsxs(He,{value:s,onValueChange:x,children:[e.jsx(Ge,{className:"h-10","data-testid":"dealer-status-filter",children:e.jsx(We,{placeholder:"All Status"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"pending",children:"Pending"}),e.jsx(J,{value:"paused",children:"Paused"}),e.jsx(J,{value:"approved",children:"Approved"}),e.jsx(J,{value:"rejected",children:"Rejected"}),e.jsx(J,{value:"closed",children:"Closed"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(te,{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(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:d.handleClear,children:e.jsx(jt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{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(te,{className:"text-sm font-medium text-gray-700",children:"Approver"}),r!=="all"&&f&&e.jsxs(He,{value:n,onValueChange:D=>f(D),children:[e.jsx(Ge,{className:"h-7 w-32 text-xs",children:e.jsx(We,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"current",children:"Current Only"}),e.jsx(J,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:m.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:m.selectedUser.displayName||m.selectedUser.email}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:m.handleClear,children:e.jsx(jt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{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(dt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:i,onValueChange:D=>b(D),children:[e.jsx(Ge,{className:"w-[160px] h-10",children:e.jsx(We,{placeholder:"Date Range"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Time"}),e.jsx(J,{value:"today",children:"Today"}),e.jsx(J,{value:"week",children:"This Week"}),e.jsx(J,{value:"month",children:"This Month"}),e.jsx(J,{value:"last7days",children:"Last 7 Days"}),e.jsx(J,{value:"last30days",children:"Last 30 Days"}),e.jsx(J,{value:"custom",children:"Custom Range"})]})]}),i==="custom"&&e.jsxs(ra,{open:c,onOpenChange:w,children:[e.jsx(na,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(dt,{className:"w-4 h-4"}),l&&o?`${et(l,"MMM d, yyyy")} - ${et(o,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Js,{value:l||null,onChange:D=>{const R=D?new Date(D):void 0;R?(j==null||j(R),o&&R>o&&(y==null||y(R))):j==null||j(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"end-date",children:"End Date"}),e.jsx(Js,{value:o||null,onChange:D=>{const R=D?new Date(D):void 0;R?(y==null||y(R),l&&R{w==null||w(!1),j==null||j(void 0),y==null||y(void 0),b("month")},children:"Cancel"})]})]})})]})]})]})})})}function dk(t){switch(t){case"DEALER_CLAIM":return nk;case"CUSTOM":default:return o5}}function mk(t){switch(t){case"DEALER":return lk;case"STANDARD":default:return m5}}function uk(t){switch(t){case"DEALER":return ok;case"STANDARD":default:return h5}}function xk(t){switch(t){case"DEALER":return ck;case"STANDARD":default:return p5}}const hk=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ca,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:qt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:qt,iconColor:"text-gray-600"}}},pk=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:At,iconColor:"text-red-600",label:"Rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Oe,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 gk({onViewRequest:t}){const[s,a]=h.useState([]),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState(1),[d,m]=h.useState(0),[p]=h.useState(10),x=h.useRef(null),u=jw(),g=h.useMemo(()=>{try{const R=at.getUserData();return lc(R)}catch(R){return console.error("[OpenRequests] Error getting user filter type:",R),"STANDARD"}},[]),f=h.useMemo(()=>mk(g),[g]),b=g==="DEALER",j=R=>{const N={search:u.searchTerm||void 0,status:R&&!b&&u.statusFilter!=="all"?u.statusFilter:void 0,priority:!b&&u.priorityFilter!=="all"?u.priorityFilter:void 0,templateType:u.templateTypeFilter!=="all"?u.templateTypeFilter:void 0,sortBy:u.sortBy,sortOrder:u.sortOrder};return N.templateType==="FORM_16"&&(u.form16FinancialYear&&(N.financialYear=u.form16FinancialYear),u.form16Quarter&&(N.quarter=u.form16Quarter)),N},y=h.useCallback(async(R=1,N)=>{try{R===1&&(n(!0),a([]));const _=await Gs.listOpenForMe({page:R,limit:p,search:N==null?void 0:N.search,status:N==null?void 0:N.status,priority:N==null?void 0:N.priority,templateType:N==null?void 0:N.templateType,financialYear:N==null?void 0:N.financialYear,quarter:N==null?void 0:N.quarter,sortBy:N==null?void 0:N.sortBy,sortOrder:N==null?void 0:N.sortOrder}),S=Array.isArray(_==null?void 0:_.data)?_.data:[],U=_==null?void 0:_.pagination;U&&(u.setCurrentPage(U.page||1),c(U.totalPages||1),m(U.total||0));const F=S.map($=>{var T,k,B,I;const P=$.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)||((k=$.initiator)==null?void 0:k.email)||"—",avatar:(((B=$.initiator)==null?void 0:B.displayName)||((I=$.initiator)==null?void 0:I.email)||"NA").split(" ").map(E=>E[0]).join("").slice(0,2).toUpperCase()},currentApprover:$.currentApprover?{name:$.currentApprover.name||$.currentApprover.email||"—",avatar:($.currentApprover.name||$.currentApprover.email||"CA").split(" ").map(E=>E[0]).join("").slice(0,2).toUpperCase(),sla:$.currentApprover.sla}:void 0,createdAt:P||"—",approvalStep:$.currentLevel?`Step ${$.currentLevel} of ${$.totalLevels||"?"}`:void 0,department:$.department,currentLevelSLA:$.currentLevelSLA,templateType:$.templateType||$.template_type,form16Submission:$.form16Submission??null}});a(F)}finally{n(!1),l(!1)}},[p,u]);x.current=y;const w=h.useCallback(()=>{l(!0),y(u.currentPage,j(!0))},[u.currentPage,y]),v=h.useCallback(R=>{R>=1&&R<=o&&(u.setCurrentPage(R),y(R,j(!0)))},[o,u,y]),C=()=>{const R=[];let _=Math.max(1,u.currentPage-Math.floor(2.5)),S=Math.min(o,_+5-1);S-_<4&&(_=Math.max(1,S-5+1));for(let U=_;U<=S;U++)R.push(U);return R},A=h.useRef(!1);h.useEffect(()=>{if(!A.current){A.current=!0;const R=u.currentPage||1;y(R,j(!0))}},[]);const L=h.useRef({searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,isDealer:b});h.useEffect(()=>{if(!A.current)return;const R=L.current;if(!(R.searchTerm!==u.searchTerm||R.statusFilter!==u.statusFilter||R.priorityFilter!==u.priorityFilter||R.templateTypeFilter!==u.templateTypeFilter||R.sortBy!==u.sortBy||R.sortOrder!==u.sortOrder||R.isDealer!==b))return;const _=setTimeout(()=>{u.setCurrentPage(1),y(1,j(!0)),L.current={searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,sortBy:u.sortBy,sortOrder:u.sortOrder,isDealer:b}},u.searchTerm?500:0);return()=>clearTimeout(_)},[u.searchTerm,u.statusFilter,u.priorityFilter,u.templateTypeFilter,u.form16FinancialYear,u.form16Quarter,u.sortBy,u.sortOrder,b]);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(Ie,{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(ae,{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(M,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 h-8 sm:h-9",onClick:w,disabled:i,children:[e.jsx(Ut,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${i?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:i?"Refreshing...":"Refresh"})]})]})]}),e.jsx(f,{searchTerm:u.searchTerm,statusFilter:u.statusFilter,priorityFilter:u.priorityFilter,templateTypeFilter:u.templateTypeFilter,form16FinancialYear:u.form16FinancialYear,form16Quarter:u.form16Quarter,sortBy:u.sortBy,sortOrder:u.sortOrder,onSearchChange:u.setSearchTerm,onStatusFilterChange:u.setStatusFilter,onPriorityFilterChange:u.setPriorityFilter,onTemplateTypeFilterChange:u.setTemplateTypeFilter,onForm16FinancialYearChange:u.setForm16FinancialYear,onForm16QuarterChange:u.setForm16Quarter,onSortByChange:u.setSortBy,onSortOrderChange:u.setSortOrder,onClearFilters:u.clearFilters,activeFiltersCount:u.activeFiltersCount}),e.jsx("div",{className:"space-y-3",children:D.map(R=>{const N=hk(R.priority),_=(R.templateType||R.template_type||"").toString().toUpperCase()==="FORM_16",S=R.form16Submission,U=S==null?void 0:S.displayStatus,F=U&&/balance mismatch|failed/i.test(String(U)),$=_&&U?{color:F?"bg-red-100 text-red-800 border-red-200":U==="Completed"?"bg-green-100 text-green-800 border-green-200":"bg-gray-100 text-gray-700 border-gray-200",icon:Ze,label:U}:pk(R.status);return e.jsx(q,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>t==null?void 0:t(R.id,R.title),children:e.jsx(ee,{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:R.displayId||R.id}),e.jsxs(ae,{variant:"outline",className:`${$.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`,children:[e.jsx($.icon,{className:"w-3.5 h-3.5 mr-1"}),$.label||R.status]}),R.department&&e.jsx(ae,{variant:"secondary",className:"bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex",children:R.department}),e.jsx(ae,{variant:"outline",className:`${N.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:R.priority}),(()=>{const P=(R==null?void 0:R.templateType)||(R==null?void 0:R.template_type)||"",T=(P==null?void 0:P.toUpperCase())||"";let k="Non-Templatized",B="bg-purple-100 !text-purple-600 border-purple-200";return T==="DEALER CLAIM"?(k="Dealer Claim",B="bg-blue-100 !text-blue-700 border-blue-200"):T==="FORM_16"?(k="Form 16",B="bg-emerald-100 !text-emerald-700 border-emerald-200"):T==="TEMPLATE"&&(k="Template"),e.jsx(ae,{variant:"outline",className:`${B} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:k})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:R.title}),(R.templateType||"").toString().toUpperCase()==="FORM_16"&&R.form16Submission&&e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-600 mt-1",children:[R.form16Submission.dealerCode&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Dealer:"})," ",R.form16Submission.dealerCode]}),R.form16Submission.form16aNumber&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Form 16A:"})," ",R.form16Submission.form16aNumber]}),R.form16Submission.financialYear&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"FY:"})," ",R.form16Submission.financialYear]}),R.form16Submission.quarter&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Q:"})," ",R.form16Submission.quarter]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Total amount:"})," ",R.form16Submission.totalAmount!=null?new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(R.form16Submission.totalAmount):"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Credit note:"})," ",R.form16Submission.creditNoteNumber||"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Status:"})," ",R.form16Submission.displayStatus||R.form16Submission.status||"—"]})]}),R.currentLevelSLA&&(()=>{var I;const P=!!(R.isPaused||(I=R.pauseInfo)!=null&&I.isPaused||R.status==="paused"),T=R.currentLevelSLA.percentageUsed||0,B=P?{bg:"bg-gray-100 border border-gray-300",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-600"}:T>=100?{bg:"bg-red-50 border border-red-200",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:T>=75?{bg:"bg-orange-50 border border-orange-200",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:T>=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 ${B.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:[P?e.jsx(ir,{className:`w-3.5 h-3.5 ${B.icon}`}):e.jsx(st,{className:`w-3.5 h-3.5 ${B.icon}`}),e.jsxs("span",{className:"text-xs font-medium text-gray-900",children:["TAT: ",T,"% ",P&&"(paused)"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:R.currentLevelSLA.elapsedText}),e.jsxs("span",{className:`font-semibold ${B.text}`,children:[R.currentLevelSLA.remainingText," left"]})]})]}),e.jsx(qs,{value:T,className:"h-1.5",indicatorClassName:B.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(ls,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(os,{className:"bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold",children:R.initiator.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:R.initiator.name})]}),R.currentApprover&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ls,{className:"h-6 w-6 ring-2 ring-yellow-200 shadow-sm",children:e.jsx(os,{className:"bg-yellow-500 text-white text-[10px] font-bold",children:R.currentApprover.avatar})}),e.jsx("span",{className:"font-medium text-gray-900",children:R.currentApprover.name})]}),R.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:R.approvalStep})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(dt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",R.createdAt!=="—"?wa(R.createdAt):"—"]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(fs,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})},R.id)})}),D.length===0&&e.jsx(q,{className:"shadow-lg border-0",children:e.jsxs(ee,{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(Ie,{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(M,{variant:"outline",className:"mt-4",onClick:u.clearFilters,children:"Clear all filters"})]})}),o>1&&!r&&e.jsx(q,{className:"shadow-md",children:e.jsx(ee,{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)*p+1," to ",Math.min(u.currentPage*p,d)," of ",d," open requests"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>v(u.currentPage-1),disabled:u.currentPage===1,className:"h-8 w-8 p-0",children:e.jsx(fs,{className:"h-4 w-4 rotate-180"})}),u.currentPage>3&&o>5&&e.jsxs(e.Fragment,{children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>v(1),className:"h-8 w-8 p-0",children:"1"}),e.jsx("span",{className:"text-muted-foreground",children:"..."})]}),C().map(R=>e.jsx(M,{variant:R===u.currentPage?"default":"outline",size:"sm",onClick:()=>v(R),className:`h-8 w-8 p-0 ${R===u.currentPage?"bg-re-green text-white hover:bg-re-green/90":""}`,children:R},R)),u.currentPage5&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"..."}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>v(o),className:"h-8 w-8 p-0",children:o})]}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>v(u.currentPage+1),disabled:u.currentPage===o,className:"h-8 w-8 p-0",children:e.jsx(fs,{className:"h-4 w-4"})})]})]})})})]})}function fk({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(Ie,{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(ae,{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(M,{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(Ut,{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 bk(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ca,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:qt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:qt,iconColor:"text-gray-600"}}}function jk(t){switch(t){case"closed":return{color:"bg-slate-100 text-slate-800 border-slate-300",icon:Oe,iconColor:"text-slate-600",label:"Closed",description:"Request finalized and archived"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-300",icon:At,iconColor:"text-red-600",label:"Rejected",description:"Request was declined"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ze,iconColor:"text-gray-600",label:t,description:""}}}function yk({request:t,onViewRequest:s}){var l;const a=bk(t.priority),r=jk(t.status),n=a.icon,i=r.icon;return e.jsx(q,{className:"group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]",onClick:()=>s==null?void 0:s(t.id,t.title),"data-testid":`closed-request-card-${t.id}`,children:e.jsx(ee,{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(ae,{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(ae,{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(ae,{variant:"outline",className:`${a.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`,children:t.priority}),(()=>{const o=t.templateType||"",c=(o==null?void 0:o.toUpperCase())||"";let d="Non-Templatized",m="bg-purple-100 !text-purple-600 border-purple-200";return c==="DEALER CLAIM"?(d="Dealer Claim",m="bg-blue-100 !text-blue-700 border-blue-200"):c==="FORM_16"?(d="Form 16",m="bg-emerald-100 !text-emerald-700 border-emerald-200"):c==="TEMPLATE"&&(d="Template"),e.jsx(ae,{variant:"outline",className:`${m} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`,"data-testid":"template-type-badge",children:d})})()]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed",children:t.title}),((l=t.templateType)==null?void 0:l.toUpperCase())==="FORM_16"&&t.form16Submission&&e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-600",children:[t.form16Submission.dealerCode&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Dealer:"})," ",t.form16Submission.dealerCode]}),t.form16Submission.form16aNumber&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Form 16A:"})," ",t.form16Submission.form16aNumber]}),t.form16Submission.financialYear&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"FY:"})," ",t.form16Submission.financialYear]}),t.form16Submission.quarter&&e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Q:"})," ",t.form16Submission.quarter]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Total amount:"})," ",t.form16Submission.totalAmount!=null?new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t.form16Submission.totalAmount):"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Credit note:"})," ",t.form16Submission.creditNoteNumber||"—"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-gray-500",children:"Status:"})," ",t.form16Submission.displayStatus||t.form16Submission.status||"—"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-gray-600",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ls,{className:"h-6 w-6 ring-2 ring-white shadow-sm",children:e.jsx(os,{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(Oe,{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(dt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:["Created: ",t.createdAt!=="—"?wa(t.createdAt,!0):"—"]})]}),t.dueDate&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Oe,{className:"w-3.5 h-3.5 text-slate-600"}),e.jsxs("span",{className:"font-medium",children:["Closed: ",wa(t.dueDate,!0)]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 flex items-center pt-2",children:e.jsx(fs,{className:"w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"})})]})})})}function vk({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(yk,{request:r,onViewRequest:a},r.id))})}function Nk({searchTerm:t,activeFiltersCount:s,onClearFilters:a}){return e.jsx(q,{className:"shadow-lg border-0","data-testid":"closed-requests-empty",children:e.jsxs(ee,{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(Ie,{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(M,{variant:"outline",className:"mt-4",onClick:a,"data-testid":"closed-requests-empty-clear-filters",children:"Clear all filters"})]})})}function wk(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 Ck({pagination:t,onPageChange:s}){const{currentPage:a,totalPages:r,totalRecords:n,itemsPerPage:i}=t;if(r<=1)return null;const l=wk(a,r);return e.jsx(q,{className:"shadow-md","data-testid":"closed-requests-pagination",children:e.jsx(ee,{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(M,{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(fs,{className:"h-4 w-4 rotate-180"})}),a>3&&r>5&&e.jsxs(e.Fragment,{children:[e.jsx(M,{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(M,{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(M,{variant:"outline",size:"sm",onClick:()=>s(r),className:"h-8 w-8 p-0","data-testid":"closed-requests-pagination-last",children:r})]}),e.jsx(M,{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(fs,{className:"h-4 w-4"})})]})]})})})}function Sk(t){var s,a,r,n;return{id:t.requestNumber||t.request_number||t.requestId,requestId:t.requestId,displayId:t.requestNumber||t.request_number||t.requestId,title:t.title,description:t.description,status:(t.status||"").toString().toLowerCase(),priority:(t.priority||"").toString().toLowerCase(),initiator:{name:((s=t.initiator)==null?void 0:s.displayName)||((a=t.initiator)==null?void 0:a.email)||"—",avatar:(((r=t.initiator)==null?void 0:r.displayName)||"NA").split(" ").map(i=>i[0]).join("").slice(0,2).toUpperCase()},createdAt:t.submittedAt||t.createdAt||t.created_at||"—",dueDate:t.closureDate||t.closure_date||t.closedAt||void 0,reason:t.conclusionRemark||t.conclusion_remark,department:t.department,totalLevels:t.totalLevels||0,completedLevels:((n=t.summary)==null?void 0:n.approvedLevels)||0,templateType:t.templateType||t.template_type,form16Submission:t.form16Submission??null}}function Ak(t){return t.map(Sk)}function Tk({itemsPerPage:t=10}={}){const[s,a]=h.useState([]),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=h.useCallback(async(p=1,x)=>{try{p===1&&(n(!0),a([]));const u=await Gs.listClosedByMe({page:p,limit:t,search:x==null?void 0:x.search,status:x!=null&&x.status&&x.status!=="all"?x.status:void 0,priority:x==null?void 0:x.priority,templateType:x==null?void 0:x.templateType,financialYear:x==null?void 0:x.financialYear,quarter:x==null?void 0:x.quarter,sortBy:x==null?void 0:x.sortBy,sortOrder:x==null?void 0:x.sortOrder}),g=Array.isArray(u==null?void 0:u.data)?u.data:[],f=Ak(g);a(f);const b=u==null?void 0:u.pagination;b&&c({currentPage:b.page||1,totalPages:b.totalPages||1,totalRecords:b.total||0,itemsPerPage:t})}catch(u){console.error("[ClosedRequests] Error fetching requests:",u),a([])}finally{n(!1),l(!1)}},[t]),m=h.useCallback(p=>{l(!0),d(o.currentPage,p)},[d,o.currentPage]);return{requests:s,loading:r,refreshing:i,pagination:o,fetchRequests:d,handleRefresh:m}}const kk={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",form16FinancialYear:"",form16Quarter:"",sortBy:"created",sortOrder:"desc",currentPage:1},b0=on({name:"closedRequests",initialState:kk,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setTemplateTypeFilter:(t,s)=>{t.templateTypeFilter=s.payload},setForm16FinancialYear:(t,s)=>{t.form16FinancialYear=s.payload},setForm16Quarter:(t,s)=>{t.form16Quarter=s.payload},setSortBy:(t,s)=>{t.sortBy=s.payload},setSortOrder:(t,s)=>{t.sortOrder=s.payload},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.templateTypeFilter="all",t.form16FinancialYear="",t.form16Quarter="",t.currentPage=1}}}),{setSearchTerm:Rk,setStatusFilter:Dk,setPriorityFilter:Fk,setTemplateTypeFilter:Ik,setForm16FinancialYear:Pk,setForm16Quarter:Ek,setSortBy:_k,setSortOrder:Mk,setCurrentPage:Lk,clearFilters:Ok}=b0.actions;function $k({onFiltersChange:t,debounceMs:s=500}={}){const a=Gn(),r=h.useRef(null),n=h.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,form16FinancialYear:d,form16Quarter:m,sortBy:p,sortOrder:x,currentPage:u}=dn(N=>N.closedRequests),g=h.useCallback(N=>a(Rk(N)),[a]),f=h.useCallback(N=>a(Dk(N)),[a]),b=h.useCallback(N=>a(Fk(N)),[a]),j=h.useCallback(N=>a(Ik(N)),[a]),y=h.useCallback(N=>a(Pk(N)),[a]),w=h.useCallback(N=>a(Ek(N)),[a]),v=h.useCallback(N=>a(_k(N)),[a]),C=h.useCallback(N=>a(Mk(N)),[a]),A=h.useCallback(N=>a(Lk(N)),[a]),L=h.useCallback(()=>({search:i,status:l,priority:o,templateType:c!=="all"?c:void 0,financialYear:c==="FORM_16"&&d?d:void 0,quarter:c==="FORM_16"&&m?m:void 0,sortBy:p,sortOrder:x}),[i,l,o,c,d,m,p,x]);h.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const N=setTimeout(()=>{t&&t(L())},i?s:0);return r.current=N,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,d,m,p,x,t,L,s]);const D=h.useCallback(()=>{a(Ok())},[a]),R=[i,o!=="all"?o:null,l!=="all"?l:null,c!=="all"?c:null,c==="FORM_16"&&d?"fy":null,c==="FORM_16"&&m?"q":null].filter(Boolean).length;return{searchTerm:i,priorityFilter:o,statusFilter:l,templateTypeFilter:c,form16FinancialYear:d,form16Quarter:m,sortBy:p,sortOrder:x,currentPage:u,setSearchTerm:g,setPriorityFilter:b,setStatusFilter:f,setTemplateTypeFilter:j,setForm16FinancialYear:y,setForm16Quarter:w,setSortBy:v,setSortOrder:C,setCurrentPage:A,clearFilters:D,activeFiltersCount:R,getFilters:L}}function Uk({onViewRequest:t}){const s=Tk({itemsPerPage:10}),a=h.useRef(s.fetchRequests);a.current=s.fetchRequests;const r=$k(),n=h.useMemo(()=>{try{const x=at.getUserData();return lc(x)}catch(x){return console.error("[ClosedRequests] Error getting user filter type:",x),"STANDARD"}},[]),i=h.useMemo(()=>uk(n),[n]),l=n==="DEALER",o=h.useCallback(()=>{const x=r.getFilters();return{search:x.search||void 0,status:x.status!=="all"?x.status:void 0,priority:!l&&x.priority?x.priority:void 0,templateType:x.templateType,financialYear:x.financialYear,quarter:x.quarter,sortBy:x.sortBy,sortOrder:x.sortOrder}},[r,l]),c=h.useRef({searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,form16FinancialYear:r.form16FinancialYear,form16Quarter:r.form16Quarter,sortBy:r.sortBy,sortOrder:r.sortOrder}),d=h.useRef(!1);h.useEffect(()=>{const x=r.currentPage||1;a.current(x,o()),d.current=!0},[l]),h.useEffect(()=>{if(!d.current)return;const x=c.current;if(!(x.searchTerm!==r.searchTerm||x.statusFilter!==r.statusFilter||x.priorityFilter!==r.priorityFilter||x.templateTypeFilter!==r.templateTypeFilter||x.form16FinancialYear!==r.form16FinancialYear||x.form16Quarter!==r.form16Quarter||x.sortBy!==r.sortBy||x.sortOrder!==r.sortOrder))return;const g=setTimeout(()=>{r.setCurrentPage(1),a.current(1,o()),c.current={searchTerm:r.searchTerm,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,templateTypeFilter:r.templateTypeFilter,form16FinancialYear:r.form16FinancialYear,form16Quarter:r.form16Quarter,sortBy:r.sortBy,sortOrder:r.sortOrder}},r.searchTerm!==x.searchTerm?500:0);return()=>clearTimeout(g)},[r.searchTerm,r.statusFilter,r.priorityFilter,r.templateTypeFilter,r.form16FinancialYear,r.form16Quarter,r.sortBy,r.sortOrder,l]);const m=h.useCallback(x=>{x>=1&&x<=s.pagination.totalPages&&(r.setCurrentPage(x),s.fetchRequests(x,o()))},[s,r,o]),p=h.useCallback(()=>{s.handleRefresh(o())},[s,o]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"closed-requests-page",children:[e.jsx(fk,{totalRecords:s.pagination.totalRecords,loading:s.loading,refreshing:s.refreshing,onRefresh:p}),e.jsx(i,{searchTerm:r.searchTerm,priorityFilter:r.priorityFilter,statusFilter:r.statusFilter,templateTypeFilter:r.templateTypeFilter,form16FinancialYear:r.form16FinancialYear,form16Quarter:r.form16Quarter,sortBy:r.sortBy,sortOrder:r.sortOrder,activeFiltersCount:r.activeFiltersCount,onSearchChange:r.setSearchTerm,onPriorityChange:r.setPriorityFilter,onStatusChange:r.setStatusFilter,onTemplateTypeChange:r.setTemplateTypeFilter,onForm16FinancialYearChange:r.setForm16FinancialYear,onForm16QuarterChange:r.setForm16Quarter,onSortByChange:r.setSortBy,onSortOrderChange:()=>r.setSortOrder(r.sortOrder==="asc"?"desc":"asc"),onClearFilters:r.clearFilters}),e.jsx(vk,{requests:s.requests,loading:s.loading,onViewRequest:t}),s.requests.length===0&&!s.loading&&e.jsx(Nk,{searchTerm:r.searchTerm,activeFiltersCount:r.activeFiltersCount,onClearFilters:r.clearFilters}),!s.loading&&e.jsx(Ck,{pagination:s.pagination,onPageChange:m})]})}function Bk(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 Vk(t){return Bk(t)?"DEALER_CLAIM":"CUSTOM"}function zk(t,s){return`/request/${t}`}class Hk extends h.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(es,{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(M,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(M,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}}function Wk({requestId:t,onBack:s,dynamicRequests:a=[]}){const n=_a().requestId||t||"",{user:i}=cs(),{apiRequest:l,loading:o}=Vc(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(Ut,{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=Vk(l),d=dk(c);return e.jsx(d,{requestId:t,onBack:s,dynamicRequests:a})}function Gk(t){return e.jsx(Hk,{children:e.jsx(Wk,{...t})})}function Yk({onViewSummary:t}){const s=ys(),[a,r]=h.useState([]),[n,i]=h.useState(!0),[l,o]=h.useState(""),[c,d]=h.useState(1),[m,p]=h.useState(1),[x,u]=h.useState(0),g=10,f=h.useCallback(async(w=1)=>{try{i(!0);const v=await BT({page:w,limit:g});r(v.data||[]),p(v.pagination.totalPages||1),u(v.pagination.total||0),d(v.pagination.page||1)}catch(v){console.error("Failed to fetch shared summaries:",v),X.error("Failed to load shared summaries")}finally{i(!1)}},[]);h.useEffect(()=>{f(1)},[f]);const b=async w=>{try{await n0(w),r(v=>v.map(C=>C.sharedSummaryId===w?{...C,isRead:!0,viewedAt:new Date().toISOString()}:C)),t?t(w):s(`/shared-summaries/${w}`)}catch(v){console.error("Failed to mark as viewed:",v),t?t(w):s(`/shared-summaries/${w}`)}},j=w=>{w>=1&&w<=m&&f(w)},y=a.filter(w=>{var C,A,L,D;if(!l)return!0;const v=l.toLowerCase();return((C=w.title)==null?void 0:C.toLowerCase().includes(v))||((A=w.requestNumber)==null?void 0:A.toLowerCase().includes(v))||((L=w.initiatorName)==null?void 0:L.toLowerCase().includes(v))||((D=w.sharedByName)==null?void 0:D.toLowerCase().includes(v))});return e.jsx("div",{className:"min-h-screen bg-gray-50 p-3 sm:p-4 md:p-6 overflow-x-hidden",children:e.jsxs("div",{className:"max-w-7xl mx-auto w-full",children:[e.jsxs("div",{className:"mb-4 sm:mb-6",children:[e.jsx("h1",{className:"text-xl sm:text-2xl md:text-3xl font-bold text-gray-900 mb-1 sm:mb-2",children:"Shared Summaries"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600",children:"View summaries of closed requests shared with you"})]}),e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs("div",{className:"relative",children:[e.jsx(Ss,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ce,{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(Qe,{className:"h-8 w-8 animate-spin text-blue-600"})}),!n&&y.length===0&&e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 p-6 sm:p-12 text-center",children:[e.jsx(Ie,{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&&y.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-3 sm:gap-4 mb-4 sm:mb-6",children:y.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:()=>b(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(Rb,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}):e.jsx(St,{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(dt,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Shared: ",et(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(St,{className:"h-3.5 w-3.5 sm:h-4 sm:w-4 flex-shrink-0"}),e.jsxs("span",{className:"truncate",children:["Viewed: ",et(new Date(w.viewedAt),"MMM dd, yyyy HH:mm")]})]})]})]}),e.jsx(M,{variant:"outline",size:"sm",className:"w-full sm:w-auto flex-shrink-0",onClick:v=>{v.stopPropagation(),b(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(M,{variant:"outline",size:"sm",onClick:()=>j(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(M,{variant:"outline",size:"sm",onClick:()=>j(c+1),disabled:c===m,className:"text-xs sm:text-sm",children:"Next"})]})]})]})]})})}function Kk(){const{sharedSummaryId:t}=_a(),s=ys(),[a,r]=h.useState(null),[n,i]=h.useState(!0);h.useEffect(()=>{if(!t){s("/shared-summaries");return}(async()=>{var m,p;try{i(!0);try{await n0(t)}catch(u){console.warn("Failed to mark as viewed:",u)}const x=await Hc(t);r(x)}catch(x){console.error("Failed to fetch summary details:",x),X.error(((p=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:p.message)||"Failed to load summary"),s("/shared-summaries")}finally{i(!1)}})()},[t,s]);const l=d=>{const m=d.toLowerCase();return m==="approved"?e.jsx(Oe,{className:"h-4 w-4 text-green-600"}):m==="rejected"?e.jsx(At,{className:"h-4 w-4 text-red-600"}):m==="pending"||m==="in progress"?e.jsx(st,{className:"h-4 w-4 text-orange-600"}):e.jsx(Ie,{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(Qe,{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(M,{variant:"ghost",size:"sm",onClick:()=>s("/shared-summaries"),className:"mb-4",children:[e.jsx(Cs,{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(ae,{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(_s,{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:et(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:et(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(ae,{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(_s,{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(Ie,{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(M,{onClick:()=>s("/shared-summaries"),children:"Go Back"})]})})}function Qk(){const{requestId:t}=_a(),s=ys(),a=i=>{s(`/${i}`)},r=()=>{s("/new-request")},n=()=>{s("/login")};return e.jsx(Xt,{currentPage:"work-notes",onNavigate:a,onNewRequest:r,onLogout:n,children:e.jsx("div",{className:"h-full w-full overflow-hidden",children:e.jsx(r0,{requestId:t||""})})})}function j0({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(ae,{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 ta({label:t,value:s,icon:a,iconColor:r,gradient:n,textColor:i,valueColor:l,testId:o="stats-card",onClick:c}){return e.jsx(q,{className:`${n} border transition-shadow ${c?"cursor-pointer hover:shadow-lg":"hover:shadow-md"}`,"data-testid":o,onClick:c,children:e.jsx(ee,{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 Xk({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(ta,{label:"Total",value:t.total,icon:Ie,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(ta,{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(ta,{label:"Paused",value:t.paused,icon:dr,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(ta,{label:"Approved",value:t.approved,icon:Oe,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(ta,{label:"Rejected",value:t.rejected,icon:At,iconColor:"text-red-600",gradient:"bg-gradient-to-br from-red-50 to-red-100 border-red-200",textColor:"text-red-700",valueColor:"text-red-900",testId:"stat-rejected",onClick:s?()=>a("rejected"):void 0}),e.jsx(ta,{label:"Draft",value:t.draft,icon:el,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(ta,{label:"Closed",value:t.closed,icon:tl,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 Jk({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,onSearchChange:n,onStatusChange:i,onPriorityChange:l,onTemplateTypeChange:o}){return e.jsx(q,{className:"border-gray-200","data-testid":"my-requests-filters",children:e.jsx(ee,{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(Ss,{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(Ce,{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(He,{value:s,onValueChange:i,children:[e.jsx(Ge,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"status-filter",children:e.jsx(We,{placeholder:"Status"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"draft",children:"Draft"}),e.jsx(J,{value:"pending",children:"Pending"}),e.jsx(J,{value:"paused",children:"Paused"}),e.jsx(J,{value:"approved",children:"Approved"}),e.jsx(J,{value:"rejected",children:"Rejected"}),e.jsx(J,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:a,onValueChange:l,children:[e.jsx(Ge,{className:"flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10","data-testid":"priority-filter",children:e.jsx(We,{placeholder:"Priority"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Priority"}),e.jsx(J,{value:"express",children:"Express"}),e.jsx(J,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:r,onValueChange:o,children:[e.jsx(Ge,{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(We,{placeholder:"Template Type"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"})]})]})]})]})})})}function Zk(t){switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ca,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:qt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:qt,iconColor:"text-gray-600"}}}function qk(t){switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Oe,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:At,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon:st,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Oe,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:el,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ze,iconColor:"text-gray-600"}}}const e4=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 t4({request:t,index:s,onViewRequest:a}){var o;const r=qk(t.status),n=Zk(t.priority),i=r.icon,l=n.icon;return e.jsx(Ht.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(q,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(ee,{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(ae,{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(ae,{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(dr,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ae,{variant:"outline",className:`${n.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(l,{className:"w-3 h-3 mr-1"}),t.priority]}),(()=>{const c=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",d=(c==null?void 0:c.toUpperCase())||"";let m="Non-Templatized",p="bg-purple-100 !text-purple-600 border-purple-200";return d==="DEALER CLAIM"?(m="Dealer Claim",p="bg-blue-100 !text-blue-700 border-blue-200"):d==="FORM_16"?(m="Form 16",p="bg-emerald-100 !text-emerald-700 border-emerald-200"):d==="TEMPLATE"&&(m="Template"),e.jsx(ae,{variant:"outline",className:`${p} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:m})})()]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 line-clamp-2 leading-relaxed","data-testid":"request-description",children:e4(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:"})," ",wa(t.submittedDate)]})]})]}),e.jsx(fs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400 group-hover:text-blue-600 transition-colors flex-shrink-0 mt-1"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-4 pt-3 border-t border-gray-100",children:[e.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4",children:((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16"?e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ws,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-emerald-600 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm font-medium text-emerald-700","data-testid":"form16-ocr-flow",children:"Form 16 OCR FLOW"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(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(Ws,{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: ",wa(t.submittedDate)]})]})]})]})})})})}function s4({requests:t,loading:s,searchTerm:a,statusFilter:r,priorityFilter:n,onViewRequest:i}){if(s)return e.jsx(q,{"data-testid":"loading-state",children:e.jsx(ee,{className:"p-6 text-sm text-gray-600",children:"Loading your requests…"})});if(t.length===0){const l=a||r!=="all"||n!=="all";return e.jsx(q,{"data-testid":"empty-state",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(Ie,{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(t4,{request:l,index:o,onViewRequest:i},l.id))})}function a4(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 y0(t){return Array.isArray(t)?t.map(a4):[]}function r4({itemsPerPage:t=10}={}){const[s,a]=h.useState([]),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState({currentPage:1,totalPages:1,totalRecords:0,itemsPerPage:t}),d=h.useCallback(async(m=1,p)=>{try{m===1&&(n(!0),a([]));const x=await Gs.listMyInitiatedWorkflows({page:m,limit:t,search:p==null?void 0:p.search,status:p==null?void 0:p.status,priority:p==null?void 0:p.priority,templateType:p==null?void 0:p.templateType}),u=Array.isArray(x==null?void 0:x.data)?x.data:[],g=y0(u);a(g),l(!0);const f=x==null?void 0:x.pagination;f&&c({currentPage:f.page||1,totalPages:f.totalPages||1,totalRecords:f.total||0,itemsPerPage:t})}catch(x){console.error("[MyRequests] Error fetching requests:",x),a([]),l(!0)}finally{n(!1)}},[t]);return{requests:s,loading:r,hasFetchedFromApi:i,pagination:o,fetchMyRequests:d}}const n4={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",currentPage:1},v0=on({name:"myRequests",initialState:n4,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:i4,setStatusFilter:l4,setPriorityFilter:o4,setTemplateTypeFilter:c4,setCurrentPage:d4,clearFilters:m4}=v0.actions;function u4({onFiltersChange:t,debounceMs:s=500}={}){const a=Gn(),r=h.useRef(null),n=h.useRef(!0),{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d}=dn(j=>j.myRequests),m=h.useCallback(j=>a(i4(j)),[a]),p=h.useCallback(j=>a(l4(j)),[a]),x=h.useCallback(j=>a(o4(j)),[a]),u=h.useCallback(j=>a(c4(j)),[a]),g=h.useCallback(j=>a(d4(j)),[a]),f=h.useCallback(()=>({search:i,status:l,priority:o,templateType:c}),[i,l,o,c]);h.useEffect(()=>{if(n.current){n.current=!1;return}r.current&&clearTimeout(r.current);const j=setTimeout(()=>{t&&t(f())},i?s:0);return r.current=j,()=>{r.current&&clearTimeout(r.current)}},[i,l,o,c,t,f,s]);const b=h.useCallback(()=>{a(m4())},[a]);return{searchTerm:i,statusFilter:l,priorityFilter:o,templateTypeFilter:c,currentPage:d,setSearchTerm:m,setStatusFilter:p,setPriorityFilter:x,setTemplateTypeFilter:u,setCurrentPage:g,getFilters:f,resetFilters:b}}function x4({onViewRequest:t,dynamicRequests:s=[]}){const{user:a}=cs(),r=r4({itemsPerPage:10}),n=h.useRef(r.fetchMyRequests);n.current=r.fetchMyRequests;const i=u4(),l=h.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter}),o=h.useRef(!1);h.useEffect(()=>{const j=i.currentPage||1;n.current(j,{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},[]),h.useEffect(()=>{if(!o.current)return;const j=l.current;if(!(j.searchTerm!==i.searchTerm||j.statusFilter!==i.statusFilter||j.priorityFilter!==i.priorityFilter||j.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!==j.searchTerm?500:0);return()=>clearTimeout(w)},[i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter]);const[c,d]=h.useState(null),[m,p]=h.useState(!1),x=h.useCallback(async()=>{if(a!=null&&a.userId)try{p(!0);const j=await Mt.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:j.totalRequests||0,pending:j.openRequests||0,paused:j.pausedRequests||0,approved:j.approvedRequests||0,rejected:j.rejectedRequests||0,draft:j.draftRequests||0,closed:j.closedRequests||0})}catch(j){console.error("Failed to fetch backend stats:",j),d(null)}finally{p(!1)}},[a==null?void 0:a.userId,i.searchTerm,i.priorityFilter,i.templateTypeFilter]);h.useEffect(()=>{const j=setTimeout(()=>{x()},i.searchTerm?500:0);return()=>clearTimeout(j)},[i.searchTerm,i.priorityFilter,i.templateTypeFilter,x]);const u=y0(s),g=r.hasFetchedFromApi?r.requests:u,f=h.useMemo(()=>c?{total:c.total||0,pending:c.pending||0,paused:c.paused||0,approved:c.approved||0,rejected:c.rejected||0,draft:c.draft||0,closed:c.closed||0}:{total:0,pending:0,paused:0,approved:0,rejected:0,draft:0,closed:0},[c]),b=h.useCallback(j=>{j>=1&&j<=r.pagination.totalPages&&(i.setCurrentPage(j),r.fetchMyRequests(j,{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(j0,{icon:Ie,title:"My Requests",description:"Track and manage all your submitted requests",badge:{value:`${f.total} total`,label:"requests",loading:r.loading||m},testId:"my-requests-header"}),e.jsx(Xk,{stats:f,onStatusFilter:j=>{i.setStatusFilter(j)}}),e.jsx(Jk,{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(s4,{requests:g,loading:r.loading,searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,onViewRequest:t}),e.jsx(Mr,{currentPage:i.currentPage||r.pagination.currentPage,totalPages:r.pagination.totalPages,totalRecords:r.pagination.totalRecords,itemsPerPage:r.pagination.itemsPerPage,onPageChange:b,loading:r.loading,itemLabel:"requests",testIdPrefix:"my-requests-pagination"})]})}function N0({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(j0,{icon:Ie,title:i(),description:l(),testId:"requests-header"}),e.jsx(ae,{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(M,{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(Ut,{className:"w-4 h-4 mr-2 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rt,{className:"w-4 h-4 mr-2"}),"Export"]})})]})}function w0({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(ta,{label:"Total",value:t.total,icon:Ie,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(ta,{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(ta,{label:"Paused",value:t.paused,icon:dr,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(ta,{label:"Approved",value:t.approved,icon:Oe,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(ta,{label:"Rejected",value:t.rejected,icon:At,iconColor:"text-red-600",gradient:"bg-gradient-to-br from-red-50 to-red-100 border-red-200",textColor:"text-red-700",valueColor:"text-red-900",testId:"stat-rejected",onClick:s?()=>a("rejected"):void 0}),e.jsx(ta,{label:"Closed",value:t.closed,icon:tl,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 h4=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ca,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:qt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:qt,iconColor:"text-gray-600"}}},Sx=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:Oe,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected",icon:At,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending",icon:st,iconColor:"text-yellow-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"closed",icon:Oe,iconColor:"text-gray-600"};case"draft":return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"draft",icon:el,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:Ze,iconColor:"text-gray-600"}}},p4=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 g4(t){return t==null?"—":new Intl.NumberFormat("en-IN",{style:"currency",currency:"INR",maximumFractionDigits:0}).format(t)}function f4({request:t,index:s,onViewRequest:a}){var p;const r=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",n=t==null?void 0:t.form16Submission,i=n==null?void 0:n.displayStatus,l=i&&/balance mismatch|failed/i.test(String(i)),o=r&&i?{color:l?"bg-red-100 !text-red-800 border-red-200":i==="Completed"?"bg-green-100 !text-green-800 border-green-200":"bg-gray-100 !text-gray-700 border-gray-200",icon:Sx(t.status).icon,label:i}:Sx(t.status),c=h4(t.priority),d=o.icon,m=c.icon;return e.jsx(Ht.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:s*.1},children:e.jsx(q,{className:"group hover:shadow-lg transition-all duration-300 cursor-pointer border border-gray-200 shadow-sm hover:shadow-md",onClick:()=>a(t.id,t.title,t.status),"data-testid":`request-card-${t.id}`,children:e.jsx(ee,{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(ae,{variant:"outline",className:`${o.color} border font-medium text-xs shrink-0`,"data-testid":"status-badge",children:[e.jsx(d,{className:"w-3 h-3 mr-1"}),e.jsx("span",{className:"capitalize",children:o.label})]}),(((p=t.pauseInfo)==null?void 0:p.isPaused)||t.isPaused)&&e.jsxs(ae,{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(dr,{className:"w-3 h-3 mr-1"}),"Paused"]}),e.jsxs(ae,{variant:"outline",className:`${c.color} border font-medium text-xs capitalize shrink-0`,"data-testid":"priority-badge",children:[e.jsx(m,{className:"w-3 h-3 mr-1"}),t.priority]}),(()=>{const x=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",u=(x==null?void 0:x.toUpperCase())||"";let g="Non-Templatized",f="bg-purple-100 !text-purple-600 border-purple-200";return u==="DEALER CLAIM"?(g="Dealer Claim",f="bg-blue-100 !text-blue-700 border-blue-200"):u==="FORM_16"?(g="Form 16",f="bg-emerald-100 !text-emerald-700 border-emerald-200"):u==="TEMPLATE"&&(g="Template"),e.jsx(ae,{variant:"outline",className:`${f} font-medium text-xs shrink-0`,"data-testid":"template-type-badge",children:g})})(),t.department&&e.jsx(ae,{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:p4(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:"})," ",wa(t.submittedDate)]}),r&&n&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"truncate","data-testid":"form16-total-amount",children:[e.jsx("span",{className:"font-medium",children:"Total amount:"})," ",n.totalAmount!=null?g4(n.totalAmount):"—"]}),e.jsxs("span",{className:"truncate","data-testid":"form16-credit-note",children:[e.jsx("span",{className:"font-medium",children:"Credit note:"})," ",n.creditNoteNumber||"—"]})]})]})]}),e.jsx(fs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400 group-hover:text-blue-600 transition-colors flex-shrink-0 mt-1"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-4 pt-3 border-t border-gray-100",children:[e.jsx("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4",children:((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16"?e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ws,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-emerald-600 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm font-medium text-emerald-700","data-testid":"form16-ocr-flow",children:"Form 16 OCR FLOW"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(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(Ws,{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: ",wa(t.submittedDate)]})]})]})]})})})})}function C0({requests:t,loading:s,hasActiveFilters:a,onViewRequest:r}){return s?e.jsx(q,{"data-testid":"loading-state",children:e.jsx(ee,{className:"p-6 text-sm text-gray-600",children:"Loading requests…"})}):t.length===0?e.jsx(q,{"data-testid":"empty-state",children:e.jsxs(ee,{className:"p-12 text-center",children:[e.jsx(Ie,{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(f4,{request:n,index:i,onViewRequest:r},n.id))})}const b4={searchTerm:"",statusFilter:"all",priorityFilter:"all",templateTypeFilter:"all",requestTypeFilter:"all",form16FinancialYear:"all",form16Quarter:"all",slaComplianceFilter:"all",departmentFilter:"all",initiatorFilter:"all",approverFilter:"all",approverFilterType:"current",dateRange:"all",customStartDate:void 0,customEndDate:void 0,showCustomDatePicker:!1,currentPage:1},S0=on({name:"requests",initialState:b4,reducers:{setSearchTerm:(t,s)=>{t.searchTerm=s.payload},setStatusFilter:(t,s)=>{t.statusFilter=s.payload},setPriorityFilter:(t,s)=>{t.priorityFilter=s.payload},setTemplateTypeFilter:(t,s)=>{t.templateTypeFilter=s.payload,s.payload!=="FORM_16"&&(t.form16FinancialYear="all",t.form16Quarter="all")},setRequestTypeFilter:(t,s)=>{t.requestTypeFilter=s.payload,s.payload!=="form_16"&&(t.form16FinancialYear="all",t.form16Quarter="all")},setForm16FinancialYear:(t,s)=>{t.form16FinancialYear=s.payload},setForm16Quarter:(t,s)=>{t.form16Quarter=s.payload},setSlaComplianceFilter:(t,s)=>{t.slaComplianceFilter=s.payload},setDepartmentFilter:(t,s)=>{t.departmentFilter=s.payload},setInitiatorFilter:(t,s)=>{t.initiatorFilter=s.payload},setApproverFilter:(t,s)=>{t.approverFilter=s.payload},setApproverFilterType:(t,s)=>{t.approverFilterType=s.payload},setDateRange:(t,s)=>{t.dateRange=s.payload},setCustomStartDate:(t,s)=>{t.customStartDate=s.payload},setCustomEndDate:(t,s)=>{t.customEndDate=s.payload},setShowCustomDatePicker:(t,s)=>{t.showCustomDatePicker=s.payload},setCurrentPage:(t,s)=>{t.currentPage=s.payload},clearFilters:t=>{t.searchTerm="",t.statusFilter="all",t.priorityFilter="all",t.templateTypeFilter="all",t.requestTypeFilter="all",t.form16FinancialYear="all",t.form16Quarter="all",t.slaComplianceFilter="all",t.departmentFilter="all",t.initiatorFilter="all",t.approverFilter="all",t.approverFilterType="current",t.dateRange="all",t.customStartDate=void 0,t.customEndDate=void 0,t.showCustomDatePicker=!1,t.currentPage=1}}}),{setSearchTerm:j4,setStatusFilter:y4,setPriorityFilter:v4,setTemplateTypeFilter:N4,setRequestTypeFilter:w4,setForm16FinancialYear:C4,setForm16Quarter:S4,setSlaComplianceFilter:A4,setDepartmentFilter:T4,setInitiatorFilter:k4,setApproverFilter:R4,setApproverFilterType:D4,setDateRange:Ax,setCustomStartDate:Kl,setCustomEndDate:Ql,setShowCustomDatePicker:di,setCurrentPage:F4,clearFilters:I4}=S0.actions;function A0(){const t=Gn(),{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,requestTypeFilter:i,form16FinancialYear:l,form16Quarter:o,slaComplianceFilter:c,departmentFilter:d,initiatorFilter:m,approverFilter:p,approverFilterType:x,dateRange:u,customStartDate:g,customEndDate:f,showCustomDatePicker:b,currentPage:j}=dn(Z=>Z.requests),y=h.useCallback(Z=>t(j4(Z)),[t]),w=h.useCallback(Z=>t(y4(Z)),[t]),v=h.useCallback(Z=>t(v4(Z)),[t]),C=h.useCallback(Z=>t(N4(Z)),[t]),A=h.useCallback(Z=>t(w4(Z)),[t]),L=h.useCallback(Z=>t(C4(Z)),[t]),D=h.useCallback(Z=>t(S4(Z)),[t]),R=h.useCallback(Z=>t(A4(Z)),[t]),N=h.useCallback(Z=>t(T4(Z)),[t]),_=h.useCallback(Z=>t(k4(Z)),[t]),S=h.useCallback(Z=>t(R4(Z)),[t]),U=h.useCallback(Z=>t(D4(Z)),[t]),F=h.useCallback(Z=>t(Ax(Z)),[t]),$=h.useCallback(Z=>t(Kl(Z)),[t]),P=h.useCallback(Z=>t(Ql(Z)),[t]),T=h.useCallback(Z=>t(di(Z)),[t]),k=h.useCallback(Z=>t(F4(Z)),[t]),B=h.useCallback(()=>n==="FORM_16"?{templateType:"FORM_16",financialYear:l!=="all"?l:void 0,quarter:o!=="all"?o:void 0}:{search:s||void 0,status:a!=="all"?a:void 0,priority:r!=="all"?r:void 0,templateType:n!=="all"?n:void 0,slaCompliance:c!=="all"?c:void 0,department:d!=="all"?d:void 0,initiator:m!=="all"?m:void 0,approver:p!=="all"?p:void 0,approverType:p!=="all"?x:void 0,dateRange:u,startDate:g,endDate:f},[s,a,r,n,l,o,c,d,m,p,x,u,g,f]),I=h.useCallback(()=>{t(I4())},[t]),E=h.useCallback(Z=>{const O=Z;t(Ax(O)),O!=="custom"?(t(Kl(void 0)),t(Ql(void 0)),t(di(!1))):t(di(!0))},[t]),W=h.useCallback(()=>{g&&f&&(g>f&&(t(Kl(f)),t(Ql(g))),t(di(!1)))},[g,f,t]),V=n==="FORM_16";return{searchTerm:s,statusFilter:a,priorityFilter:r,templateTypeFilter:n,requestTypeFilter:i,form16FinancialYear:l,form16Quarter:o,isForm16:V,slaComplianceFilter:c,departmentFilter:d,initiatorFilter:m,approverFilter:p,approverFilterType:x,dateRange:u,customStartDate:g,customEndDate:f,showCustomDatePicker:b,currentPage:j,hasActiveFilters:V?n==="FORM_16"&&(l!=="all"||o!=="all"):!!(s||a!=="all"||r!=="all"||n!=="all"||i!=="all"||i==="form_16"&&(l!=="all"||o!=="all")||c!=="all"||d!=="all"||m!=="all"||p!=="all"||u!=="all"||g||f),setSearchTerm:y,setStatusFilter:w,setPriorityFilter:v,setTemplateTypeFilter:C,setRequestTypeFilter:A,setForm16FinancialYear:L,setForm16Quarter:D,setSlaComplianceFilter:R,setDepartmentFilter:N,setInitiatorFilter:_,setApproverFilter:S,setApproverFilterType:U,setDateRange:F,setCustomStartDate:$,setCustomEndDate:P,setShowCustomDatePicker:T,setCurrentPage:k,getFilters:B,clearFilters:I,handleDateRangeChange:E,handleApplyCustomDate:W}}function Ui({filterValue:t,onFilterChange:s,source:a="default"}){const[r,n]=h.useState(""),[i,l]=h.useState([]),[o,c]=h.useState(!1),[d,m]=h.useState(null),[p,x]=h.useState(!1),u=h.useRef(null);h.useEffect(()=>{async function j(){if(t!=="all"&&!d)try{const y=await sa.getUserById(t);y&&(m(y),n(y.displayName||y.email))}catch(y){console.error("Failed to fetch user detail for search:",y)}else t==="all"&&(m(null),n(""))}j()},[t]),h.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const g=h.useCallback(j=>{if(n(j),u.current&&clearTimeout(u.current),!j||j.trim().length<2){l([]),c(!1);return}u.current=setTimeout(async()=>{var y;x(!0);try{const v=((y=(await sa.searchUsers(j.trim(),10,a)).data)==null?void 0:y.data)||[];l(v),c(v.length>0)}catch(w){console.error("Search API failed:",w),l([]),c(!1)}finally{x(!1)}},400)},[a]),f=h.useCallback(j=>{m(j),s(j.userId),n(j.displayName||j.email),c(!1),l([])},[s]),b=h.useCallback(()=>{m(null),s("all"),n(""),c(!1),l([])},[s]);return{searchQuery:r,searchResults:i,showResults:o,selectedUser:d,searching:p,handleSearch:g,handleSelect:f,handleClear:b,setShowResults:c}}function P4(t){var d,m,p,x,u,g,f;const s=t.submittedAt||t.submitted_at||t.createdAt||t.created_at,a=(t.priority||"").toString().toLowerCase(),r=(t.status||"").toString().toUpperCase();let n="—",i="—";const l=t.currentApprover||t.current_approver||t.currentApproverData;if(l)n=l.name||l.approverName||l.displayName||l.email||l.approverEmail||"—";else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const b=t.approvals.find(j=>{const y=(j.status||"").toString().toUpperCase();return y==="PENDING"||y==="IN_PROGRESS"});if(b)n=b.approverName||((d=b.approver)==null?void 0:d.name)||((m=b.approver)==null?void 0:m.displayName)||b.approverEmail||((p=b.approver)==null?void 0:p.email)||"—";else{const y=[...t.approvals].sort((w,v)=>{const C=w.levelNumber||w.level_number||0;return(v.levelNumber||v.level_number||0)-C})[0];y&&(n=y.approverName||((x=y.approver)==null?void 0:x.name)||((u=y.approver)==null?void 0:u.displayName)||y.approverEmail||((g=y.approver)==null?void 0:g.email)||"—")}}const o=t.currentLevel||t.current_level||t.currentLevelNumber||t.current_level_number,c=t.totalLevels||t.total_levels||t.totalLevelsCount||t.total_levels_count;if(o&&c)i=`${o} of ${c}`;else if(t.approvals&&Array.isArray(t.approvals)&&t.approvals.length>0){const b=t.approvals.find(j=>{const y=(j.status||"").toString().toUpperCase();return y==="PENDING"||y==="IN_PROGRESS"});if(b){const j=b.levelNumber||b.level_number||0,y=c||t.approvals.length;i=`${j} of ${y}`}else c&&(i=`${c} of ${c}`)}else t.currentStep&&t.totalSteps&&(i=`${t.currentStep} of ${t.totalSteps}`);return{id:t.requestNumber||t.request_number||t.requestId||t.id||t.request_id,requestId:t.requestId||t.id||t.request_id,displayId:t.requestNumber||t.request_number||t.id,title:t.title,description:t.description,status:r.toLowerCase().replace("_","-"),priority:a,department:t.department||((f=t.initiator)==null?void 0:f.department),submittedDate:t.submittedAt||(t.createdAt?new Date(t.createdAt).toISOString().split("T")[0]:void 0),createdAt:s,currentApprover:n,approverLevel:i,templateType:t.templateType||t.template_type,workflowType:t.workflowType||t.workflow_type,templateName:t.templateName||t.template_name,form16Submission:t.form16Submission??null}}function T0(t){return Array.isArray(t)?t.map(P4):[]}function E4(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,p=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:p}}else return s&&a?{total:a.total,pending:a.pending,paused:a.paused||0,approved:a.approved,rejected:a.rejected,draft:a.draft,closed:a.closed}:{total:n||i.length,pending:i.filter(o=>o.status==="pending"||o.status==="in-progress").length,paused:i.filter(o=>o.status==="paused").length,approved:i.filter(o=>o.status==="approved").length,rejected:i.filter(o=>o.status==="rejected").length,draft:i.filter(o=>o.status==="draft").length,closed:i.filter(o=>o.status==="closed").length}}var k0={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Vi,function(){return function(a,r){r.prototype.isSameOrBefore=function(n,i){return this.isSame(n,i)||this.isBefore(n,i)}}})})(k0);var _4=k0.exports;const R0=zi(_4);var D0={exports:{}};(function(t,s){(function(a,r){t.exports=r()})(Vi,function(){return function(a,r){r.prototype.isSameOrAfter=function(n,i){return this.isSame(n,i)||this.isAfter(n,i)}}})})(D0);var M4=D0.exports;const F0=zi(M4);ss.extend(F0);ss.extend(R0);function L4(t,s){let a=[...t];if(s.search){const r=s.search.toLowerCase();a=a.filter(n=>{var i,l,o,c;return((i=n.title)==null?void 0:i.toLowerCase().includes(r))||((l=n.description)==null?void 0:l.toLowerCase().includes(r))||((o=n.requestNumber)==null?void 0:o.toLowerCase().includes(r))||((c=n.request_number)==null?void 0:c.toLowerCase().includes(r))})}if(s.status&&s.status!=="all")if(s.status.toLowerCase()==="pending")a=a.filter(r=>{var l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return(n==="PENDING"||n==="IN_PROGRESS")&&!i});else if(s.status.toLowerCase()==="paused")a=a.filter(r=>{var l;const n=(r.status||"").toString().toUpperCase(),i=((l=r.pauseInfo)==null?void 0:l.isPaused)||r.isPaused||!1;return n==="PAUSED"||i});else{const r=s.status.toUpperCase().replace("-","_");a=a.filter(n=>{var o;const i=(n.status||"").toString().toUpperCase(),l=((o=n.pauseInfo)==null?void 0:o.isPaused)||n.isPaused||!1;return r==="IN_PROGRESS"||r==="IN-PROGRESS"?i==="IN_PROGRESS"&&!l:i===r&&!l})}if(s.priority&&s.priority!=="all"&&(a=a.filter(r=>{var n;return(r.priority||"").toString().toLowerCase()===((n=s.priority)==null?void 0:n.toLowerCase())})),s.department&&s.department!=="all"&&(a=a.filter(r=>{var i;return(r.department||((i=r.initiator)==null?void 0:i.department)||"")===s.department})),s.initiator&&s.initiator!=="all"&&(a=a.filter(r=>{var i,l;return(r.initiatorId||r.initiator_id||((i=r.initiator)==null?void 0:i.userId)||((l=r.initiator)==null?void 0:l.user_id)||(r.initiator&&typeof r.initiator=="object"&&"userId"in r.initiator?r.initiator.userId:null))===s.initiator})),s.approver&&s.approver!=="all"&&((s.approverType||"current")==="current"?a=a.filter(n=>{var l,o,c,d,m,p;return(((l=n.currentApprover)==null?void 0:l.userId)||((o=n.currentApprover)==null?void 0:o.user_id)||((d=(c=n.approvals)==null?void 0:c.find(x=>{const u=(x.status||"").toString().toUpperCase();return u==="IN_PROGRESS"||u==="PENDING"}))==null?void 0:d.approverId)||((p=(m=n.approvals)==null?void 0:m.find(x=>{const u=(x.status||"").toString().toUpperCase();return u==="IN_PROGRESS"||u==="PENDING"}))==null?void 0:p.approver_id)||n.currentApproverId||n.current_approver_id)===s.approver}):a=a.filter(n=>{var l,o;const i=[];return(l=n.currentApprover)!=null&&l.userId&&i.push(n.currentApprover.userId),(o=n.currentApprover)!=null&&o.user_id&&i.push(n.currentApprover.user_id),Array.isArray(n.approvals)&&n.approvals.forEach(c=>{c.approverId&&i.push(c.approverId),c.approver_id&&i.push(c.approver_id)}),i.includes(s.approver||"")})),s.slaCompliance&&s.slaCompliance!=="all"&&(a=a.filter(r=>{var c,d,m,p,x,u,g,f,b,j,y,w;const n=s.slaCompliance||"";if(n.toLowerCase()==="compliant"){const v=(r.status||"").toString().toUpperCase();if(!(v==="APPROVED"||v==="REJECTED"||v==="CLOSED"))return!1;const A=((c=r.currentLevelSLA)==null?void 0:c.status)||((m=(d=r.currentApprover)==null?void 0:d.sla)==null?void 0:m.status)||((p=r.sla)==null?void 0:p.status)||((u=(x=r.summary)==null?void 0:x.sla)==null?void 0:u.status);return A?A!=="breached"&&A.toLowerCase()!=="breached":!0}const i=((g=r.currentLevelSLA)==null?void 0:g.status)||((b=(f=r.currentApprover)==null?void 0:f.sla)==null?void 0:b.status)||((j=r.sla)==null?void 0:j.status)||((w=(y=r.summary)==null?void 0:y.sla)==null?void 0:w.status);if(!i)return n==="on-track"||n==="on_track";const 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=ss(s.startDate).startOf("day").toDate(),n=ss(s.endDate).endOf("day").toDate();else{const i=ss();switch(s.dateRange){case"today":r=i.startOf("day").toDate(),n=i.endOf("day").toDate();break;case"week":r=i.startOf("week").toDate(),n=i.endOf("week").toDate();break;case"month":r=i.startOf("month").toDate(),n=i.endOf("month").toDate();break}}r&&n&&(a=a.filter(i=>{const l=i.submittedAt||i.submission_date||i.submitted_at;if(!l){const m=i.createdAt||i.created_at||i.created_date;if(!m)return!1;const p=ss(m).startOf("day").toDate(),x=ss(r).startOf("day").toDate(),u=ss(n).endOf("day").toDate();return p>=x&&p<=u}const o=ss(l).startOf("day").toDate(),c=ss(r).startOf("day").toDate(),d=ss(n).endOf("day").toDate();return o>=c&&o<=d}))}return a}ss.extend(R0);ss.extend(F0);function O4(t){if(!t)return"N/A";try{const s=typeof t=="string"?new Date(t):t;return et(s,"yyyy-MM-dd HH:mm:ss")}catch{return"N/A"}}async function I0(t,s){const a=L4(t,s),r=[["Request Number","Title","Status","Priority","Initiator","Department","Current Approver","Approval Level","Submitted Date","Description"].join(",")];a.forEach(c=>{var y,w,v,C,A;const d=(c.status||"").toString().toLowerCase().replace("_","-"),m=(c.priority||"").toString().toLowerCase(),p=((y=c.initiator)==null?void 0:y.displayName)||((w=c.initiator)==null?void 0:w.email)||c.initiatorName||"N/A",x=c.department||((v=c.initiator)==null?void 0:v.department)||"N/A",u=((C=c.currentApprover)==null?void 0:C.displayName)||((A=c.currentApprover)==null?void 0:A.email)||c.currentApproverName||"N/A",g=c.currentApproverLevel||c.approvalLevel||c.currentLevel||"N/A",f=O4(c.submittedAt||c.createdAt||c.submitted_at||c.created_at),b=(c.description||"").replace(/"/g,'""').replace(/\n/g," ").replace(/\r/g,""),j=[c.requestNumber||c.request_number||"",`"${(c.title||"").replace(/"/g,'""')}"`,d,m,`"${p.replace(/"/g,'""')}"`,`"${x.replace(/"/g,'""')}"`,`"${u.replace(/"/g,'""')}"`,g,f,`"${b}"`];r.push(j.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 $4({page:t,itemsPerPage:s,filters:a,isOrgLevel:r}){var n,i,l,o;if(r){const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(c.templateType=a.templateType),(a==null?void 0:a.templateType)==="FORM_16"&&(a!=null&&a.financialYear&&(c.financialYear=a.financialYear),a!=null&&a.quarter&&(c.quarter=a.quarter)),a!=null&&a.department&&a.department!=="all"&&(c.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(c.initiator=a.initiator),a!=null&&a.approver&&a.approver!=="all"&&(c.approver=a.approver,c.approverType=a.approverType||"current"),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(c.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(c.dateRange=a.dateRange),a!=null&&a.startDate&&(c.startDate=(n=a.startDate)==null?void 0:n.toISOString()),a!=null&&a.endDate&&(c.endDate=(i=a.endDate)==null?void 0:i.toISOString());const d=await Gs.listWorkflows({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const p=m.filter(g=>(g.status||"").toString().toUpperCase()!=="DRAFT"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:p.length,totalPages:1};return{data:p,allData:[],filteredData:p,pagination:{page:x.page,limit:x.limit||s,total:x.total||p.length,totalPages:x.totalPages||1}}}else{const c={};a!=null&&a.search&&(c.search=a.search),a!=null&&a.status&&a.status!=="all"&&(c.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(c.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(c.templateType=a.templateType),(a==null?void 0:a.templateType)==="FORM_16"&&(a!=null&&a.financialYear&&(c.financialYear=a.financialYear),a!=null&&a.quarter&&(c.quarter=a.quarter)),a!=null&&a.department&&a.department!=="all"&&(c.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(c.initiator=a.initiator),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(c.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(c.dateRange=a.dateRange),a!=null&&a.startDate&&(c.startDate=(l=a.startDate)==null?void 0:l.toISOString()),a!=null&&a.endDate&&(c.endDate=(o=a.endDate)==null?void 0:o.toISOString());const d=await Gs.listParticipantRequests({page:t,limit:s,...c});let m=[];Array.isArray(d==null?void 0:d.data)?m=d.data:Array.isArray(d)&&(m=d);const p=m.filter(u=>(u.status||"").toString().toUpperCase()!=="DRAFT"),x=(d==null?void 0:d.pagination)||{page:t,limit:s,total:p.length,totalPages:1};return{data:p,allData:[],filteredData:p,pagination:x}}}async function U4(t){const a=[];let r=1,n=!0;const i=100;for(;n&&r<=i;){const l=t?await Gs.listWorkflows({page:r,limit:100}):await Gs.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 B4({onViewRequest:t}){const{user:s}=cs(),a=dn(I=>I.dashboard.viewAsUser),r=h.useMemo(()=>sl(s),[s]),n=h.useMemo(()=>r&&!a,[r,a]),i=A0(),[l,o]=h.useState([]),[c,d]=h.useState(!1),[m,p]=h.useState(!1),[x,u]=h.useState(null),[g,f]=h.useState([]),[b,j]=h.useState(!1),[y,w]=h.useState(1),[v,C]=h.useState(0),[A]=h.useState(10),L=Ui({filterValue:i.initiatorFilter,onFilterChange:i.setInitiatorFilter,source:"local"}),D=Ui({filterValue:i.approverFilter,onFilterChange:i.setApproverFilter,source:"local"}),R=h.useCallback(async(I,E,W,V)=>{try{const Y=V==null?void 0:V.slaCompliance;if(Y&&Y!=="all"&&Y!=="breached"&&Y!=="compliant"){const O={};V!=null&&V.search&&(O.search=V.search),V!=null&&V.priority&&V.priority!=="all"&&(O.priority=V.priority),V!=null&&V.department&&V.department!=="all"&&(O.department=V.department),V!=null&&V.initiator&&V.initiator!=="all"&&(O.initiator=V.initiator),V!=null&&V.approver&&V.approver!=="all"&&(O.approver=V.approver,O.approverType=V.approverType||"current"),O.slaCompliance=Y,I&&(O.dateRange=I),E&&(O.startDate=E.toISOString()),W&&(O.endDate=W.toISOString());const z=n?await Gs.listWorkflows({page:1,limit:1e3,...O}):await Gs.listParticipantRequests({page:1,limit:1e3,...O}),K=Array.isArray(z==null?void 0:z.data)?z.data:[],re=K.length,G=K.filter(Ke=>{const Je=(Ke.status||"").toString().toUpperCase();return Je==="PENDING"||Je==="IN_PROGRESS"}).length,se=K.filter(Ke=>(Ke.status||"").toString().toUpperCase()==="APPROVED").length,ve=K.filter(Ke=>(Ke.status||"").toString().toUpperCase()==="REJECTED").length,Te=K.filter(Ke=>(Ke.status||"").toString().toUpperCase()==="CLOSED").length;u({total:re,pending:G,paused:0,approved:se,rejected:ve,draft:0,closed:Te})}else{const O=await Mt.getRequestStats(I,E?E.toISOString():void 0,W?W.toISOString():void 0,void 0,V==null?void 0:V.priority,V==null?void 0:V.templateType,V==null?void 0:V.department,V==null?void 0:V.initiator,V==null?void 0:V.approver,V==null?void 0:V.approverType,V==null?void 0:V.search,V==null?void 0:V.slaCompliance,!n);u({total:O.totalRequests||0,pending:O.openRequests||0,paused:O.pausedRequests||0,approved:O.approvedRequests||0,rejected:O.rejectedRequests||0,draft:O.draftRequests||0,closed:O.closedRequests||0})}}catch(Y){console.error("Failed to fetch backend stats:",Y)}finally{}},[n]),N=h.useCallback(async()=>{try{j(!0);const I=await Mt.getDepartments();f(I)}catch{}finally{j(!1)}},[]),_=h.useRef(i),S=h.useRef(R);h.useEffect(()=>{_.current=i,S.current=R},[i,R]),h.useEffect(()=>{const I=new URLSearchParams(window.location.search),E=I.get("approver"),W=I.get("approverType"),V=I.get("slaCompliance"),Y=I.get("dateRange"),Z=I.get("startDate"),O=I.get("endDate");E&&i.setApproverFilter(E),(W==="current"||W==="any")&&i.setApproverFilterType(W),V&&i.setSlaComplianceFilter(V),Y&&i.setDateRange(Y),Z&&i.setCustomStartDate(new Date(Z)),O&&i.setCustomEndDate(new Date(O))},[]);const U=h.useCallback(async(I=1)=>{try{I===1&&(d(!0),o([]));const E=_.current.getFilters(),W=await $4({page:I,itemsPerPage:A,filters:E,isOrgLevel:n});o(W.data),i.setCurrentPage(W.pagination.page),w(W.pagination.totalPages),C(W.pagination.total)}catch{o([])}finally{d(!1)}},[A,n]),F=h.useCallback(async()=>{try{p(!0);const I=await U4(n);await I0(I,i.getFilters())}catch(I){console.error("Failed to export requests:",I),alert("Failed to export requests. Please try again.")}finally{p(!1)}},[n,i]);h.useEffect(()=>{N()},[N]),h.useEffect(()=>{const I=setTimeout(()=>{const E={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";S.current(W,i.customStartDate,i.customEndDate,E)},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 $=h.useRef({searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,form16FinancialYear:i.form16FinancialYear,form16Quarter:i.form16Quarter,slaComplianceFilter:i.slaComplianceFilter,departmentFilter:i.departmentFilter,initiatorFilter:i.initiatorFilter,approverFilter:i.approverFilter,approverFilterType:i.approverFilterType,dateRange:i.dateRange,customStartDate:i.customStartDate,customEndDate:i.customEndDate,isOrgLevel:n}),P=h.useRef(!1);h.useEffect(()=>{const I=i.currentPage||1;U(I),P.current=!0},[]),h.useEffect(()=>{if(!P.current)return;const I=$.current;if(!(I.searchTerm!==i.searchTerm||I.statusFilter!==i.statusFilter||I.priorityFilter!==i.priorityFilter||I.templateTypeFilter!==i.templateTypeFilter||I.form16FinancialYear!==i.form16FinancialYear||I.form16Quarter!==i.form16Quarter||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),U(1),$.current={searchTerm:i.searchTerm,statusFilter:i.statusFilter,priorityFilter:i.priorityFilter,templateTypeFilter:i.templateTypeFilter,form16FinancialYear:i.form16FinancialYear,form16Quarter:i.form16Quarter,slaComplianceFilter:i.slaComplianceFilter,departmentFilter:i.departmentFilter,initiatorFilter:i.initiatorFilter,approverFilter:i.approverFilter,approverFilterType:i.approverFilterType,dateRange:i.dateRange,customStartDate:i.customStartDate,customEndDate:i.customEndDate,isOrgLevel:n}},i.searchTerm!==I.searchTerm?500:0);return()=>clearTimeout(W)},[n,i.searchTerm,i.statusFilter,i.priorityFilter,i.templateTypeFilter,i.form16FinancialYear,i.form16Quarter,i.slaComplianceFilter,i.departmentFilter,i.initiatorFilter,i.approverFilter,i.approverFilterType,i.dateRange,i.customStartDate,i.customEndDate]);const T=h.useCallback(I=>{I>=1&&I<=y&&(i.setCurrentPage(I),U(I))},[y,U,i]),k=h.useMemo(()=>T0(l),[l]),B=h.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}:E4([],n,x,!1,v,k),[n,x,v,k]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[e.jsx(N0,{isOrgLevel:n,isAdmin:r,loading:c,exporting:m,onExport:F}),e.jsx(w0,{stats:B,onStatusFilter:I=>{i.setStatusFilter(I)}}),e.jsx(q,{className:"border-gray-200 shadow-md","data-testid":"requests-filters",children:e.jsx(ee,{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(Pa,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),i.hasActiveFilters&&e.jsx(ae,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),i.hasActiveFilters&&e.jsxs(M,{variant:"ghost",size:"sm",onClick:i.clearFilters,className:"gap-2",children:[e.jsx(Ut,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Qt,{}),i.isForm16?e.jsxs("div",{className:"flex flex-wrap items-end gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(te,{className:"text-sm font-medium text-gray-700",children:"All Templates"}),e.jsxs(He,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(Ge,{className:"h-10 w-[180px]","data-testid":"template-type-filter",children:e.jsx(We,{placeholder:"All Templates"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Custom"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(J,{value:"FORM_16",children:"Form 16"})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(te,{className:"text-sm font-medium text-gray-700",children:"Financial Year"}),e.jsxs(He,{value:i.form16FinancialYear,onValueChange:i.setForm16FinancialYear,children:[e.jsx(Ge,{className:"h-10 w-[140px]","data-testid":"form16-financial-year-filter",children:e.jsx(We,{placeholder:"Financial Year"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Years"}),e.jsx(J,{value:"2024-25",children:"2024-25"}),e.jsx(J,{value:"2023-24",children:"2023-24"}),e.jsx(J,{value:"2022-23",children:"2022-23"})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(te,{className:"text-sm font-medium text-gray-700",children:"Quarter"}),e.jsxs(He,{value:i.form16Quarter,onValueChange:i.setForm16Quarter,children:[e.jsx(Ge,{className:"h-10 w-[130px]","data-testid":"form16-quarter-filter",children:e.jsx(We,{placeholder:"Quarter"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Quarters"}),e.jsx(J,{value:"Q1",children:"Q1"}),e.jsx(J,{value:"Q2",children:"Q2"}),e.jsx(J,{value:"Q3",children:"Q3"}),e.jsx(J,{value:"Q4",children:"Q4"})]})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(Ss,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Ce,{placeholder:"Search requests...",value:i.searchTerm,onChange:I=>i.setSearchTerm(I.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(He,{value:i.statusFilter,onValueChange:i.setStatusFilter,children:[e.jsx(Ge,{className:"h-10","data-testid":"status-filter",children:e.jsx(We,{placeholder:"All Status"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"pending",children:"Pending"}),e.jsx(J,{value:"paused",children:"Paused"}),e.jsx(J,{value:"approved",children:"Approved"}),e.jsx(J,{value:"rejected",children:"Rejected"}),e.jsx(J,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:i.priorityFilter,onValueChange:i.setPriorityFilter,children:[e.jsx(Ge,{className:"h-10","data-testid":"priority-filter",children:e.jsx(We,{placeholder:"All Priority"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Priority"}),e.jsx(J,{value:"express",children:"Express"}),e.jsx(J,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:i.templateTypeFilter,onValueChange:i.setTemplateTypeFilter,children:[e.jsx(Ge,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(We,{placeholder:"All Templates"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(J,{value:"FORM_16",children:"Form 16"})]})]}),e.jsxs(He,{value:i.departmentFilter,onValueChange:i.setDepartmentFilter,disabled:b||g.length===0,children:[e.jsx(Ge,{className:"h-10","data-testid":"department-filter",children:e.jsx(We,{placeholder:b?"Loading...":"All Departments"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Departments"}),g.map(I=>e.jsx(J,{value:I,children:I},I))]})]}),e.jsxs(He,{value:i.slaComplianceFilter,onValueChange:i.setSlaComplianceFilter,children:[e.jsx(Ge,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(We,{placeholder:"All SLA Status"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All SLA Status"}),e.jsx(J,{value:"compliant",children:"Compliant"}),e.jsx(J,{value:"on-track",children:"On Track"}),e.jsx(J,{value:"approaching",children:"Approaching"}),e.jsx(J,{value:"critical",children:"Critical"}),e.jsx(J,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(te,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:L.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:L.selectedUser.displayName||L.selectedUser.email}),e.jsx(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:L.handleClear,children:e.jsx(jt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{placeholder:"Search initiator...",value:L.searchQuery,onChange:I=>L.handleSearch(I.target.value),onFocus:()=>{L.searchResults.length>0&&L.setShowResults(!0)},onBlur:()=>setTimeout(()=>L.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),L.showResults&&L.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:L.searchResults.map(I=>e.jsx("button",{type:"button",onClick:()=>L.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(te,{className:"text-sm font-medium text-gray-700",children:"Approver"}),i.approverFilter!=="all"&&e.jsxs(He,{value:i.approverFilterType,onValueChange:I=>i.setApproverFilterType(I),children:[e.jsx(Ge,{className:"h-7 w-32 text-xs",children:e.jsx(We,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"current",children:"Current Only"}),e.jsx(J,{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(M,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:D.handleClear,children:e.jsx(jt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{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(dt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:i.dateRange,onValueChange:i.handleDateRangeChange,children:[e.jsx(Ge,{className:"w-[160px] h-10",children:e.jsx(We,{placeholder:"Date Range"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Time"}),e.jsx(J,{value:"today",children:"Today"}),e.jsx(J,{value:"week",children:"This Week"}),e.jsx(J,{value:"month",children:"This Month"}),e.jsx(J,{value:"last7days",children:"Last 7 Days"}),e.jsx(J,{value:"last30days",children:"Last 30 Days"}),e.jsx(J,{value:"custom",children:"Custom Range"})]})]}),i.dateRange==="custom"&&e.jsxs(ra,{open:i.showCustomDatePicker,onOpenChange:i.setShowCustomDatePicker,children:[e.jsx(na,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(dt,{className:"w-4 h-4"}),i.customStartDate&&i.customEndDate?`${et(i.customStartDate,"MMM d, yyyy")} - ${et(i.customEndDate,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Js,{value:i.customStartDate||null,onChange:I=>{const E=I?new Date(I):void 0;E?(i.setCustomStartDate(E),i.customEndDate&&E>i.customEndDate&&i.setCustomEndDate(E)):i.setCustomStartDate(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"end-date",children:"End Date"}),e.jsx(Js,{value:i.customEndDate||null,onChange:I=>{const E=I?new Date(I):void 0;E?(i.setCustomEndDate(E),i.customStartDate&&E{i.setShowCustomDatePicker(!1),i.setCustomStartDate(void 0),i.setCustomEndDate(void 0),i.setDateRange("month")},children:"Cancel"})})]})})]})]})]})]})})}),e.jsx(C0,{requests:k,loading:c,hasActiveFilters:i.hasActiveFilters,onViewRequest:t}),e.jsx(Mr,{currentPage:i.currentPage||1,totalPages:y,totalRecords:v,itemsPerPage:A,onPageChange:T,loading:c,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}async function V4({page:t,itemsPerPage:s,filters:a}){const r={};a!=null&&a.search&&(r.search=a.search),a!=null&&a.status&&a.status!=="all"&&(r.status=a.status),a!=null&&a.priority&&a.priority!=="all"&&(r.priority=a.priority),a!=null&&a.templateType&&a.templateType!=="all"&&(r.templateType=a.templateType),a!=null&&a.financialYear&&(r.financialYear=a.financialYear),a!=null&&a.quarter&&(r.quarter=a.quarter),a!=null&&a.department&&a.department!=="all"&&(r.department=a.department),a!=null&&a.initiator&&a.initiator!=="all"&&(r.initiator=a.initiator),a!=null&&a.approver&&a.approver!=="all"&&(r.approver=a.approver,r.approverType=a.approverType||"current"),a!=null&&a.slaCompliance&&a.slaCompliance!=="all"&&(r.slaCompliance=a.slaCompliance),a!=null&&a.dateRange&&(r.dateRange=a.dateRange),a!=null&&a.startDate&&(r.startDate=a.startDate instanceof Date?a.startDate.toISOString():a.startDate),a!=null&&a.endDate&&(r.endDate=a.endDate instanceof Date?a.endDate.toISOString():a.endDate);const n=await Gs.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 Tx=100;async function z4(t){const s=[];let a=!0,r=1;const n=100,i={};for(t!=null&&t.search&&(i.search=t.search),t!=null&&t.status&&t.status!=="all"&&(i.status=t.status),t!=null&&t.priority&&t.priority!=="all"&&(i.priority=t.priority),t!=null&&t.templateType&&t.templateType!=="all"&&(i.templateType=t.templateType),t!=null&&t.financialYear&&(i.financialYear=t.financialYear),t!=null&&t.quarter&&(i.quarter=t.quarter),t!=null&&t.department&&t.department!=="all"&&(i.department=t.department),t!=null&&t.initiator&&t.initiator!=="all"&&(i.initiator=t.initiator),t!=null&&t.approver&&t.approver!=="all"&&(i.approver=t.approver,i.approverType=t.approverType||"current"),t!=null&&t.slaCompliance&&t.slaCompliance!=="all"&&(i.slaCompliance=t.slaCompliance),t!=null&&t.dateRange&&(i.dateRange=t.dateRange),t!=null&&t.startDate&&(i.startDate=t.startDate instanceof Date?t.startDate.toISOString():t.startDate),t!=null&&t.endDate&&(i.endDate=t.endDate instanceof Date?t.endDate.toISOString():t.endDate);a&&r<=n;){const l=await Gs.listParticipantRequests({page:r,limit:Tx,...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===Tx}}return s}function H4({onViewRequest:t}){const s=A0(),a=h.useMemo(()=>{try{const Y=at.getUserData();return lc(Y)}catch(Y){return console.error("[UserAllRequests] Error getting user filter type:",Y),"STANDARD"}},[]),r=h.useMemo(()=>xk(a),[a]),n=a==="DEALER",i=h.useCallback(()=>{const Y=s.getFilters();if(!n)return Y;const Z=s.requestTypeFilter;if(Z==="form_16")return{templateType:"FORM_16",financialYear:s.form16FinancialYear!=="all"?s.form16FinancialYear:void 0,quarter:s.form16Quarter!=="all"?s.form16Quarter:void 0};if(Z==="claim_management")return{templateType:"DEALER CLAIM",search:Y.search,status:Y.status!=="all"?Y.status:void 0,dateRange:Y.dateRange,startDate:Y.startDate,endDate:Y.endDate,initiator:Y.initiator,approver:Y.approver,approverType:Y.approverType};const{priority:O,templateType:z,department:K,slaCompliance:re,...G}=Y;return G},[s,n]),l=h.useCallback(()=>{if(n){const Y=s.requestTypeFilter;return Y==="form_16"?s.form16FinancialYear!=="all"||s.form16Quarter!=="all":Y==="claim_management"?s.statusFilter!=="all"||s.dateRange!=="all"||!!s.customStartDate||!!s.customEndDate:!!(s.searchTerm||s.statusFilter!=="all"||s.initiatorFilter!=="all"||s.approverFilter!=="all"||s.dateRange!=="all"||s.customStartDate||s.customEndDate)}return s.hasActiveFilters},[n,s]),[o,c]=h.useState([]),[d,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(null),[f,b]=h.useState([]),[j,y]=h.useState(!1),[w,v]=h.useState(!1),[C,A]=h.useState(1),[L,D]=h.useState(0),[R]=h.useState(10),N=Ui({filterValue:s.initiatorFilter,onFilterChange:s.setInitiatorFilter,source:"local"}),_=Ui({filterValue:s.approverFilter,onFilterChange:s.setApproverFilter,source:"local"}),S=h.useCallback(async(Y,Z,O,z)=>{try{const K=await Mt.getRequestStats(Y,Z?Z.toISOString():void 0,O?O.toISOString():void 0,void 0,z==null?void 0:z.priority,z==null?void 0:z.templateType,z==null?void 0:z.department,z==null?void 0:z.initiator,z==null?void 0:z.approver,z==null?void 0:z.approverType,z==null?void 0:z.search,z==null?void 0:z.slaCompliance,!0);g({total:K.totalRequests||0,pending:K.openRequests||0,paused:K.pausedRequests||0,approved:K.approvedRequests||0,rejected:K.rejectedRequests||0,draft:K.draftRequests||0,closed:K.closedRequests||0})}catch(K){console.error("Failed to fetch backend stats:",K)}},[]),U=h.useCallback(async()=>{try{y(!0);const Y=await Mt.getDepartments();b(Y)}catch{}finally{y(!1)}},[]);h.useEffect(()=>{a==="STANDARD"&&zh().then(Y=>v(!!(Y.canViewForm16Submission||Y.canView26AS))).catch(()=>v(!1))},[a]);const F=h.useRef(s),$=h.useRef(S),P=h.useRef(i);h.useEffect(()=>{F.current=s,$.current=S,P.current=i},[s,S,i]);const T=h.useCallback(async(Y=1)=>{try{Y===1&&(m(!0),c([]));const Z=P.current(),O=await V4({page:Y,itemsPerPage:R,filters:Z});c(O.data),s.setCurrentPage(O.pagination.page),A(O.pagination.totalPages),D(O.pagination.total)}catch{c([])}finally{m(!1)}},[R,s]),k=h.useCallback(async()=>{try{x(!0);const Y=i(),Z=await z4(Y);await I0(Z,Y)}catch(Y){console.error("Failed to export requests:",Y),alert("Failed to export requests. Please try again.")}finally{x(!1)}},[i]);h.useEffect(()=>{U()},[U]),h.useEffect(()=>{const Y=setTimeout(()=>{const Z={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"&&(Z.priority=s.priorityFilter),s.templateTypeFilter!=="all"&&(Z.templateType=s.templateTypeFilter),s.departmentFilter!=="all"&&(Z.department=s.departmentFilter),s.slaComplianceFilter!=="all"&&(Z.slaCompliance=s.slaComplianceFilter));const O=s.dateRange==="all"?"all":s.dateRange||"month";$.current(O,s.customStartDate,s.customEndDate,Z)},s.searchTerm?500:0);return()=>clearTimeout(Y)},[s.searchTerm,s.priorityFilter,s.slaComplianceFilter,s.departmentFilter,s.initiatorFilter,s.approverFilter,s.approverFilterType,s.dateRange,s.customStartDate,s.customEndDate,s.templateTypeFilter,n]);const B=h.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}),I=h.useRef(!1);h.useEffect(()=>{const Y=s.currentPage||1;T(Y),I.current=!0},[]),h.useEffect(()=>{if(!I.current)return;const Y=B.current;if(!(Y.searchTerm!==s.searchTerm||Y.statusFilter!==s.statusFilter||Y.priorityFilter!==s.priorityFilter||Y.templateTypeFilter!==s.templateTypeFilter||Y.slaComplianceFilter!==s.slaComplianceFilter||Y.departmentFilter!==s.departmentFilter||Y.initiatorFilter!==s.initiatorFilter||Y.approverFilter!==s.approverFilter||Y.approverFilterType!==s.approverFilterType||Y.dateRange!==s.dateRange||Y.customStartDate!==s.customStartDate||Y.customEndDate!==s.customEndDate))return;const O=setTimeout(()=>{s.setCurrentPage(1),T(1),B.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!==Y.searchTerm?500:0);return()=>clearTimeout(O)},[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 E=h.useCallback(Y=>{Y>=1&&Y<=C&&(s.setCurrentPage(Y),T(Y))},[C,T,s]),W=h.useMemo(()=>T0(o),[o]),V=h.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 Y=W.filter(re=>{const G=(re.status||"").toString().toLowerCase();return G==="pending"||G==="in-progress"}).length,Z=W.filter(re=>(re.status||"").toString().toLowerCase()==="paused").length,O=W.filter(re=>(re.status||"").toString().toLowerCase()==="approved").length,z=W.filter(re=>(re.status||"").toString().toLowerCase()==="rejected").length,K=W.filter(re=>(re.status||"").toString().toLowerCase()==="closed").length;return{total:L>0?L:W.length,pending:Y,paused:Z,approved:O,rejected:z,draft:0,closed:K}},[u,L,W]);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(N0,{isOrgLevel:!1,isAdmin:!1,loading:d,exporting:p,onExport:k}),e.jsx(w0,{stats:V,onStatusFilter:Y=>{s.setStatusFilter(Y)}}),e.jsx(r,{requestTypeFilter:s.requestTypeFilter,onRequestTypeChange:Y=>s.setRequestTypeFilter(Y),showForm16Filter:w,form16FinancialYear:s.form16FinancialYear,form16Quarter:s.form16Quarter,onForm16FinancialYearChange:s.setForm16FinancialYear,onForm16QuarterChange:s.setForm16Quarter,searchTerm:s.searchTerm,statusFilter:s.statusFilter,priorityFilter:s.priorityFilter,templateTypeFilter:s.templateTypeFilter,departmentFilter:s.departmentFilter,slaComplianceFilter:s.slaComplianceFilter,initiatorFilter:s.initiatorFilter,approverFilter:s.approverFilter,approverFilterType:s.approverFilterType,dateRange:s.dateRange,customStartDate:s.customStartDate,customEndDate:s.customEndDate,showCustomDatePicker:s.showCustomDatePicker,departments:f,loadingDepartments:j,initiatorSearch:N,approverSearch:_,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(C0,{requests:W,loading:d,hasActiveFilters:s.hasActiveFilters,onViewRequest:t}),e.jsx(Mr,{currentPage:s.currentPage||1,totalPages:C,totalRecords:L,itemsPerPage:R,onPageChange:E,loading:d,itemLabel:"requests",testIdPrefix:"requests-pagination"})]})}function W4(){const t=ys();return e.jsx("div",{className:"flex-1 p-3 lg:p-6 overflow-auto min-w-0","data-testid":"approver-performance-empty",children:e.jsx("div",{className:"max-w-7xl mx-auto p-4",children:e.jsx(q,{children:e.jsxs(ee,{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(M,{onClick:()=>t(-1),className:"mt-4","data-testid":"back-button",children:[e.jsx(Cs,{className:"w-4 h-4 mr-2"}),"Back"]})]})})})})}function G4({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(Jt,{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(M,{variant:"outline",size:"sm",onClick:a,disabled:s,className:"gap-2","data-testid":"refresh-button",children:[e.jsx(Ut,{className:`w-4 h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]})]})}function Y4({approverStats:t}){const s=(t==null?void 0:t.tatCompliancePercent)??0;return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4","data-testid":"approver-stats-cards",children:[e.jsxs(q,{children:[e.jsx(oe,{className:"pb-3",children:e.jsx(de,{className:"text-sm font-medium text-gray-600",children:"TAT Compliance"})}),e.jsxs(ee,{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(qt,{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(qs,{value:s,className:"mt-2 h-2"})]})]}),e.jsxs(q,{children:[e.jsx(oe,{className:"pb-3",children:e.jsx(de,{className:"text-sm font-medium text-gray-600",children:"Total Approved"})}),e.jsxs(ee,{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(Oe,{className:"w-5 h-5 text-blue-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Requests handled"})]})]}),e.jsxs(q,{children:[e.jsx(oe,{className:"pb-3",children:e.jsx(de,{className:"text-sm font-medium text-gray-600",children:"Avg Response Time"})}),e.jsxs(ee,{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(Wo,{className:"w-5 h-5 text-purple-600"})})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:t.avgResponseHours<24?`${(t.avgResponseHours/8).toFixed(1)} working days`:`${(t.avgResponseHours/24).toFixed(1)} days`})]})]}),e.jsxs(q,{children:[e.jsx(oe,{className:"pb-3",children:e.jsx(de,{className:"text-sm font-medium text-gray-600",children:"Pending Actions"})}),e.jsxs(ee,{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 K4({approverName:t,approverStats:s,dateRange:a="all",customStartDate:r,customEndDate:n}){return e.jsxs(q,{"data-testid":"approver-actions-stats",children:[e.jsxs(oe,{children:[e.jsx(de,{children:"Approver's Actions"}),e.jsxs(ye,{children:["Statistics for all requests by ",t," ",a&&a!=="all"?qN(a,r,n,""):"(all time)"]})]}),e.jsxs(ee,{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(Jt,{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(Oe,{className:"w-5 h-5 text-green-600"}),e.jsx("span",{className:"text-xs text-green-600 font-medium",children:s&&s.approvedCount+s.rejectedCount>0?`${Math.round(s.approvedCount/(s.approvedCount+s.rejectedCount)*100)}%`:"0%"})]}),e.jsx("div",{className:"text-2xl font-bold text-green-700",children:(s==null?void 0:s.approvedCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Approved by Approver"})]}),e.jsxs("div",{className:"p-4 bg-red-50 rounded-lg border border-red-200",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(At,{className:"w-5 h-5 text-red-600"}),e.jsx("span",{className:"text-xs text-red-600 font-medium",children:s&&s.approvedCount+s.rejectedCount>0?`${Math.round(s.rejectedCount/(s.approvedCount+s.rejectedCount)*100)}%`:"0%"})]}),e.jsx("div",{className:"text-2xl font-bold text-red-700",children:(s==null?void 0:s.rejectedCount)||0}),e.jsx("div",{className:"text-xs text-gray-600 mt-1",children:"Rejected by Approver"})]}),e.jsxs("div",{className:"p-4 bg-yellow-50 rounded-lg border border-yellow-200",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(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(tl,{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(Ie,{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(qt,{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(Db,{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(Ii,{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 Q4({searchTerm:t,statusFilter:s,priorityFilter:a,slaComplianceFilter:r,dateRange:n,customStartDate:i,customEndDate:l,showCustomDatePicker:o,tempCustomStartDate:c,tempCustomEndDate:d,onSearchChange:m,onStatusChange:p,onPriorityChange:x,onSlaComplianceChange:u,onDateRangeChange:g,onShowCustomDatePickerChange:f,onTempStartDateChange:b,onTempEndDateChange:j,onApplyCustomDate:y,onClearFilters:w}){return e.jsxs(q,{"data-testid":"approver-performance-filters",children:[e.jsx(oe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(de,{children:"Filters"}),e.jsx(M,{variant:"ghost",size:"sm",onClick:w,className:"text-xs","data-testid":"clear-filters-button",children:"Clear All"})]})}),e.jsx(ee,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Ss,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Ce,{placeholder:"Search requests...",value:t,onChange:v=>m(v.target.value),className:"pl-10","data-testid":"search-input"})]}),e.jsxs(He,{value:s,onValueChange:p,children:[e.jsx(Ge,{"data-testid":"status-filter",children:e.jsx(We,{placeholder:"Status"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"pending",children:"Pending"}),e.jsx(J,{value:"approved",children:"Approved"}),e.jsx(J,{value:"rejected",children:"Rejected"}),e.jsx(J,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:a,onValueChange:x,children:[e.jsx(Ge,{"data-testid":"priority-filter",children:e.jsx(We,{placeholder:"Priority"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Priority"}),e.jsx(J,{value:"express",children:"Express"}),e.jsx(J,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:r,onValueChange:u,children:[e.jsx(Ge,{"data-testid":"sla-compliance-filter",children:e.jsx(We,{placeholder:"SLA Compliance"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All SLA"}),e.jsx(J,{value:"compliant",children:"Compliant"}),e.jsx(J,{value:"on-track",children:"On Track"}),e.jsx(J,{value:"approaching",children:"Approaching"}),e.jsx(J,{value:"critical",children:"Critical"}),e.jsx(J,{value:"breached",children:"Breached"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:n,onValueChange:g,children:[e.jsx(Ge,{className:"flex-1","data-testid":"date-range-filter",children:e.jsx(We,{placeholder:"Date Range"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Time"}),e.jsx(J,{value:"today",children:"Today"}),e.jsx(J,{value:"week",children:"This Week"}),e.jsx(J,{value:"month",children:"This Month"}),e.jsx(J,{value:"last7days",children:"Last 7 Days"}),e.jsx(J,{value:"last30days",children:"Last 30 Days"}),e.jsx(J,{value:"custom",children:"Custom Range"})]})]}),n==="custom"&&e.jsxs(ra,{open:o,onOpenChange:f,children:[e.jsx(na,{asChild:!0,children:e.jsxs(M,{variant:"outline",size:"sm",className:"gap-2","data-testid":"custom-date-trigger",children:[e.jsx(dt,{className:"w-4 h-4"}),c&&d?`${et(c,"MMM d")} - ${et(d,"MMM d")}`:"Select dates"]})}),e.jsx(ia,{className:"w-auto p-4",align:"start",sideOffset:8,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"start-date",className:"text-sm font-medium",children:"Start Date"}),e.jsx(Ce,{id:"start-date",type:"date",value:c?et(c,"yyyy-MM-dd"):"",onChange:v=>{const C=v.target.value?new Date(v.target.value):void 0;C?(b(C),d&&C>d&&j(C)):b(void 0)},max:et(new Date,"yyyy-MM-dd"),className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"end-date",className:"text-sm font-medium",children:"End Date"}),e.jsx(Ce,{id:"end-date",type:"date",value:d?et(d,"yyyy-MM-dd"):"",onChange:v=>{const C=v.target.value?new Date(v.target.value):void 0;C?(j(C),c&&C{f(!1),b(i),j(l),(!i||!l)&&g("all")},"data-testid":"cancel-date-button",children:"Cancel"})]})]})})]})]})]})})]})}const X4=t=>{switch(t){case"express":return{color:"bg-red-100 text-red-800 border-red-200",icon:Ws,iconColor:"text-red-600"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",icon:qt,iconColor:"text-blue-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:qt,iconColor:"text-gray-600"}}},J4=t=>{switch(t){case"approved":return{color:"bg-green-100 text-green-800 border-green-200",icon:Oe,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",icon:At,iconColor:"text-red-600"};case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",icon: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:Oe,iconColor:"text-gray-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",icon:Ie,iconColor:"text-gray-600"}}},Z4=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 q4(t){if(!t)return"N/A";try{return et(new Date(t),"MMM d, yyyy")}catch{return"N/A"}}function e6(t){if(!t)return"N/A";try{return et(new Date(t),"MMM d, yyyy HH:mm")}catch{return"N/A"}}function Bi(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=zk(s);n(l)}function t6({requests:t,loading:s,approverName:a,currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o}){const c=ys();return e.jsxs(q,{"data-testid":"approver-performance-request-list",children:[e.jsxs(oe,{children:[e.jsx(de,{children:"Request Details"}),e.jsxs(ye,{children:["All requests handled by ",a," with applied filters"]})]}),e.jsxs(ee,{children:[s?e.jsxs("div",{className:"flex items-center justify-center py-12","data-testid":"loading-state",children:[e.jsx(Ut,{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(Ie,{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=X4(d.priority),p=J4(d.status),x=Z4(d.slaStatus||""),u=m.icon,g=p.icon;return e.jsx(q,{className:"hover:shadow-md transition-shadow cursor-pointer",onClick:()=>{Bi({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":`request-card-${d.requestId}`,children:e.jsx(ee,{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(ae,{className:m.color,"data-testid":"priority-badge",children:[e.jsx(u,{className:`w-3 h-3 mr-1 ${m.iconColor}`}),d.priority]}),e.jsxs(ae,{className:p.color,"data-testid":"status-badge",children:[e.jsx(g,{className:`w-3 h-3 mr-1 ${p.iconColor}`}),d.status]}),d.approvalStatus&&e.jsx(ae,{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(Oe,{className:"w-3 h-3 mr-1"}),"Approved"]}):d.approvalStatus==="rejected"||d.approvalStatus==="REJECTED"?e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"w-3 h-3 mr-1"}),"Rejected"]}):e.jsxs(e.Fragment,{children:[e.jsx(st,{className:"w-3 h-3 mr-1"}),"Pending"]})}),d.slaStatus&&e.jsx(ae,{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: ",q4(d.submissionDate)]}),d.approvalActionDate&&e.jsxs("span",{className:"flex items-center gap-1","data-testid":"action-date",children:[e.jsx(Oe,{className:"w-3 h-3"}),"Action: ",e6(d.approvalActionDate)]}),e.jsxs("span",{className:"flex items-center gap-1","data-testid":"approval-level",children:[e.jsx(qt,{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(Wo,{className:"w-3 h-3"}),Kt(d.levelElapsedHours)," / ",Kt(d.levelTatHours||0)," TAT"]})]})]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:f=>{f.stopPropagation(),Bi({requestId:d.requestId,requestTitle:d.title,status:d.status,request:d,navigate:c})},"data-testid":"view-request-button",children:e.jsx(fs,{className:"w-4 h-4"})})]})})},d.requestId)})}),n>0&&e.jsx("div",{className:"mt-6","data-testid":"pagination-container",children:e.jsx(Mr,{currentPage:r,totalPages:n,totalRecords:i,itemsPerPage:l,onPageChange:o,itemLabel:"requests",testIdPrefix:"approver-performance"})})]})]})}function s6(){const[t]=jh(),[s,a]=h.useState(""),[r,n]=h.useState(t.get("status")||"all"),[i,l]=h.useState(t.get("priority")||"all"),[o,c]=h.useState(t.get("slaCompliance")||"all"),[d,m]=h.useState(t.get("dateRange")||"all"),[p,x]=h.useState(t.get("startDate")?new Date(t.get("startDate")):void 0),[u,g]=h.useState(t.get("endDate")?new Date(t.get("endDate")):void 0),[f,b]=h.useState(!1),[j,y]=h.useState(void 0),[w,v]=h.useState(void 0),C=h.useCallback(()=>{a(""),n("all"),l("all"),c("all"),m("all"),x(void 0),g(void 0),y(void 0),v(void 0),b(!1)},[]),A=h.useCallback(D=>{const R=D;m(R),R!=="custom"?(x(void 0),g(void 0),y(void 0),v(void 0),b(!1)):(y(p),v(u),b(!0))},[p,u]),L=h.useCallback(()=>{if(j&&w){if(j>w){const D=j;x(w),g(D),y(w),v(D)}else x(j),g(w);b(!1)}},[j,w]);return{searchTerm:s,statusFilter:r,priorityFilter:i,slaComplianceFilter:o,dateRange:d,customStartDate:p,customEndDate:u,showCustomDatePicker:f,tempCustomStartDate:j,tempCustomEndDate:w,setSearchTerm:a,setStatusFilter:n,setPriorityFilter:l,setSlaComplianceFilter:c,setDateRange:m,setCustomStartDate:x,setCustomEndDate:g,setShowCustomDatePicker:b,setTempCustomStartDate:y,setTempCustomEndDate:v,clearFilters:C,handleDateRangeChange:A,handleApplyCustomDate:L}}function a6({approverId:t,dateRange:s,customStartDate:a,customEndDate:r,statusFilter:n,priorityFilter:i,slaComplianceFilter:l,searchTerm:o,itemsPerPage:c}){const[d,m]=h.useState([]),[p,x]=h.useState(null),[u,g]=h.useState([]),[f,b]=h.useState(!0),[j,y]=h.useState(!1),[w,v]=h.useState(1),[C,A]=h.useState(1),[L,D]=h.useState(0),R=h.useRef(!0),N=h.useCallback(async()=>{if(t)try{const F=s==="all"?void 0:s,$=await Mt.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]),_=h.useCallback(async(F=1)=>{if(!t){b(!1);return}try{b(!0);const $=await Mt.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),A($.pagination.totalPages),v($.pagination.currentPage),g($.requests)}catch($){console.error("Failed to fetch requests:",$)}finally{b(!1),y(!1)}},[t,s,a,r,n,i,l,o,c]);h.useEffect(()=>{R.current&&(R.current=!1,N(),_(1))},[]),h.useEffect(()=>{R.current||N()},[s,a,r,i,l]),h.useEffect(()=>{R.current||_(1)},[s,a,r,n,i,l,o]);const S=h.useCallback(()=>{y(!0),N(),_(1)},[N,_]),U=h.useCallback(F=>{_(F)},[_]);return{requests:d,approverStats:p,allFilteredRequests:u,loading:f,refreshing:j,currentPage:w,totalPages:C,totalRecords:L,handleRefresh:S,handlePageChange:U}}const kx=10;function r6(){const[t]=jh(),s=t.get("approverId")||"",a=t.get("approverName")||"Unknown Approver",r=s6(),n=a6({approverId:s,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate,statusFilter:r.statusFilter,priorityFilter:r.priorityFilter,slaComplianceFilter:r.slaComplianceFilter,searchTerm:r.searchTerm,itemsPerPage:kx});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(G4,{approverName:a,refreshing:n.refreshing,onRefresh:n.handleRefresh}),n.approverStats&&e.jsx(Y4,{approverStats:n.approverStats}),n.approverStats&&e.jsx(K4,{approverName:a,approverStats:n.approverStats,dateRange:r.dateRange,customStartDate:r.customStartDate,customEndDate:r.customEndDate}),e.jsx(Q4,{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(t6,{requests:n.requests,loading:n.loading,approverName:a,currentPage:n.currentPage,totalPages:n.totalPages,totalRecords:n.totalRecords,itemsPerPage:kx,onPageChange:n.handlePageChange})]}):e.jsx(W4,{})}function n6(){const{user:t}=cs(),s=()=>{var a,r;if(t!=null&&t.displayName){const n=t.displayName.split(" ").filter(Boolean);return n.length>=2?`${((a=n[0])==null?void 0:a[0])||""}${((r=n[n.length-1])==null?void 0:r[0])||""}`.toUpperCase():t.displayName.substring(0,2).toUpperCase()}return t!=null&&t.email?t.email.substring(0,2).toUpperCase():"U"};return e.jsxs("div",{className:"space-y-6 max-w-7xl mx-auto",children:[e.jsxs(q,{className:"relative overflow-hidden shadow-xl border-0",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"}),e.jsx(ee,{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(ls,{className:"h-24 w-24 ring-4 ring-white/20 shadow-xl",children:[e.jsx(rl,{src:(t==null?void 0:t.picture)||""}),e.jsx(os,{className:"bg-yellow-400 text-slate-900 text-2xl font-bold",children:s()})]}),Nr(t)&&e.jsx("div",{className:"absolute -bottom-2 -right-2 bg-yellow-400 rounded-full p-1.5 shadow-lg",children:e.jsx(ps,{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:[Nr(t)&&e.jsxs(ae,{className:"bg-yellow-400 text-slate-900 hover:bg-yellow-400 font-semibold",children:[e.jsx(ps,{className:"w-3 h-3 mr-1"}),"Administrator"]}),bn(t)&&e.jsxs(ae,{className:"bg-blue-400 text-slate-900 hover:bg-blue-400 font-semibold",children:[e.jsx(Jt,{className:"w-3 h-3 mr-1"}),"Management"]}),(t==null?void 0:t.employeeId)&&e.jsxs(ae,{variant:"outline",className:"border-white/30 text-white bg-white/10",children:["ID: ",t.employeeId]})]})]})})})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(q,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(oe,{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(de,{className:"text-lg text-gray-900",children:"Personal Information"}),e.jsx(ye,{className:"text-gray-600",children:"Your personal details"})]})]})}),e.jsx(ee,{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(fa,{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(Hn,{className:"w-5 h-5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-500",children:"Phone"}),e.jsx("p",{className:"text-base text-gray-900",children:t.phone})]})]})]})})]}),e.jsxs(q,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(oe,{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(km,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg text-gray-900",children:"Professional Information"}),e.jsx(ye,{className:"text-gray-600",children:"Work-related details"})]})]})}),e.jsx(ee,{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($o,{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(km,{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(ps,{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(ae,{variant:Nr(t)||bn(t)?"default":"secondary",className:Nr(t)?"bg-yellow-400 text-slate-900":bn(t)?"bg-blue-400 text-slate-900":"",children:Nr(t)?"Administrator":bn(t)?"Management":"User"}),(Nr(t)||bn(t))&&e.jsx(Oe,{className:"w-4 h-4 text-green-600"})]})]})]})]})})]})]}),e.jsxs(q,{className:"shadow-lg hover:shadow-xl transition-shadow",children:[e.jsx(oe,{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(dt,{className:"h-5 w-5 text-purple-600"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg text-gray-900",children:"Account Status"}),e.jsx(ye,{className:"text-gray-600",children:"Account information and activity"})]})]})}),e.jsx(ee,{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(Oe,{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(ae,{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 mi="BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI",i6="https://reflow-uat.royalenfield.com";function Xl(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:Xl(mi)})}else try{s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Xl(mi)})}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:Xl(mi)})}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(`${i6}/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 c6(){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 l6()}catch(a){throw new Error(`Service worker registration failed: ${(a==null?void 0:a.message)||"Unknown error"}`)}try{await o6(s)}catch(a){throw a}}function Po({className:t,defaultValue:s,value:a,min:r=0,max:n=100,...i}){const l=h.useMemo(()=>Array.isArray(a)?a:Array.isArray(s)?s:[r,n],[a,s,r,n]);return e.jsxs($f,{"data-slot":"slider",defaultValue:s,value:a,min:r,max:n,className:Me("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(Uf,{"data-slot":"slider-track",className:Me("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(Bf,{"data-slot":"slider-range",className:Me("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:l.length},(o,c)=>e.jsx(Vf,{"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 d6({onConfigUpdate:t}){const[s,a]=h.useState([]),[r,n]=h.useState(!0),[i,l]=h.useState(null),[o,c]=h.useState(null),[d,m]=h.useState({}),[p,x]=h.useState(null);h.useEffect(()=>{u()},[]);const u=async()=>{var N,_;try{n(!0),c(null);const S=await ml();a(S)}catch(S){c(((_=(N=S.response)==null?void 0:N.data)==null?void 0:_.error)||"Failed to load configurations")}finally{n(!1)}},g=async N=>{var _,S;try{l(N.configKey),c(null);const U=d[N.configKey]??N.configValue;if(N.validationRules){const F=parseFloat(U);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 Vs(N.configKey,U),a(F=>F.map($=>$.configKey===N.configKey?{...$,configValue:U}:$)),m(F=>{const $={...F};return delete $[N.configKey],$}),x(`${N.displayName} updated successfully`),setTimeout(()=>x(null),3e3),t&&t()}catch(U){c(U.message||((S=(_=U.response)==null?void 0:_.data)==null?void 0:S.error)||"Failed to save configuration")}finally{l(null)}},f=async N=>{var _,S;if(confirm(`Reset "${N.displayName}" to default value?`))try{l(N.configKey),c(null),await DA(N.configKey),a(U=>U.map(F=>F.configKey===N.configKey?{...F,configValue:F.defaultValue||""}:F)),m(U=>{const F={...U};return delete F[N.configKey],F}),x(`${N.displayName} reset to default`),setTimeout(()=>x(null),3e3)}catch(U){c(((S=(_=U.response)==null?void 0:_.data)==null?void 0:S.error)||"Failed to reset configuration")}finally{l(null)}},b=(N,_)=>{m(S=>({...S,[N]:_}))},j=N=>d[N.configKey]??N.configValue,y=N=>d[N.configKey]!==void 0&&d[N.configKey]!==N.configValue,w=N=>{var U,F,$,P;const _=j(N),S=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 ${_==="true"?"bg-green-500":"bg-slate-400"}`}),e.jsx("span",{className:`text-sm font-medium ${_==="true"?"text-green-700":"text-slate-600"}`,children:_==="true"?"Enabled":"Disabled"})]}),e.jsx(ms,{checked:_==="true",onCheckedChange:I=>b(N.configKey,I?"true":"false"),disabled:S})]});case"slider":const T=parseInt(_)||0,k=((U=N.validationRules)==null?void 0:U.min)||0,B=((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: ",k,"-",B]})]}),e.jsx(Po,{value:[T],min:k,max:B,step:1,onValueChange:([I])=>{I!==void 0&&b(N.configKey,I.toString())},disabled:S,className:"w-full"})]});case"number":return e.jsx(Ce,{type:"number",value:_,onChange:I=>b(N.configKey,I.target.value),disabled:S,min:($=N.validationRules)==null?void 0:$.min,max:(P=N.validationRules)==null?void 0:P.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(Ce,{type:"text",value:_,onChange:I=>b(N.configKey,I.target.value),disabled:S,className:"font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"})}},v=N=>{switch(N){case"TAT_SETTINGS":return e.jsx(st,{className:"w-5 h-5"});case"DOCUMENT_POLICY":return e.jsx(Ie,{className:"w-5 h-5"});case"NOTIFICATION_RULES":return e.jsx(Ms,{className:"w-5 h-5"});case"AI_CONFIGURATION":return e.jsx(Yi,{className:"w-5 h-5"});case"WORKFLOW_SHARING":return e.jsx(an,{className:"w-5 h-5"});default:return e.jsx(cr,{className:"w-5 h-5"})}},C=["DASHBOARD_LAYOUT"],A=["ALLOW_EXTERNAL_SHARING","NOTIFICATION_BATCH_DELAY_MS","AI_REMARK_MAX_CHARACTERS"],L=s.filter(N=>!C.includes(N.configCategory)&&!A.includes(N.configKey)),D=L.reduce((N,_)=>(N[_.configCategory]||(N[_.configCategory]=[]),N[_.configCategory].push(_),N),{});if(Object.keys(D).forEach(N=>{const _=D[N];_&&_.sort((S,U)=>S.sortOrder-U.sortOrder)}),r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Qe,{className:"w-8 h-8 animate-spin text-gray-400"})});if(L.length===0)return e.jsx(q,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ee,{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(cr,{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 R=Object.keys(D);return e.jsxs("div",{className:"space-y-6",children:[p&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-green-500 rounded-md",children:e.jsx(Oe,{className:"w-4 h-4 text-white shrink-0"})}),e.jsx("p",{className:"text-sm font-medium text-green-900",children:p})]}),o&&e.jsxs("div",{className:"p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300",children:[e.jsx("div",{className:"p-1.5 bg-red-500 rounded-md",children:e.jsx(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(M,{size:"sm",variant:"ghost",onClick:()=>c(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsxs(si,{defaultValue:R[0],className:"w-full",children:[e.jsx(ai,{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:R.map(N=>e.jsx(Lt,{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))}),R.map(N=>{var _,S,U;return e.jsx(Ot,{value:N,className:"space-y-4 mt-6",children:e.jsxs(q,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(oe,{className:"pb-4 border-b border-slate-100",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md",children:e.jsx("div",{className:"text-white",children:v(N)})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-slate-900",children:N.replace(/_/g," ")}),e.jsxs(ye,{className:"text-sm",children:[((_=D[N])==null?void 0:_.length)||0," setting",(((S=D[N])==null?void 0:S.length)||0)!==1?"s":""," available"]})]})]})}),e.jsx(ee,{className:"space-y-6",children:(U=D[N])==null?void 0:U.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(te,{className:"text-sm font-semibold text-slate-900",children:F.displayName}),y(F)&&e.jsx(ae,{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(ae,{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(M,{size:"sm",onClick:()=>g(F),disabled:!y(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(Qe,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"w-4 h-4"}),"Save Changes"]})}),F.defaultValue&&e.jsxs(M,{size:"sm",variant:"outline",onClick:()=>f(F),disabled:i===F.configKey,className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(dh,{className:"w-4 h-4"}),"Reset to Default"]})]})]},F.configKey))})]})},N)})]})]})}function m6(){const[t,s]=h.useState([]),[a,r]=h.useState(!0),[n,i]=h.useState(new Date().getFullYear()),[l,o]=h.useState(!1),[c,d]=h.useState(null),[m,p]=h.useState(null),[x,u]=h.useState(null),[g,f]=h.useState({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1});h.useEffect(()=>{b()},[n]);const b=async()=>{var N,_;try{r(!0),p(null);const S=await PA(n);s(S)}catch(S){p(((_=(N=S.response)==null?void 0:N.data)==null?void 0:_.error)||"Failed to load holidays")}finally{r(!1)}},j=()=>{f({holidayDate:"",holidayName:"",description:"",holidayType:"ORGANIZATIONAL",isRecurring:!1}),d(null),o(!0)},y=N=>{f({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]},v=async()=>{var N,_;try{if(p(null),!g.holidayDate||!g.holidayName){p("Holiday date and name are required");return}c?(await _A(c.holidayId,g),u("Holiday updated successfully")):(await EA(g),u("Holiday created successfully")),await b(),o(!1),setTimeout(()=>u(null),3e3)}catch(S){p(((_=(N=S.response)==null?void 0:N.data)==null?void 0:_.error)||"Failed to save holiday")}},C=async N=>{var _,S;if(confirm(`Delete "${N.holidayName}"?`))try{p(null),await MA(N.holidayId),u("Holiday deleted successfully"),await b(),setTimeout(()=>u(null),3e3)}catch(U){p(((S=(_=U.response)==null?void 0:_.data)==null?void 0:S.error)||"Failed to delete holiday")}},A=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"}},L=Array.from({length:5},(N,_)=>new Date().getFullYear()-1+_),D=t.reduce((N,_)=>{const S=new Date(_.holidayDate).toLocaleString("default",{month:"long"});return N[S]||(N[S]=[]),N[S].push(_),N},{}),R=Object.keys(D).sort((N,_)=>{const S=new Date(Date.parse(N+" 1, 2000")).getMonth(),U=new Date(Date.parse(_+" 1, 2000")).getMonth();return S-U});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(Oe,{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(M,{size:"sm",variant:"ghost",onClick:()=>p(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(q,{className:"shadow-lg border-0 rounded-md",children:e.jsx(oe,{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(dt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Holiday Calendar"}),e.jsx(ye,{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(He,{value:n.toString(),onValueChange:N=>i(parseInt(N)),children:[e.jsx(Ge,{className:"w-24 sm:w-32 border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm",children:e.jsx(We,{})}),e.jsx(Ye,{className:"rounded-md",children:L.map(N=>e.jsx(J,{value:N.toString(),children:N},N))})]}),e.jsxs(M,{onClick:j,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm flex-1 sm:flex-initial",children:[e.jsx(bs,{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(Qe,{className:"w-8 h-8 animate-spin text-gray-400"})}):t.length===0?e.jsx(q,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ee,{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(dt,{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(M,{onClick:j,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(bs,{className:"w-4 h-4"}),"Add First Holiday"]})]})}):e.jsx("div",{className:"space-y-4 sm:space-y-6",children:R.map(N=>{var _,S,U;return e.jsxs(q,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(oe,{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(de,{className:"text-base sm:text-lg font-semibold text-slate-900",children:[N," ",n]}),e.jsxs(ye,{className:"text-xs sm:text-sm",children:[((_=D[N])==null?void 0:_.length)||0," holiday",(((S=D[N])==null?void 0:S.length)||0)!==1?"s":""]})]}),e.jsx("div",{className:"p-2 bg-blue-50 rounded-md",children:e.jsx(dt,{className:"w-4 h-4 text-blue-600"})})]})}),e.jsx(ee,{className:"space-y-3 pt-4",children:(U=D[N])==null?void 0:U.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(ae,{variant:"outline",className:`${A(F.holidayType)} text-[10px] sm:text-xs font-medium shadow-sm`,children:F.holidayType}),F.isRecurring&&e.jsx(ae,{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:up(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(M,{size:"sm",variant:"ghost",onClick:()=>y(F),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(Fi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(M,{size:"sm",variant:"ghost",onClick:()=>C(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(ln,{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(ht,{open:l,onOpenChange:o,children:e.jsxs(mt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(pt,{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(dt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ut,{className:"text-xl font-semibold text-slate-900",children:c?"Edit Holiday":"Add New Holiday"}),e.jsx(_t,{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(te,{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(Ce,{id:"date",type:"date",value:g.holidayDate,onChange:N=>f({...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(te,{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(Ce,{id:"name",placeholder:"e.g., Diwali, Republic Day, Christmas",value:g.holidayName,onChange:N=>f({...g,holidayName:N.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Enter the official name of the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{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(Ce,{id:"description",placeholder:"Add additional details about this holiday...",value:g.description,onChange:N=>f({...g,description:N.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Optional description or notes about the holiday"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"type",className:"text-sm font-semibold text-slate-900",children:"Holiday Type"}),e.jsxs(He,{value:g.holidayType,onValueChange:N=>f({...g,holidayType:N}),children:[e.jsx(Ge,{id:"type",className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm",children:e.jsx(We,{})}),e.jsxs(Ye,{className:"rounded-lg",children:[e.jsx(J,{value:"NATIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-red-500"}),e.jsx("span",{children:"National"})]})}),e.jsx(J,{value:"REGIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-500"}),e.jsx("span",{children:"Regional"})]})}),e.jsx(J,{value:"ORGANIZATIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-purple-500"}),e.jsx("span",{children:"Organizational"})]})}),e.jsx(J,{value:"OPTIONAL",className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-500"}),e.jsx("span",{children:"Optional"})]})})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Select the category of this holiday"})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-gradient-to-br from-slate-50 to-slate-100/50 border-2 border-slate-200 rounded-lg hover:border-slate-300 hover:bg-slate-100 transition-all cursor-pointer group",onClick:()=>f({...g,isRecurring:!g.isRecurring}),children:[e.jsx("input",{type:"checkbox",id:"recurring",checked:g.isRecurring,onChange:N=>f({...g,isRecurring:N.target.checked}),className:"mt-0.5 rounded border-slate-300 text-re-green focus:ring-2 focus:ring-re-green/20 focus:ring-offset-0 w-4 h-4 cursor-pointer"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(te,{htmlFor:"recurring",className:"font-semibold cursor-pointer text-sm text-slate-900 block mb-1",children:"Recurring Holiday"}),e.jsx("p",{className:"text-xs text-slate-600",children:"This holiday will automatically repeat every year on the same date"})]})]})]}),e.jsxs(Et,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(M,{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(M,{onClick:v,disabled:!g.holidayDate||!g.holidayName,className:"h-11 bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(dt,{className:"w-4 h-4 mr-2"}),c?"Update Holiday":"Add Holiday"]})]})]})})]})}function u6(t,s){let a=null;return function(...n){const i=()=>{a=null,t(...n)};a&&clearTimeout(a),a=setTimeout(i,s)}}function x6(){const[t,s]=h.useState(""),[a,r]=h.useState([]),[n,i]=h.useState(!1),[l,o]=h.useState(null),[c,d]=h.useState("USER"),[m,p]=h.useState(!1),[x,u]=h.useState(null),[g,f]=h.useState([]),[b,j]=h.useState(!1),[y,w]=h.useState({admins:0,management:0,users:0}),[v,C]=h.useState("ELEVATED"),[A,L]=h.useState(1),[D,R]=h.useState(1),[N,_]=h.useState(0),S=10,U=h.useRef(null),F=h.useRef(null),$=h.useCallback(u6(async O=>{var z,K,re;if(!O||!O.startsWith("@")||O.length<2){r([]),i(!1);return}i(!0);try{const G=O.slice(1),ve=((z=(await sa.searchUsers(G,20)).data)==null?void 0:z.data)||[];r(ve)}catch(G){console.error("Search failed:",G),u({type:"error",text:((re=(K=G.response)==null?void 0:K.data)==null?void 0:re.message)||"Failed to search users"})}finally{i(!1)}},300),[]),P=O=>{const z=O.target.value;s(z),$(z)},T=async O=>{o(O),s(O.email),r([]);const z=g.find(K=>K.email.toLowerCase()===O.email.toLowerCase()||K.userId===O.userId);if(z&&z.role)d(z.role);else try{const re=(await sa.getAllUsers()).find(G=>G.email&&G.email.toLowerCase()===O.email.toLowerCase()||G.userId&&G.userId===O.userId);re&&re.role?d(re.role):d("USER")}catch(K){console.error("Failed to check user role:",K),d("USER")}},k=async()=>{var O,z;if(!l||!c){u({type:"error",text:"Please select a user and role"});return}p(!0),u(null);try{await sa.assignRole(l.email,c),u({type:"success",text:`Successfully assigned ${c} role to ${l.displayName||l.email}`}),o(null),s(""),d("USER"),await B(),await I()}catch(K){console.error("Role assignment failed:",K),u({type:"error",text:((z=(O=K.response)==null?void 0:O.data)==null?void 0:z.error)||"Failed to assign role"})}finally{p(!1)}},B=async(O=A)=>{var z,K,re,G,se,ve;j(!0);try{const Te=await sa.getUsersByRole(v,O,S),Ke=((K=(z=Te.data)==null?void 0:z.data)==null?void 0:K.users)||[],Je=(G=(re=Te.data)==null?void 0:re.data)==null?void 0:G.pagination,Pe=(ve=(se=Te.data)==null?void 0:se.data)==null?void 0:ve.summary;f(Ke),Je&&(L(Je.currentPage),R(Je.totalPages),_(Je.totalUsers)),Pe&&w({admins:Pe.ADMIN||0,management:Pe.MANAGEMENT||0,users:Pe.USER||0})}catch(Te){console.error("Failed to fetch users:",Te)}finally{j(!1)}},I=async()=>{var O,z,K,re,G,se;try{const ve=await sa.getRoleStatistics(),Te=((z=(O=ve.data)==null?void 0:O.data)==null?void 0:z.statistics)||((K=ve.data)==null?void 0:K.statistics)||[];w({admins:parseInt(((re=Te.find(Ke=>Ke.role==="ADMIN"))==null?void 0:re.count)||"0"),management:parseInt(((G=Te.find(Ke=>Ke.role==="MANAGEMENT"))==null?void 0:G.count)||"0"),users:parseInt(((se=Te.find(Ke=>Ke.role==="USER"))==null?void 0:se.count)||"0")})}catch(ve){console.error("Failed to fetch statistics:",ve)}};h.useEffect(()=>{B(1),I()},[v]);const E=O=>{C(O),L(1)},W=O=>{B(O)},V=O=>{C(O),L(1),requestAnimationFrame(()=>{const z=F.current;z&&z.scrollIntoView({behavior:"smooth",block:"start"})})};h.useEffect(()=>{const O=z=>{U.current&&!U.current.contains(z.target)&&r([])};return a.length>0&&document.addEventListener("mousedown",O),()=>{document.removeEventListener("mousedown",O)}},[a]);const Y=O=>{switch(O){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"}},Z=O=>{switch(O){case"ADMIN":return e.jsx(Vr,{className:"w-5 h-5 text-slate-800"});case"MANAGEMENT":return e.jsx(Jt,{className:"w-5 h-5 text-slate-800"});default:return e.jsx(Vt,{className:"w-5 h-5 text-slate-800"})}};return e.jsxs(q,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(oe,{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(Fb,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg font-semibold text-gray-900",children:"User Role Management"}),e.jsx(ye,{className:"text-sm text-gray-600",children:"Search for users, assign roles, and manage user permissions across the system"})]})]})}),e.jsxs(ee,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6",children:[e.jsx(q,{className:`border-2 bg-gradient-to-br from-yellow-50 to-yellow-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${v==="ADMIN"?"border-yellow-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"admin-count-card",onClick:()=>V("ADMIN"),children:e.jsx(ee,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Administrators"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"admin-count",children:y.admins}),e.jsx("p",{className:"text-xs text-yellow-700 mt-1 font-semibold",children:v==="ADMIN"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-yellow-400 to-yellow-500 rounded-xl shadow-md",children:e.jsx(Vr,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(q,{className:`border-2 bg-gradient-to-br from-blue-50 to-blue-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${v==="MANAGEMENT"?"border-blue-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"management-count-card",onClick:()=>V("MANAGEMENT"),children:e.jsx(ee,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Management"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"management-count",children:y.management}),e.jsx("p",{className:"text-xs text-blue-700 mt-1 font-semibold",children:v==="MANAGEMENT"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-blue-400 to-blue-500 rounded-xl shadow-md",children:e.jsx(Jt,{className:"w-6 h-6 text-slate-800"})})]})})}),e.jsx(q,{className:`border-2 bg-gradient-to-br from-gray-50 to-gray-100/50 hover:shadow-lg transition-all rounded-xl cursor-pointer ${v==="USER"?"border-gray-400 shadow-lg":"border-transparent shadow-md"}`,"data-testid":"user-count-card",onClick:()=>V("USER"),children:e.jsx(ee,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wide",children:"Regular Users"}),e.jsx("p",{className:"text-3xl font-bold text-gray-900 mt-2","data-testid":"user-count",children:y.users}),e.jsx("p",{className:"text-xs text-gray-700 mt-1 font-semibold",children:v==="USER"?"✓ Viewing":"Click to view"})]}),e.jsx("div",{className:"p-3 bg-gradient-to-br from-gray-400 to-gray-500 rounded-xl shadow-md",children:e.jsx(Vt,{className:"w-6 h-6 text-slate-800"})})]})})})]}),e.jsx(Qt,{}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-gray-900 mb-1",children:"Assign User Role"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Search for a user in Okta and assign them a role"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",ref:U,children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Search User"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ss,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none"}),e.jsx(Ce,{type:"text",placeholder:"Type @ to search users...",value:t,onChange:P,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(Qe,{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(O=>e.jsxs("button",{onClick:()=>T(O),className:"w-full text-left p-2 hover:bg-purple-50 rounded-lg transition-colors mb-1 last:mb-0","data-testid":`user-result-${O.email}`,children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:O.displayName||O.email}),e.jsx("p",{className:"text-xs text-gray-600",children:O.email}),O.department&&e.jsxs("p",{className:"text-xs text-gray-500",children:[O.department,O.designation?` • ${O.designation}`:""]})]},O.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(M,{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(He,{value:c,onValueChange:O=>d(O),children:[e.jsx(Ge,{className:"border-gray-200 focus:border-re-green focus:ring-2 focus:ring-re-green/20","data-testid":"role-select",children:e.jsx(We,{placeholder:"Select role"})}),e.jsxs(Ye,{children:[e.jsx(J,{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(J,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Management - Read all data"})]})}),e.jsx(J,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"w-4 h-4 text-yellow-600"}),e.jsx("span",{children:"Administrator - Full access"})]})})]})]})]}),e.jsx(M,{onClick:k,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(Qe,{className:"w-4 h-4 mr-2 animate-spin"}),"Assigning Role..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ps,{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(Oe,{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(Qt,{}),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," ",v!=="ALL"&&v!=="ELEVATED"?v.toLowerCase():""," users)"]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs(He,{value:v,onValueChange:E,children:[e.jsx(Ge,{className:"w-[200px] h-10 border rounded-lg border-gray-300",children:e.jsx(We,{placeholder:"Filter by role"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"ELEVATED",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-4 h-4 text-purple-600"}),e.jsxs("span",{children:["Elevated (",y.admins+y.management,")"]})]})}),e.jsx(J,{value:"ADMIN",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"w-4 h-4 text-yellow-600"}),e.jsxs("span",{children:["Admins (",y.admins,")"]})]})}),e.jsx(J,{value:"MANAGEMENT",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jt,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Management (",y.management,")"]})]})}),e.jsx(J,{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 (",y.users,")"]})]})}),e.jsx(J,{value:"ALL",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jt,{className:"w-4 h-4 text-gray-600"}),e.jsxs("span",{children:["All Users (",y.admins+y.management+y.users,")"]})]})})]})]})})]}),e.jsx("div",{className:"pt-2",children:b?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Qe,{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(Jt,{className:"w-6 h-6 text-gray-400"})}),e.jsx("p",{className:"font-medium text-gray-700",children:"No users found"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:v==="ELEVATED"?"Assign ADMIN or MANAGEMENT roles to see users here":"No users match the selected filter"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2","data-testid":"users-list",children:g.map(O=>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-${O.email}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg ${Y(O.role)} flex items-center justify-center shadow-sm`,children:Z(O.role)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-gray-900 truncate",children:O.displayName}),e.jsx("p",{className:"text-sm text-gray-600 truncate",children:O.email}),O.department&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 truncate",children:[O.department,O.designation?` • ${O.designation}`:""]})]})]}),e.jsx(ae,{className:`${Y(O.role)} shrink-0`,"data-testid":`role-badge-${O.role}`,children:O.role})]})},O.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 ",(A-1)*S+1," to ",Math.min(A*S,N)," of ",N," users"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M,{variant:"outline",size:"sm",onClick:()=>W(A-1),disabled:A===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)},(O,z)=>{let K;return D<=5||A<=3?K=z+1:A>=D-2?K=D-4+z:K=A-2+z,e.jsx(M,{variant:A===K?"default":"outline",size:"sm",onClick:()=>W(K),className:`w-9 h-9 p-0 ${A===K?"bg-re-green hover:bg-re-green/90 text-white":""}`,"data-testid":`page-${K}-button`,children:K},K)})}),e.jsx(M,{variant:"outline",size:"sm",onClick:()=>W(A+1),disabled:A===D,"data-testid":"next-page-button",children:"Next"})]})]})]})})]})]})]})}function h6(){const[t,s]=h.useState([]),[a,r]=h.useState(!0),[n,i]=h.useState(!1),[l,o]=h.useState(null),[c,d]=h.useState(null),[m,p]=h.useState(null),[x,u]=h.useState({title:"",itemCode:"",taxationType:"",sapRefNo:""});h.useEffect(()=>{g()},[]);const g=async()=>{var C,A;try{r(!0),d(null);const L=await OA(!1);s(L)}catch(L){const D=((A=(C=L.response)==null?void 0:C.data)==null?void 0:A.error)||"Failed to load activity types";d(D),X.error(D)}finally{r(!1)}},f=()=>{u({title:"",itemCode:"",taxationType:"",sapRefNo:""}),o(null),i(!0)},b=C=>{u({title:C.title,itemCode:C.itemCode||"",taxationType:C.taxationType||"",sapRefNo:C.sapRefNo||""}),o(C),i(!0)},j=async()=>{var C,A;try{if(d(null),!x.title.trim()||!x.taxationType.trim()||!x.sapRefNo.trim()){d("Title, Taxation Type, and Claim Document Type (SAP Ref) are required"),X.error("Please fill in all mandatory fields");return}const L={title:x.title.trim(),itemCode:x.itemCode.trim()||null,taxationType:x.taxationType.trim(),sapRefNo:x.sapRefNo.trim()};l?(await UA(l.activityTypeId,L),p("Activity type updated successfully"),X.success("Activity type updated successfully")):(await $A(L),p("Activity type created successfully"),X.success("Activity type created successfully")),await g(),i(!1),setTimeout(()=>p(null),3e3)}catch(L){const D=((A=(C=L.response)==null?void 0:C.data)==null?void 0:A.error)||"Failed to save activity type";d(D),X.error(D)}},y=async C=>{var A,L;if(confirm(`Delete "${C.title}"? This will deactivate the activity type.`))try{d(null),await BA(C.activityTypeId),p("Activity type deleted successfully"),X.success("Activity type deleted successfully"),await g(),setTimeout(()=>p(null),3e3)}catch(D){const R=((L=(A=D.response)==null?void 0:A.data)==null?void 0:L.error)||"Failed to delete activity type";d(R),X.error(R)}},w=t.filter(C=>C.isActive!==!1&&C.isActive!==void 0),v=t.filter(C=>C.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(Oe,{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(M,{size:"sm",variant:"ghost",onClick:()=>d(null),className:"ml-auto hover:bg-red-100",children:"Dismiss"})]}),e.jsx(q,{className:"shadow-lg border-0 rounded-md",children:e.jsx(oe,{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(Ie,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx(de,{className:"text-lg sm:text-xl font-semibold text-slate-900",children:"Activity Types"}),e.jsx(ye,{className:"text-sm",children:"Manage dealer claim activity types"})]})]}),e.jsxs(M,{onClick:f,className:"gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm",children:[e.jsx(bs,{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(Qe,{className:"w-8 h-8 animate-spin text-gray-400"})}):w.length===0?e.jsx(q,{className:"shadow-lg border-0 rounded-md",children:e.jsxs(ee,{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(Ie,{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(M,{onClick:f,variant:"outline",className:"gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm",children:[e.jsx(bs,{className:"w-4 h-4"}),"Add First Activity Type"]})]})}):e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(q,{className:"shadow-lg border-0 rounded-md",children:[e.jsx(oe,{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(de,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Active Activity Types"}),e.jsxs(ye,{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(Oe,{className:"w-4 h-4 text-green-600"})})]})}),e.jsx(ee,{className:"space-y-3 pt-4",children:w.map(C=>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:C.title}),e.jsx(ae,{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:[C.itemCode&&e.jsxs("span",{className:"font-medium",children:["Item Code: ",e.jsx("span",{className:"text-slate-900",children:C.itemCode})]}),C.taxationType&&e.jsxs("span",{className:"font-medium",children:["Taxation: ",e.jsx("span",{className:"text-slate-900",children:C.taxationType})]}),C.sapRefNo&&e.jsxs("span",{className:"font-medium",children:["SAP Ref: ",e.jsx("span",{className:"text-slate-900",children:C.sapRefNo})]}),!C.itemCode&&!C.taxationType&&!C.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(M,{size:"sm",variant:"ghost",onClick:()=>b(C),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(Fi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]}),e.jsxs(M,{size:"sm",variant:"ghost",onClick:()=>y(C),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(ln,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Delete"})]})]})]},C.activityTypeId))})]}),v.length>0&&e.jsxs(q,{className:"shadow-lg border-0 rounded-md border-amber-200",children:[e.jsx(oe,{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(de,{className:"text-base sm:text-lg font-semibold text-slate-900",children:"Inactive Activity Types"}),e.jsxs(ye,{className:"text-xs sm:text-sm",children:[v.length," inactive type",v.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(ee,{className:"space-y-3 pt-4",children:v.map(C=>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:C.title}),e.jsx(ae,{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(M,{size:"sm",variant:"ghost",onClick:()=>b(C),className:"gap-1.5 hover:bg-blue-50 border border-transparent hover:border-blue-200 text-xs sm:text-sm",children:[e.jsx(Fi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden xs:inline",children:"Edit"})]})})]},C.activityTypeId))})]})]}),e.jsx(ht,{open:n,onOpenChange:i,children:e.jsxs(mt,{className:"sm:max-w-[550px] max-h-[90vh] rounded-lg flex flex-col p-0",children:[e.jsx(pt,{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(Ie,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ut,{className:"text-xl font-semibold text-slate-900",children:l?"Edit Activity Type":"Add New Activity Type"}),e.jsx(_t,{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(te,{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(Ce,{id:"title",placeholder:"e.g., Riders Mania Claims, Legal Claims Reimbursement",value:x.title,onChange:C=>u({...x,title:C.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(te,{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(Ce,{id:"itemCode",placeholder:"e.g., 1, 2, 3",value:x.itemCode,onChange:C=>u({...x,itemCode:C.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(te,{htmlFor:"taxationType",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Taxation Type ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs(He,{value:x.taxationType,onValueChange:C=>u({...x,taxationType:C}),children:[e.jsx(Ge,{id:"taxationType",className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm",children:e.jsx(We,{placeholder:"Select Taxation Type"})}),e.jsxs(Ye,{className:"rounded-lg",children:[e.jsx(J,{value:"GST",className:"p-3",children:"GST"}),e.jsx(J,{value:"Non GST",className:"p-3",children:"Non GST"})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Select whether the activity is GST or Non-GST"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"sapRefNo",className:"text-sm font-semibold text-slate-900 flex items-center gap-1",children:["Claim Document Type (SAP Ref) ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ce,{id:"sapRefNo",placeholder:"e.g., ZCNS, ZRE",value:x.sapRefNo,onChange:C=>u({...x,sapRefNo:C.target.value}),className:"h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Required SAP reference number for CSV generation"})]})]}),e.jsxs(Et,{className:"gap-3 pt-4 border-t border-slate-100 px-6 pb-6 flex-shrink-0",children:[e.jsx(M,{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(M,{onClick:j,disabled:!x.title.trim()||!x.taxationType||!x.sapRefNo.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(Ie,{className:"w-4 h-4 mr-2"}),l?"Update Activity Type":"Add Activity Type"]})]})]})})]})}function oa({className:t,...s}){return e.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:e.jsx("table",{"data-slot":"table",className:Me("w-full caption-bottom text-sm",t),...s})})}function ca({className:t,...s}){return e.jsx("thead",{"data-slot":"table-header",className:Me("[&_tr]:border-b",t),...s})}function da({className:t,...s}){return e.jsx("tbody",{"data-slot":"table-body",className:Me("[&_tr:last-child]:border-0",t),...s})}function xt({className:t,...s}){return e.jsx("tr",{"data-slot":"table-row",className:Me("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",t),...s})}function Ee({className:t,...s}){return e.jsx("th",{"data-slot":"table-head",className:Me("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function Se({className:t,...s}){return e.jsx("td",{"data-slot":"table-cell",className:Me("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",t),...s})}function p6(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function Rx({emails:t,onAdd:s,onRemove:a,placeholder:r}){const[n,i]=h.useState(""),l=()=>{const o=n.trim().toLowerCase();if(o){if(!p6(o)){X.error("Please enter a valid email address");return}if(t.includes(o)){X.error("This email is already in the list");return}s(o),i("")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ce,{type:"email",placeholder:r??"e.g., user@royalenfield.com",value:n,onChange:o=>i(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l()),className:"flex-1"}),e.jsxs(M,{type:"button",variant:"outline",size:"sm",onClick:l,className:"shrink-0 gap-1",children:[e.jsx(bs,{className:"w-4 h-4"}),"Add"]})]}),t.length>0?e.jsx("div",{className:"rounded-md border",children:e.jsxs(oa,{children:[e.jsx(ca,{children:e.jsxs(xt,{children:[e.jsx(Ee,{children:"Email"}),e.jsx(Ee,{className:"w-[80px] text-right",children:"Actions"})]})}),e.jsx(da,{children:t.map(o=>e.jsxs(xt,{children:[e.jsx(Se,{className:"font-medium",children:o}),e.jsx(Se,{className:"text-right",children:e.jsx(M,{type:"button",variant:"ghost",size:"sm",onClick:()=>a(o),className:"text-destructive hover:text-destructive",children:e.jsx(ln,{className:"w-4 h-4"})})})]},o))})]})}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center rounded-md border border-dashed",children:"No viewers added. Add emails above or leave empty to allow all RE users with access."})]})}function Dx(t,s){return{enabled:t,template:s}}const Jl=()=>({enabled:!0,templateRe:"26AS data has been added. Please review and use for matching dealer Form 16 submissions.",templateDealers:"New 26AS data has been uploaded. You can now submit your Form 16 for the relevant quarter if you haven’t already."});function g6(){const[t,s]=h.useState(!0),[a,r]=h.useState(!1),[n,i]=h.useState([]),[l,o]=h.useState([]),[c,d]=h.useState(!0),[m,p]=h.useState(7),[x,u]=h.useState(Jl()),[g,f]=h.useState(Dx(!0,"Form 16 submitted successfully. Credit note: [CreditNoteRef].")),[b,j]=h.useState(Dx(!0,"Form 16 submission was unsuccessful. Issue: [Issue]. Please review.")),[y,w]=h.useState(!0),[v,C]=h.useState(0),[A,L]=h.useState(24),[D,R]=h.useState("09:00"),[N,_]=h.useState("Please submit your Form 16 at your earliest. [Name], due date: [DueDate]."),[S,U]=h.useState(!0),[F,$]=h.useState(0),[P,T]=h.useState(12),[k,B]=h.useState("10:00"),[I,E]=h.useState("Reminder: Form 16 submission is pending. [Name], [Request ID]. Please review.");h.useEffect(()=>{let V=!0;return FA().then(Y=>{if(V){if(i(Y.submissionViewerEmails??[]),o(Y.twentySixAsViewerEmails??[]),d(Y.reminderEnabled??!0),p(typeof Y.reminderDays=="number"?Y.reminderDays:7),Y.notification26AsDataAdded){const Z=Y.notification26AsDataAdded;u({enabled:Z.enabled??!0,templateRe:Z.templateRe??Z.template??Jl().templateRe,templateDealers:Z.templateDealers??Jl().templateDealers})}Y.notificationForm16SuccessCreditNote&&f(Y.notificationForm16SuccessCreditNote),Y.notificationForm16Unsuccessful&&j(Y.notificationForm16Unsuccessful),w(Y.alertSubmitForm16Enabled??!0),C(Y.alertSubmitForm16FrequencyDays??0),L(Y.alertSubmitForm16FrequencyHours??24),R(Y.alertSubmitForm16RunAtTime!==void 0&&Y.alertSubmitForm16RunAtTime!==null?Y.alertSubmitForm16RunAtTime:"09:00"),_(Y.alertSubmitForm16Template??"Please submit your Form 16 at your earliest. [Name], due date: [DueDate]."),U(Y.reminderNotificationEnabled??!0),$(Y.reminderFrequencyDays??0),T(Y.reminderFrequencyHours??12),B(Y.reminderRunAtTime!==void 0&&Y.reminderRunAtTime!==null?Y.reminderRunAtTime:"10:00"),E(Y.reminderNotificationTemplate??"Reminder: Form 16 submission is pending. [Name], [Request ID]. Please review.")}}).catch(()=>{V&&X.error("Failed to load Form 16 configuration")}).finally(()=>{V&&s(!1)}),()=>{V=!1}},[]);const W=async()=>{r(!0);try{await IA({submissionViewerEmails:n,twentySixAsViewerEmails:l,reminderEnabled:c,reminderDays:Math.max(1,Math.min(365,m))||7,notification26AsDataAdded:x,notificationForm16SuccessCreditNote:g,notificationForm16Unsuccessful:b,alertSubmitForm16Enabled:y,alertSubmitForm16FrequencyDays:Math.max(0,Math.min(365,v)),alertSubmitForm16FrequencyHours:Math.max(0,Math.min(168,A)),alertSubmitForm16RunAtTime:D??"",alertSubmitForm16Template:N,reminderNotificationEnabled:S,reminderFrequencyDays:Math.max(0,Math.min(365,F)),reminderFrequencyHours:Math.max(0,Math.min(168,P)),reminderRunAtTime:k??"",reminderNotificationTemplate:I}),X.success("Form 16 configuration saved")}catch{X.error("Failed to save Form 16 configuration")}finally{r(!1)}};return t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Qe,{className:"w-8 h-8 animate-spin text-re-green"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Form 16 Administration"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Configure Form 16 access, who can view submission data and 26AS, and notification settings."})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Submission data viewers (RE)"}),e.jsx("p",{className:"text-2xl font-semibold",children:n.length}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Who can see Form 16 submissions"})]}),e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"26AS viewers (RE)"}),e.jsx("p",{className:"text-2xl font-semibold",children:l.length}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Who can see 26AS page"})]}),e.jsxs("div",{className:"p-4 bg-green-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Reminders to dealers"}),e.jsx("p",{className:"text-2xl font-semibold text-green-600",children:c?"On":"Off"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Pending Form 16 reminder schedule"})]}),e.jsxs("div",{className:"p-4 bg-purple-50 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Email / in-app notifications"}),e.jsxs("p",{className:"text-2xl font-semibold text-purple-600",children:[[x==null?void 0:x.enabled,g==null?void 0:g.enabled,b==null?void 0:b.enabled,y,S].filter(Boolean).length," ","/ 5 enabled"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"To dealers and RE as per rules below"})]})]}),e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"w-5 h-5"}),"Submission data – who can see"]}),e.jsxs(ye,{children:["Users with these email addresses can see Form 16 submission data (and the Form 16 menu in the sidebar). Use the ",e.jsx("strong",{children:"exact login email"})," of each user (the same email they use to sign in). Leave the list empty to allow all RE users with Form 16 access."]})]}),e.jsx(ee,{children:e.jsx(Rx,{emails:n,onAdd:V=>i(Y=>[...Y,V].sort()),onRemove:V=>i(Y=>Y.filter(Z=>Z!==V)),placeholder:"e.g., user@royalenfield.com"})})]}),e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Ib,{className:"w-5 h-5"}),"26AS page and button – who can see"]}),e.jsxs(ye,{children:["Users with these email addresses can see the 26AS page and 26AS menu item. Use the ",e.jsx("strong",{children:"exact login email"})," of each user. Leave empty to allow all RE users."]})]}),e.jsx(ee,{children:e.jsx(Rx,{emails:l,onAdd:V=>o(Y=>[...Y,V].sort()),onRemove:V=>o(Y=>Y.filter(Z=>Z!==V)),placeholder:"e.g., user@royalenfield.com"})})]}),e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsxs(de,{className:"flex items-center gap-2",children:[e.jsx(Ms,{className:"w-5 h-5"}),"Reminder schedule (for dealers)"]}),e.jsx(ye,{children:"When reminders are enabled, dealers with pending Form 16 for a quarter are reminded at this interval. Set how often (in days) the system may send them a reminder to submit Form 16."})]}),e.jsxs(ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{htmlFor:"reminder-enabled",children:"Enable reminders to dealers"}),e.jsx(ms,{id:"reminder-enabled",checked:c,onCheckedChange:d})]}),e.jsxs("div",{className:"space-y-2 max-w-xs",children:[e.jsx(te,{htmlFor:"reminder-days",children:"Remind dealers every (days)"}),e.jsx(Ce,{id:"reminder-days",type:"number",min:1,max:365,value:m,onChange:V=>p(parseInt(V.target.value,10)||7)})]})]})]}),e.jsxs(q,{children:[e.jsxs(oe,{children:[e.jsx(de,{children:"Email and in-app notifications"}),e.jsx(ye,{children:"Configure who receives each notification, what triggers it, and when it is sent. Templates support placeholders such as [Name], [Request ID], [DueDate]."})]}),e.jsx(ee,{className:"space-y-6",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-medium",children:"Form 16 notifications – recipient and trigger"}),e.jsxs("div",{className:"flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0 space-y-3",children:[e.jsx("p",{className:"font-medium",children:"26AS data added"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Sent to:"})," RE users who can view 26AS, and separately to all dealers. ",e.jsx("span",{className:"font-medium text-foreground",children:"When:"})," As soon as new 26AS data is uploaded."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-muted-foreground",children:"Message to RE users"}),e.jsx(is,{rows:2,value:x.templateRe??"",onChange:V=>u(Y=>({...Y,templateRe:V.target.value})),className:"resize-none text-sm mt-1",placeholder:"e.g. 26AS data has been added. Please review..."})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-muted-foreground",children:"Message to dealers"}),e.jsx(is,{rows:2,value:x.templateDealers??"",onChange:V=>u(Y=>({...Y,templateDealers:V.target.value})),className:"resize-none text-sm mt-1",placeholder:"e.g. New 26AS data has been uploaded. You can submit Form 16..."})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Placeholders: [Name], [Request ID]"})]})]}),e.jsx(ms,{checked:x.enabled,onCheckedChange:V=>u(Y=>({...Y,enabled:V}))})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:"Form 16 success – credit note issued"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Sent to:"})," The dealer who submitted the Form 16. ",e.jsx("span",{className:"font-medium text-foreground",children:"When:"})," Immediately after their submission is matched with 26AS and a credit note is generated."]}),e.jsxs("div",{className:"mt-2",children:[e.jsx(is,{rows:2,value:g.template??"",onChange:V=>f(Y=>({...Y,template:V.target.value})),className:"resize-none text-sm",placeholder:"Message template..."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Placeholders: [Name], [CreditNoteRef], [Request ID]"})]})]}),e.jsx(ms,{checked:g.enabled,onCheckedChange:V=>f(Y=>({...Y,enabled:V}))})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:"Form 16 unsuccessful (mismatch or issue)"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Sent to:"})," The dealer who submitted. ",e.jsx("span",{className:"font-medium text-foreground",children:"When:"})," When their submission fails (e.g. value mismatch with 26AS, duplicate, or validation error) so they can correct and resubmit."]}),e.jsxs("div",{className:"mt-2",children:[e.jsx(is,{rows:2,value:b.template??"",onChange:V=>j(Y=>({...Y,template:V.target.value})),className:"resize-none text-sm",placeholder:"Message template..."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Placeholders: [Name], [Issue], [Request ID]"})]})]}),e.jsx(ms,{checked:b.enabled,onCheckedChange:V=>j(Y=>({...Y,enabled:V}))})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:"Alert – submit Form 16 (to dealers who haven’t submitted)"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Sent to:"})," Dealers who have not yet submitted Form 16 for the current FY. ",e.jsx("span",{className:"font-medium text-foreground",children:"When:"})," Daily at the time below (server timezone). All settings are API-driven from this config."]}),e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{htmlFor:"alert-run-at",className:"text-sm whitespace-nowrap",children:"Run daily at (optional):"}),e.jsx(Ce,{id:"alert-run-at",type:"time",value:D,onChange:V=>R(V.target.value),className:"w-28"}),D?e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:()=>R(""),children:"Clear"}):null]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"24h, server TZ. Leave empty to disable daily run."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{htmlFor:"alert-freq-days",className:"text-sm whitespace-nowrap",children:"Frequency (days):"}),e.jsx(Ce,{id:"alert-freq-days",type:"number",min:0,max:365,value:v,onChange:V=>C(Math.max(0,parseInt(V.target.value,10)||0)),className:"w-20"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{htmlFor:"alert-freq-hours",className:"text-sm whitespace-nowrap",children:"Hours:"}),e.jsx(Ce,{id:"alert-freq-hours",type:"number",min:0,max:168,value:A,onChange:V=>L(Math.max(0,parseInt(V.target.value,10)||0)),className:"w-20"})]})]}),e.jsxs("div",{children:[e.jsx(is,{rows:2,value:N,onChange:V=>_(V.target.value),className:"resize-none text-sm mt-1",placeholder:"Message template for alert to dealers..."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Placeholders: [Name], [DueDate], [Request ID]"})]})]})]}),e.jsx(ms,{checked:y,onCheckedChange:w})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:"Reminder – pending Form 16 (to dealers)"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Sent to:"})," Dealers who have at least one open Form 16 submission without a credit note. ",e.jsx("span",{className:"font-medium text-foreground",children:"When:"})," Daily at the time below (server timezone). All settings are API-driven from this config."]}),e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{htmlFor:"reminder-run-at",className:"text-sm whitespace-nowrap",children:"Run daily at (optional):"}),e.jsx(Ce,{id:"reminder-run-at",type:"time",value:k,onChange:V=>B(V.target.value),className:"w-28"}),k?e.jsx(M,{type:"button",variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:()=>B(""),children:"Clear"}):null]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"24h, server TZ. Leave empty to disable daily run."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{htmlFor:"reminder-freq-days",className:"text-sm whitespace-nowrap",children:"Frequency (days):"}),e.jsx(Ce,{id:"reminder-freq-days",type:"number",min:0,max:365,value:F,onChange:V=>$(Math.max(0,parseInt(V.target.value,10)||0)),className:"w-20"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{htmlFor:"reminder-freq-hours",className:"text-sm whitespace-nowrap",children:"Hours:"}),e.jsx(Ce,{id:"reminder-freq-hours",type:"number",min:0,max:168,value:P,onChange:V=>T(Math.max(0,parseInt(V.target.value,10)||0)),className:"w-20"})]})]}),e.jsxs("div",{children:[e.jsx(is,{rows:2,value:I,onChange:V=>E(V.target.value),className:"resize-none text-sm mt-1",placeholder:"Message template for reminder to dealers..."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Placeholders: [Name], [Request ID], [Status], [TAT]"})]})]})]}),e.jsx(ms,{checked:S,onCheckedChange:U})]})]})})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(M,{onClick:W,disabled:a,className:"bg-re-green hover:bg-re-green/90 gap-2",children:[a?e.jsx(Qe,{className:"w-4 h-4 animate-spin"}):e.jsx(Ea,{className:"w-4 h-4"}),"Save Form 16 configuration"]})})]})}function f6({open:t,onClose:s,success:a,message:r}){return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-md",children:[e.jsxs(pt,{children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(Ms,{className:"w-5 h-5 text-blue-600"}),"Push Notifications"]}),e.jsx(_t,{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(Oe,{className:"w-8 h-8 text-green-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Notifications Enabled!"}),e.jsx("p",{className:"text-sm text-gray-600 max-w-sm",children:r||"You will now receive push notifications for workflow updates, approvals, and TAT alerts."})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-red-100 flex items-center justify-center mb-4",children:e.jsx(At,{className:"w-8 h-8 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Subscription Failed"}),e.jsx("p",{className:"text-sm text-gray-600 max-w-sm mb-4 whitespace-pre-line",children:r||"Unable to enable push notifications. Please check your browser settings and try again."}),e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 text-left w-full",children:[e.jsx("p",{className:"text-xs text-amber-800 font-medium mb-2",children:"💡 Troubleshooting Tips:"}),e.jsxs("ul",{className:"text-xs text-amber-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Check if notifications are blocked in browser settings"}),e.jsx("li",{children:"Ensure your browser supports push notifications"}),e.jsx("li",{children:"Try refreshing the page and enabling again"})]})]})]})})}),e.jsx(Et,{children:e.jsx(M,{onClick:s,className:"w-full",children:a?"Done":"Close"})})]})})}const b6=async()=>(await je.get("/user/preferences/notifications")).data.data,j6=async t=>(await je.put("/user/preferences/notifications",t)).data.data;function y6({open:t,onClose:s}){const[a,r]=h.useState({emailNotificationsEnabled:!0,pushNotificationsEnabled:!0,inAppNotificationsEnabled:!0}),[n,i]=h.useState(!0),[l,o]=h.useState(null),[c,d]=h.useState(null),[m,p]=h.useState(null);h.useEffect(()=>{t&&x()},[t]);const x=async()=>{var g,f;try{i(!0),p(null);const b=await b6();r(b)}catch(b){console.error("[NotificationPreferences] Failed to load preferences:",b),p(((f=(g=b.response)==null?void 0:g.data)==null?void 0:f.message)||"Failed to load notification preferences")}finally{i(!1)}},u=async(g,f)=>{var b,j;try{o(g),p(null),d(null);const y={[g]:f},w=await j6(y);r(w),d(`${g==="emailNotificationsEnabled"?"Email":g==="pushNotificationsEnabled"?"Push":"In-App"} notifications ${f?"enabled":"disabled"}`),setTimeout(()=>d(null),3e3)}catch(y){console.error("[NotificationPreferences] Failed to update preference:",y),p(((j=(b=y.response)==null?void 0:b.data)==null?void 0:j.message)||"Failed to update notification preference"),x()}finally{o(null)}};return e.jsx(ht,{open:t,onOpenChange:s,children:e.jsxs(mt,{className:"sm:max-w-[600px] max-h-[85vh] overflow-y-auto",children:[e.jsx(pt,{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(cr,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{children:[e.jsx(ut,{className:"text-xl font-semibold",children:"Notification Preferences"}),e.jsx(_t,{className:"text-sm",children:"Customize how you receive notifications for workflow updates"})]})]})}),e.jsx(Qt,{className:"my-4"}),n?e.jsx("div",{className:"p-12 flex items-center justify-center",children:e.jsx(Qe,{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(Oe,{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(fa,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(te,{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(Qe,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(ms,{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(Ms,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(te,{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(Qe,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(ms,{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(Hs,{className:"w-6 h-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx(te,{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(Qe,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx(ms,{id:"inapp-notifications-modal",checked:a.inAppNotificationsEnabled,onCheckedChange:g=>u("inAppNotificationsEnabled",g),disabled:l==="inAppNotificationsEnabled"})]})]})}),e.jsx(Qt,{}),e.jsx("div",{className:"p-4 bg-gray-50 border border-gray-200 rounded-lg",children:e.jsxs("p",{className:"text-sm text-gray-700 leading-relaxed",children:[e.jsx("span",{className:"font-semibold",children:"Note:"})," These settings control your notification preferences across all channels. Critical system alerts and urgent notifications may still be delivered regardless of these settings to ensure important information reaches you."]})})]})]})})}function v6(){const t=ys(),{user:s}=cs(),a=Nr(s),[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,c]=h.useState(),[d,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(!1),[f,b]=h.useState(!0),[j,y]=h.useState(!1),[w,v]=h.useState(!1);h.useEffect(()=>{C()},[]);const C=async()=>{try{b(!0);const L=await jy();g(L.length>0)}catch(L){console.error("Failed to check subscription status:",L),g(!1)}finally{b(!1)}},A=async()=>{m(!0),n(!1);try{if(!("Notification"in window)){l(!1),c("Notifications are not supported in this browser. Please use a modern browser like Chrome, Firefox, or Edge."),n(!0),m(!1);return}let L=Notification.permission;if(L==="denied"){l(!1),c(`Notification permission was previously denied. To enable notifications: 1. Click the lock icon (🔒) or info icon (ℹ️) in your browser's address bar diff --git a/build/index.html b/build/index.html index 2fea448..d95e65d 100644 --- a/build/index.html +++ b/build/index.html @@ -13,7 +13,7 @@ - +