diff --git a/build/assets/conclusionApi-C6tUM9Rq.js b/build/assets/conclusionApi-CKkdyXjv.js similarity index 90% rename from build/assets/conclusionApi-C6tUM9Rq.js rename to build/assets/conclusionApi-CKkdyXjv.js index b5ac22a..342a471 100644 --- a/build/assets/conclusionApi-C6tUM9Rq.js +++ b/build/assets/conclusionApi-CKkdyXjv.js @@ -1 +1 @@ -import{a as s}from"./index-Dxe43Cgo.js";import"./radix-vendor-CYvDqP9X.js";import"./charts-vendor-BVfwAPj-.js";import"./utils-vendor-BTBPSQfW.js";import"./ui-vendor-BrA5VgBk.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-DJz4SgPf.js";import"./radix-vendor-CYvDqP9X.js";import"./charts-vendor-BVfwAPj-.js";import"./utils-vendor-BTBPSQfW.js";import"./ui-vendor-BrA5VgBk.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-Dxe43Cgo.js b/build/assets/index-DJz4SgPf.js similarity index 99% rename from build/assets/index-Dxe43Cgo.js rename to build/assets/index-DJz4SgPf.js index 5a10af6..468ea2a 100644 --- a/build/assets/index-Dxe43Cgo.js +++ b/build/assets/index-DJz4SgPf.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-C6tUM9Rq.js","assets/radix-vendor-CYvDqP9X.js","assets/charts-vendor-BVfwAPj-.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-BrA5VgBk.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-CKkdyXjv.js","assets/radix-vendor-CYvDqP9X.js","assets/charts-vendor-BVfwAPj-.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-BrA5VgBk.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-BATWUvr6.js"])))=>i.map(i=>d[i]); var W0=Object.defineProperty;var G0=(t,s,a)=>s in t?W0(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var fl=(t,s,a)=>G0(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Vx,R as zx,I as Hx,F as Wx,a as Y0,T as K0,P as Q0,C as X0,b as J0,O as Gx,c as Yx,d as Z0,e as q0,f as ef,D as tf,g as sf,A as af,h as rf,i as nf,k as lf,l as of,m as cf,n as df,V as mf,o as uf,p as xf,q as hf,r as pf,s as gf,t as ff,u as bf,v as jf,w as yf,x as vf,y as Nf,z as wf,B as Cf,E as Sf,G as Af,H as Tf,J as kf,K as Rf,L as Df,M as Ff,N as Pf,Q as Kx,U as Qx,W as If,X as Xx,Y as Jx,Z as Ef,_ as _f,$ as Mf,a0 as Lf,a1 as Of,a2 as $f,a3 as Uf,a4 as Bf,a5 as Vf,a6 as zf,a7 as Hf,a8 as Wf,a9 as Gf,aa as Yf,ab as Kf}from"./radix-vendor-CYvDqP9X.js";import{a as Qf,r as h,c as Zx,d as Zr,B as co,C as Ri,X as Di,Y as Fi,T as qr,L as Pi,e as Fa,P as qx,f as eh,g as th,h as Xf,i as Rm,j as Gi,k as Yi,b as Jf}from"./charts-vendor-BVfwAPj-.js";import{a as Bo,f as sh,s as la,e as Vo,b as Dm,c as Zf,d as _a,g as $n,i as zo,h as ah,j as Qs,k as ra,l as bl,m as Ha,n as qf,o as mo,p as eb,q as et,r as uo,t as tb,u as sb,v as ab,w as rb,x as jl,y as Fm,z as nb,A as rh,B as nh,C as Ho,D as Wo,E as ib,F as lb,G as ih,H as zr,I as yl,J as ob,K as cb,L as db}from"./utils-vendor-BTBPSQfW.js";import{A as fs,S as ps,C as Ze,a as xs,L as Ke,X as jt,H as mb,b as lh,U as zt,F as De,c as $e,d as ln,R as Pt,e as on,f as cn,P as bs,g as ub,h as xb,B as Es,i as ir,j as vl,k as Go,l as Wa,m as Ki,n as Yo,o as ht,p as Ma,q as Et,I as Mr,T as es,r as st,s as Ra,t as hb,u as ts,M as Vs,v as Qi,w as Bt,x as xo,D as At,Z as Xi,y as Zt,z as pb,E as gb,G as fb,J as bb,K as jb,N as yb,O as vb,Q as Nb,V as wb,W as oh,Y as Cb,_ as Sb,$ as ch,a0 as ja,a1 as Kn,a2 as lr,a3 as Ii,a4 as Pm,a5 as oi,a6 as Ei,a7 as dh,a8 as Ct,a9 as Ab,aa as G,ab as zs,ac as Ko,ad as ws,ae as Ji,af as mh,ag as Nt,ah as Tb,ai as kb,aj as uh,ak as Zi,al as xh,am as Rb,an as Qo,ao as js,ap as Ga,aq as hh,ar as qi,as as el,at as ys,au as Db,av as Fb,aw as ph,ax as gh,ay as bi,az as rr,aA as Xo,aB as tl,aC as _i,aD as fh,aE as bh,aF as Jo,aG as sl,aH as al,aI as Pb,aJ as Zs,aK as jh,aL as Mi,aM as Ib,aN as Eb,aO as _b,aP as rl,aQ as nl,aR as Zo,aS as Mb,aT as Im,aU as La,aV as dn,aW as Lb,aX as Wr,aY as Em,aZ as yh,a_ as _m,a$ as vh,b0 as Ob,b1 as $b,b2 as Ub,b3 as Bb,b4 as Nh,b5 as Vb,b6 as zb,b7 as Hb,b8 as qo,b9 as Wb,ba as Gb}from"./ui-vendor-BrA5VgBk.js";import{l as Yb}from"./socket-vendor-TjCxX7sJ.js";import{c as mn,a as Kb}from"./redux-vendor-tbZCm13o.js";import{u as Cs,a as Oa,b as wh,c as Qb,B as Xb,R as Jb,d as Dt,O as Zb}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 ho={},Mm=Qf;ho.createRoot=Mm.createRoot,ho.hydrateRoot=Mm.hydrateRoot;var Ch={exports:{}},Sh={};var Qn=h;function qb(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var ej=typeof Object.is=="function"?Object.is:qb,tj=Qn.useSyncExternalStore,sj=Qn.useRef,aj=Qn.useEffect,rj=Qn.useMemo,nj=Qn.useDebugValue;Sh.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=sj(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=rj(function(){function d(u){if(!c){if(c=!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,ej(m,u))return g;var b=r(u);return n!==void 0&&n(g,b)?(m=u,g):(m=u,p=b)}var c=!1,m,p,x=a===void 0?null:a;return[function(){return d(s())},x===null?void 0:function(){return d(x())}]},[s,a,r,n]);var o=tj(t,i[0],i[1]);return aj(function(){l.hasValue=!0,l.value=o},[o]),nj(o),o};Ch.exports=Sh;var ij=Ch.exports;function lj(t){t()}function oj(){let t=null,s=null;return{clear(){t=null,s=null},notify(){lj(()=>{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 Lm={notify(){},get:()=>[]};function cj(t,s){let a,r=Lm,n=0,i=!1;function l(b){m();const f=r.subscribe(b);let j=!1;return()=>{j||(j=!0,f(),p())}}function o(){r.notify()}function d(){g.onStateChange&&g.onStateChange()}function c(){return i}function m(){n++,a||(a=t.subscribe(d),r=oj())}function p(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Lm)}function x(){i||(i=!0,m())}function u(){i&&(i=!1,p())}const g={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:d,isSubscribed:c,trySubscribe:x,tryUnsubscribe:u,getListeners:()=>r};return g}var dj=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",mj=dj(),uj=()=>typeof navigator<"u"&&navigator.product==="ReactNative",xj=uj(),hj=()=>mj||xj?h.useLayoutEffect:h.useEffect,pj=hj(),Nl=Symbol.for("react-redux-context"),wl=typeof globalThis<"u"?globalThis:{};function gj(){if(!h.createContext)return{};const t=wl[Nl]??(wl[Nl]=new Map);let s=t.get(h.createContext);return s||(s=h.createContext(null),t.set(h.createContext,s)),s}var or=gj();function fj(t){const{children:s,context:a,serverState:r,store:n}=t,i=h.useMemo(()=>{const d=cj(n);return{store:n,subscription:d,getServerState:r?()=>r:void 0}},[n,r]),l=h.useMemo(()=>n.getState(),[n]);pj(()=>{const{subscription:d}=i;return d.onStateChange=d.notifyNestedSubs,d.trySubscribe(),l!==n.getState()&&d.notifyNestedSubs(),()=>{d.tryUnsubscribe(),d.onStateChange=void 0}},[i,l]);const o=a||or;return h.createElement(o.Provider,{value:i},s)}var bj=fj;function ec(t=or){return function(){return h.useContext(t)}}var Ah=ec();function Th(t=or){const s=t===or?Ah:ec(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var jj=Th();function yj(t=or){const s=t===or?jj:Th(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var vj=yj(),Nj=(t,s)=>t===s;function wj(t=or){const s=t===or?Ah:ec(t),a=(r,n={})=>{const{equalityFn:i=Nj}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:d,getServerState:c}=l;h.useRef(!0);const m=h.useCallback({[r.name](x){return r(x)}}[r.name],[r]),p=ij.useSyncExternalStoreWithSelector(d.addNestedSub,o.getState,c||o.getState,m,i);return h.useDebugValue(p),p};return Object.assign(a,{withTypes:()=>a}),a}var Cj=wj(),po=function(t,s){return po=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])},po(t,s)};function Sj(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");po(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var Li=function(){return Li=Object.assign||function(s){for(var a,r=1,n=arguments.length;r0&&g[g.length-1])||w[0]!==6&&w[0]!==2)){f=0;continue}if(w[0]===3&&(!g||w[1]>g[0]&&w[1]0?setTimeout(u,v):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,b;return r(this,function(f){switch(f.label){case 0:return x=this.storageHandler===void 0?l:this.storageHandler,u=i+"-"+p,(g=x.getItemSync(u))===null?[2]:(b=JSON.parse(g)).id!==this.id?[3,2]:[4,Nr.default().lock(b.iat)];case 1:f.sent(),this.acquiredIatSet.delete(b.iat),x.removeItemSync(u),Nr.default().unlock(b.iat),m.notifyWaiters(),f.label=2;case 2:return[2]}})})},m.lockCorrector=function(p){for(var x=Date.now()-5e3,u=p,g=[],b=0;;){var f=u.keySync(b);if(f===null)break;g.push(f),b++}for(var j=!1,y=0;y.")},kj=Li(Li({},Tj),{buildAuthorizeUrl:Gs,buildLogoutUrl:Gs,getAccessTokenSilently:Gs,getAccessTokenWithPopup:Gs,getIdTokenClaims:Gs,loginWithRedirect:Gs,loginWithPopup:Gs,connectAccountWithRedirect:Gs,logout:Gs,handleRedirectCallback:Gs,getDpopNonce:Gs,setDpopNonce:Gs,generateDpopProof:Gs,createFetcher:Gs}),Rj=h.createContext(kj);(function(t){Sj(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 Dj=function(t){return t===void 0&&(t=Rj),h.useContext(t)};const Cl="idToken",Sl="userData",Fj=()=>!0;class at{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(Cl,s)}static getIdToken(){return sessionStorage.getItem(Cl)}static setUserData(s){localStorage.setItem(Sl,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(Sl);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(Sl),sessionStorage.removeItem(Cl)}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 Fj()}}function Al(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));be.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 Bo.post(`${kh}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),d=(l.data.data||l.data).accessToken;return be(s)}catch(i){return at.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function Pj(t,s){const r=(await be.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 Ij(t,s){var a,r;try{const n=await be.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 Ej(){var r;const t={},a=(await be.post("/auth/refresh",t)).data;if((r=a.data)!=null&&r.accessToken||a.accessToken,a.success!==!1)return"cookie-based-auth";throw new Error("Failed to refresh token")}async function Rn(){const s=(await be.get("/auth/me")).data;return s.data||s}async function _j(){var t,s;try{await be.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 go="https://ssodev.rebridge.co.in/realms/RE",Rh="REFLOW",ac=`${window.location.origin}/login/callback`;function Mj(){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=`${go}/protocol/openid-connect/auth?client_id=${Rh}&response_type=code&scope=openid&redirect_uri=${encodeURIComponent(ac)}&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 Lj(t,s){var r,n,i;const a="https://reflow-uat.royalenfield.com/api/v1/";try{const l=await Bo.post(`${a}/auth/tanflow/token-exchange`,{code:t,redirectUri:ac,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 Oj(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=ac,a=new URL(`${go}/protocol/openid-connect/logout`);a.searchParams.set("client_id",Rh),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:`${go}/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 Dh=h.createContext(void 0);function $j({children:t}){const[s,a]=h.useState(!1),[r,n]=h.useState(!0),[i,l]=h.useState(null),[o,d]=h.useState(null),[c,m]=h.useState(!1);h.useEffect(()=>{const v=sessionStorage.getItem("__logout_in_progress__"),w=sessionStorage.getItem("__force_logout__");if(v==="true"||w==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),at.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(D){console.error("Error clearing storage:",D)}a(!1),l(null),n(!1),d(null);return}const S=new URLSearchParams(window.location.search),C=S.has("code");if((S.has("logout")||S.has("okta_logged_out")||S.has("tanflow_logged_out"))&&!C){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(),c?n(!1):x())},[c]),h.useEffect(()=>{if(!s)return;const v=async()=>{try{await j()}catch(C){console.error("Silent refresh failed:",C)}},w=10*60*1e3,S=setInterval(v,w);return()=>clearInterval(S)},[s]);const p=h.useRef(!1);h.useEffect(()=>{if(p.current||window.location.pathname!=="/login/callback")return;(async()=>{const w=new URLSearchParams(window.location.search);if(sessionStorage.getItem("auth_provider")==="tanflow")return;if((w.has("logout")||w.has("tanflow_logged_out")||w.has("okta_logged_out"))&&!w.get("code")){console.log("🚪 Logout redirect detected in callback, redirecting to home");const D=new URLSearchParams;w.has("tanflow_logged_out")&&D.set("tanflow_logged_out","true"),w.has("okta_logged_out")&&D.set("okta_logged_out","true"),w.has("logout")&&D.set("logout",w.get("logout")||Date.now().toString());const T=D.toString()?`/?${D.toString()}`:"/?logout="+Date.now();window.location.replace(T);return}p.current=!0;const C=w.get("code"),I=w.get("error");if(window.history.replaceState({},document.title,"/login/callback"),I){d(new Error(`Authentication error: ${I}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!C){n(!1),sessionStorage.removeItem("auth_provider");return}try{n(!0),a(!1),d(null);const D=`${window.location.origin}/login/callback`,T=await Ij(C,D);l(T.user),a(!0),d(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(D){console.error("❌ Token exchange error in AuthContext:",D),d(D),a(!1),l(null),sessionStorage.removeItem("auth_provider"),p.current=!1}finally{n(!1)}})()},[]);const x=async()=>{var w;if(c){n(!1);return}const v=!0;try{if(n(!0),v){const I=at.getUserData();try{const D=await Rn();l(D),at.setUserData(D),a(!0)}catch(D){if(((w=D==null?void 0:D.response)==null?void 0:w.status)===401)try{await j();const T=await Rn();l(T),at.setUserData(T),a(!0)}catch{at.clearAll(),a(!1),l(null)}else D!=null&&D.isConnectionError?I?(l(I),a(!0)):(a(!1),l(null)):(at.clearAll(),a(!1),l(null))}return}const S=at.getAccessToken(),C=at.getUserData();if(!S){a(!1),l(null),n(!1);return}if(Al(S))try{await j();const I=at.getAccessToken();if(I&&!Al(I)){const D=at.getUserData();if(D)l(D),a(!0);else try{const T=await Rn();l(T),at.setUserData(T),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(C)l(C),a(!0);else try{const I=await Rn();l(I),at.setUserData(I),a(!0)}catch{at.clearAll(),a(!1),l(null)}}catch(S){console.error("Error checking auth status:",S),d(S),at.clearAll(),a(!1),l(null)}finally{n(!1)}},u=async()=>{try{d(null);const v="https://dev-830839.oktapreview.com",w="0oa2jgzvrpdwx2iqd0h8",S=`${window.location.origin}/login/callback`,C="code",I="openid profile email",D=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const T=new URLSearchParams(window.location.search),N=T.has("logout")||T.has("okta_logged_out")||T.has("tanflow_logged_out"),_=sessionStorage.getItem("__force_reauth_after_logout__")==="true",A=N||_;let z=`${v}/oauth2/default/v1/authorize?client_id=${w}&redirect_uri=${encodeURIComponent(S)}&response_type=${C}&scope=${encodeURIComponent(I)}&state=${D}`;A&&(z+="&prompt=login",sessionStorage.removeItem("__force_reauth_after_logout__")),window.location.href=z}catch(v){throw d(v),v}},g=async(v,w)=>{d(null),n(!0);try{const S=await Pj(v,w);l(S.user),a(!0),window.history.replaceState({},document.title,"/")}catch(S){throw d(S),a(!1),l(null),S}finally{n(!1)}},b=async()=>{try{const v=at.getIdToken(),w=sessionStorage.getItem("auth_provider")||(v&&v.includes("tanflow")?"tanflow":null)||"okta";sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),m(!0),a(!1),l(null),d(null),n(!0);try{await _j(),console.log("🚪 Backend logout API called successfully")}catch(T){console.error("🚪 Logout API error:",T),console.warn("🚪 Backend logout failed - httpOnly cookies may not be cleared")}const S=sessionStorage.getItem("__logout_in_progress__"),C=sessionStorage.getItem("__force_logout__"),I=sessionStorage.getItem("auth_provider");if(at.clearAll(),S&&sessionStorage.setItem("__logout_in_progress__",S),C&&sessionStorage.setItem("__force_logout__",C),v&&at.setIdToken(v),I&&sessionStorage.setItem("auth_provider",I),await new Promise(T=>setTimeout(T,100)),w==="tanflow"&&v){console.log("🚪 Initiating Tanflow logout...");try{Oj(v);return}catch(T){console.error("🚪 Tanflow logout error:",T)}}console.log("🚪 Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),v&&at.clearAll();const D=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(D)}catch(v){console.error("🚪 Logout error:",v);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const w=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(w)}catch{window.location.replace("/?logout="+Date.now())}}},f=async()=>{{if(s)return"cookie-based-auth";try{return await j(),s?"cookie-based-auth":null}catch{return null}}const v=at.getAccessToken();if(v&&!Al(v))return v;try{return await j(),at.getAccessToken()}catch{return null}},j=async()=>{try{const w=await Ej();return}catch(w){throw at.clearAll(),a(!1),l(null),w}},y={isAuthenticated:s,isLoading:r,user:i,error:o,login:u,loginWithPassword:g,logout:b,getAccessTokenSilently:f,refreshTokenSilently:j};return e.jsx(Dh.Provider,{value:y,children:t})}function Uj({children:t}){return e.jsx($j,{children:t})}function ds(){const t=h.useContext(Dh);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function wr(t){return(t==null?void 0:t.role)==="ADMIN"}function vn(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function il(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const Um=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,Bm=Zx,rc=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return Bm(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,l=Object.keys(n).map(c=>{const m=a==null?void 0:a[c],p=i==null?void 0:i[c];if(m===null)return null;const x=Um(m)||Um(p);return n[c][x]}),o=a&&Object.entries(a).reduce((c,m)=>{let[p,x]=m;return x===void 0||(c[p]=x),c},{}),d=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((c,m)=>{let{class:p,className:x,...u}=m;return Object.entries(u).every(g=>{let[b,f]=g;return Array.isArray(f)?f.includes({...i,...o}[b]):{...i,...o}[b]===f})?[...c,p,x]:c},[]);return Bm(t,l,d,a==null?void 0:a.class,a==null?void 0:a.className)},nc="-",Bj=t=>{const s=zj(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(nc);return o[0]===""&&o.length!==1&&o.shift(),Fh(o,s)||Vj(l)},getConflictingClassGroupIds:(l,o)=>{const d=a[l]||[];return o&&r[l]?[...d,...r[l]]:d}}},Fh=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?Fh(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(nc);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Vm=/^\[(.+)\]$/,Vj=t=>{if(Vm.test(t)){const s=Vm.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},zj=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return Wj(Object.entries(t.classGroups),a).forEach(([i,l])=>{fo(l,r,i,s)}),r},fo=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:zm(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(Hj(n)){fo(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{fo(l,zm(s,i),a,r)})})},zm=(t,s)=>{let a=t;return s.split(nc).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},Hj=t=>t.isThemeGetter,Wj=(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,Gj=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)}}},Ph="!",Yj=t=>{const{separator:s,experimentalParseClassName:a}=t,r=s.length===1,n=s[0],i=s.length,l=o=>{const d=[];let c=0,m=0,p;for(let f=0;fm?p-m:void 0;return{modifiers:d,hasImportantModifier:u,baseClassName:g,maybePostfixModifierPosition:b}};return a?o=>a({className:o,parseClassName:l}):l},Kj=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},Qj=t=>({cache:Gj(t.cacheSize),parseClassName:Yj(t),...Bj(t)}),Xj=/\s+/,Jj=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(Xj);let o="";for(let d=l.length-1;d>=0;d-=1){const c=l[d],{modifiers:m,hasImportantModifier:p,baseClassName:x,maybePostfixModifierPosition:u}=a(c);let g=!!u,b=r(g?x.substring(0,u):x);if(!b){if(!g){o=c+(o.length>0?" "+o:o);continue}if(b=r(x),!b){o=c+(o.length>0?" "+o:o);continue}g=!1}const f=Kj(m).join(":"),j=p?f+Ph:f,y=j+b;if(i.includes(y))continue;i.push(y);const v=n(b,g);for(let w=0;w0?" "+o:o)}return o};function Zj(){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=Qj(c),r=a.cache.get,n=a.cache.set,i=o,o(d)}function o(d){const c=r(d);if(c)return c;const m=Jj(d,a);return n(d,m),m}return function(){return i(Zj.apply(null,arguments))}}const Kt=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},Eh=/^\[(?:([a-z-]+):)?(.+)\]$/i,ey=/^\d+\/\d+$/,ty=new Set(["px","full","screen"]),sy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,ay=/\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$/,ry=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,ny=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,iy=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ba=t=>en(t)||ty.has(t)||ey.test(t),tr=t=>un(t,"length",hy),en=t=>!!t&&!Number.isNaN(Number(t)),Tl=t=>un(t,"number",en),Nn=t=>!!t&&Number.isInteger(Number(t)),ly=t=>t.endsWith("%")&&en(t.slice(0,-1)),bt=t=>Eh.test(t),sr=t=>sy.test(t),oy=new Set(["length","size","percentage"]),cy=t=>un(t,oy,_h),dy=t=>un(t,"position",_h),my=new Set(["image","url"]),uy=t=>un(t,my,gy),xy=t=>un(t,"",py),wn=()=>!0,un=(t,s,a)=>{const r=Eh.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},hy=t=>ay.test(t)&&!ry.test(t),_h=()=>!1,py=t=>ny.test(t),gy=t=>iy.test(t),fy=()=>{const t=Kt("colors"),s=Kt("spacing"),a=Kt("blur"),r=Kt("brightness"),n=Kt("borderColor"),i=Kt("borderRadius"),l=Kt("borderSpacing"),o=Kt("borderWidth"),d=Kt("contrast"),c=Kt("grayscale"),m=Kt("hueRotate"),p=Kt("invert"),x=Kt("gap"),u=Kt("gradientColorStops"),g=Kt("gradientColorStopPositions"),b=Kt("inset"),f=Kt("margin"),j=Kt("opacity"),y=Kt("padding"),v=Kt("saturate"),w=Kt("scale"),S=Kt("sepia"),C=Kt("skew"),I=Kt("space"),D=Kt("translate"),T=()=>["auto","contain","none"],N=()=>["auto","hidden","clip","visible","scroll"],_=()=>["auto",bt,s],A=()=>[bt,s],z=()=>["",Ba,tr],F=()=>["auto",en,bt],O=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],P=()=>["solid","dashed","dotted","double","none"],k=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],R=()=>["start","end","center","between","around","evenly","stretch"],V=()=>["","0",bt],M=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>[en,bt];return{cacheSize:500,separator:":",theme:{colors:[wn],spacing:[Ba,tr],blur:["none","",sr,bt],brightness:L(),borderColor:[t],borderRadius:["none","","full",sr,bt],borderSpacing:A(),borderWidth:z(),contrast:L(),grayscale:V(),hueRotate:L(),invert:V(),gap:A(),gradientColorStops:[t],gradientColorStopPositions:[ly,tr],inset:_(),margin:_(),opacity:L(),padding:A(),saturate:L(),scale:L(),sepia:V(),skew:L(),space:A(),translate:A()},classGroups:{aspect:[{aspect:["auto","square","video",bt]}],container:["container"],columns:[{columns:[sr]}],"break-after":[{"break-after":M()}],"break-before":[{"break-before":M()}],"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:[...O(),bt]}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[b]}],"inset-x":[{"inset-x":[b]}],"inset-y":[{"inset-y":[b]}],start:[{start:[b]}],end:[{end:[b]}],top:[{top:[b]}],right:[{right:[b]}],bottom:[{bottom:[b]}],left:[{left:[b]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Nn,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:V()}],shrink:[{shrink:V()}],order:[{order:["first","last","none",Nn,bt]}],"grid-cols":[{"grid-cols":[wn]}],"col-start-end":[{col:["auto",{span:["full",Nn,bt]},bt]}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":[wn]}],"row-start-end":[{row:["auto",{span:[Nn,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",...R()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...R(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...R(),"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:[f]}],mx:[{mx:[f]}],my:[{my:[f]}],ms:[{ms:[f]}],me:[{me:[f]}],mt:[{mt:[f]}],mr:[{mr:[f]}],mb:[{mb:[f]}],ml:[{ml:[f]}],"space-x":[{"space-x":[I]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[I]}],"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:[sr]},sr]}],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",sr,tr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Tl]}],"font-family":[{font:[wn]}],"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",en,Tl]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Ba,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",Ba,tr]}],"underline-offset":[{"underline-offset":["auto",Ba,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:A()}],"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:[...O(),dy]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",cy]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},uy]}],"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":[Ba,bt]}],"outline-w":[{outline:[Ba,tr]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:z()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[Ba,tr]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",sr,xy]}],"shadow-color":[{shadow:[wn]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...k(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":k()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[d]}],"drop-shadow":[{"drop-shadow":["","none",sr,bt]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[p]}],saturate:[{saturate:[v]}],sepia:[{sepia:[S]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[d]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[j]}],"backdrop-saturate":[{"backdrop-saturate":[v]}],"backdrop-sepia":[{"backdrop-sepia":[S]}],"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:L()}],ease:[{ease:["linear","in","out","in-out",bt]}],delay:[{delay:L()}],animate:[{animate:["none","spin","ping","pulse","bounce",bt]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[w]}],"scale-x":[{"scale-x":[w]}],"scale-y":[{"scale-y":[w]}],rotate:[{rotate:[Nn,bt]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"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":A()}],"scroll-mx":[{"scroll-mx":A()}],"scroll-my":[{"scroll-my":A()}],"scroll-ms":[{"scroll-ms":A()}],"scroll-me":[{"scroll-me":A()}],"scroll-mt":[{"scroll-mt":A()}],"scroll-mr":[{"scroll-mr":A()}],"scroll-mb":[{"scroll-mb":A()}],"scroll-ml":[{"scroll-ml":A()}],"scroll-p":[{"scroll-p":A()}],"scroll-px":[{"scroll-px":A()}],"scroll-py":[{"scroll-py":A()}],"scroll-ps":[{"scroll-ps":A()}],"scroll-pe":[{"scroll-pe":A()}],"scroll-pt":[{"scroll-pt":A()}],"scroll-pr":[{"scroll-pr":A()}],"scroll-pb":[{"scroll-pb":A()}],"scroll-pl":[{"scroll-pl":A()}],"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:[Ba,tr,Tl]}],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"]}}},by=qj(fy);function Me(...t){return by(Zx(t))}const Un=rc("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background text-foreground hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),E=h.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?Vx:"button";return e.jsx(l,{"data-slot":"button",className:Me(Un({variant:s,size:a,className:t})),ref:i,...n})});E.displayName="Button";function Z({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 ce({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 te({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:Me("px-6 [&:last-child]:pb-6",t),...s})}const ll="/assets/Re_Logo-By51taPS.png",Hm="/assets/landing_page_image-ClTD-4qZ.jpg";function jy(){var p,x;const{login:t,isLoading:s,error:a}=ds(),[r,n]=h.useState(!1),[i,l]=h.useState(null),[o,d]=h.useState(!1);h.useEffect(()=>{const u=new Image;u.src=Hm,u.onload=()=>d(!0),u.complete&&d(!0)},[]);const c=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{Mj()}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(${Hm})`:"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(Z,{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:ll,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(te,{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(E,{onClick:c,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(E,{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 Mh(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=ds(),[n,i]=h.useState("exchanging");h.useEffect(()=>{if(a){i("error");return}if(s){const d=new URLSearchParams(window.location.search).get("code");i(d&&!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:ll,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(xs,{className:"w-16 h-16 text-green-500"})}),e.jsx(xs,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(Ke,{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,11 +33,11 @@ var W0=Object.defineProperty;var G0=(t,s,a)=>s in t?W0(t,s,{enumerable:!0,config ${g}px !important; top: ${p}px !important; } - `),()=>{f.contains(b)&&f.removeChild(b)}},[s]),e.jsx(e2,{isPresent:s,childRef:i,sizeRef:l,children:h.cloneElement(t,{ref:d})})}const s2=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:d})=>{const c=fc(a2),m=h.useId();let p=!0,x=h.useMemo(()=>(p=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:u=>{c.set(u,!0);for(const g of c.values())if(!g)return;r&&r()},register:u=>(c.set(u,!1),()=>c.delete(u))}),[a,c,r]);return i&&p&&(x={...x}),h.useMemo(()=>{c.forEach((u,g)=>c.set(g,!1))},[a]),h.useEffect(()=>{!a&&!c.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(t2,{isPresent:a,anchorX:o,root:d,children:t})),e.jsx(dl.Provider,{value:x,children:t})};function a2(){return new Map}function xg(t=!0){const s=h.useContext(dl);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 ui=t=>t.key||"";function Su(t){const s=[];return h.Children.forEach(t,a=>{h.isValidElement(a)&&s.push(a)}),s}const ml=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",root:d})=>{const[c,m]=xg(l),p=h.useMemo(()=>Su(t),[t]),x=l&&!c?[]:p.map(ui),u=h.useRef(!0),g=h.useRef(p),b=fc(()=>new Map),[f,j]=h.useState(p),[y,v]=h.useState(p);Np(()=>{u.current=!1,g.current=p;for(let C=0;C{const I=ui(C),D=l&&!c?!1:p===y||x.includes(I),T=()=>{if(b.has(I))b.set(I,!0);else return;let N=!0;b.forEach(_=>{_||(N=!1)}),N&&(S==null||S(),v(g.current),l&&(m==null||m()),r&&r())};return e.jsx(s2,{isPresent:D,initial:!u.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:d,onExitComplete:D?void 0:T,anchorX:o,children:C},I)})})},hg=h.createContext({strict:!1}),Au={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"]},nn={};for(const t in Au)nn[t]={isEnabled:s=>Au[t].some(a=>!!s[a])};function r2(t){for(const s in t)nn[s]={...nn[s],...t[s]}}const n2=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 Vi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||n2.has(t)}let pg=t=>!Vi(t);function i2(t){typeof t=="function"&&(pg=s=>s.startsWith("on")?!Vi(s):t(s))}try{i2(require("@emotion/is-prop-valid").default)}catch{}function l2(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(pg(n)||a===!0&&Vi(n)||!s&&!Vi(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const ul=h.createContext({});function xl(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Hn(t){return typeof t=="string"||Array.isArray(t)}const Bc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Vc=["initial",...Bc];function hl(t){return xl(t.animate)||Vc.some(s=>Hn(t[s]))}function gg(t){return!!(hl(t)||t.variants)}function o2(t,s){if(hl(t)){const{initial:a,animate:r}=t;return{initial:a===!1||Hn(a)?a:void 0,animate:Hn(r)?r:void 0}}return t.inherit!==!1?s:{}}function c2(t){const{initial:s,animate:a}=o2(t,h.useContext(ul));return h.useMemo(()=>({initial:s,animate:a}),[Tu(s),Tu(a)])}function Tu(t){return Array.isArray(t)?t.join(" "):t}const Wn={};function d2(t){for(const s in t)Wn[s]=t[s],Ac(s)&&(Wn[s].isCSSVariable=!0)}function fg(t,{layout:s,layoutId:a}){return fn.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!Wn[t]||t==="opacity")}const m2={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},u2=gn.length;function x2(t,s,a){let r="",n=!0;for(let i=0;i({style:{},transform:{},transformOrigin:{},vars:{}});function bg(t,s,a){for(const r in s)!Ls(s[r])&&!fg(r,a)&&(t[r]=s[r])}function h2({transformTemplate:t},s){return h.useMemo(()=>{const a=Hc();return zc(a,s,t),Object.assign({},a.vars,a.style)},[s])}function p2(t,s){const a=t.style||{},r={};return bg(r,a,t),Object.assign(r,h2(t,s)),r}function g2(t,s){const a={},r=p2(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 f2={offset:"stroke-dashoffset",array:"stroke-dasharray"},b2={offset:"strokeDashoffset",array:"strokeDasharray"};function j2(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?f2:b2;t[i.offset]=it.transform(-r);const l=it.transform(s),o=it.transform(a);t[i.array]=`${l} ${o}`}function jg(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},d,c,m){if(zc(t,o,c),d){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&&j2(p,n,i,l,!1)}const yg=()=>({...Hc(),attrs:{}}),vg=t=>typeof t=="string"&&t.toLowerCase()==="svg";function y2(t,s,a,r){const n=h.useMemo(()=>{const i=yg();return jg(i,s,vg(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};bg(i,t.style,t),n.style={...i,...n.style}}return n}const v2=["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 Wc(t){return typeof t!="string"||t.includes("-")?!1:!!(v2.indexOf(t)>-1||/[A-Z]/u.test(t))}function N2(t,s,a,{latestValues:r},n,i=!1){const o=(Wc(t)?y2:g2)(s,r,n,t),d=l2(s,typeof t=="string",i),c=t!==h.Fragment?{...d,...o,ref:a}:{},{children:m}=s,p=h.useMemo(()=>Ls(m)?m.get():m,[m]);return h.createElement(t,{...c,children:p})}function ku(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function Gc(t,s,a,r){if(typeof s=="function"){const[n,i]=ku(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]=ku(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Ai(t){return Ls(t)?t.get():t}function w2({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:C2(a,r,n,t),renderState:s()}}function C2(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=Ai(i[x]);let{initial:l,animate:o}=t;const d=hl(t),c=gg(t);s&&c&&!d&&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"&&!xl(p)){const x=Array.isArray(p)?p:[p];for(let u=0;u(s,a)=>{const r=h.useContext(ul),n=h.useContext(dl),i=()=>w2(t,s,r,n);return a?i():fc(i)};function Yc(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(Ls(r[l])||s.style&&Ls(s.style[l])||fg(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const S2=Ng({scrapeMotionValuesFromProps:Yc,createRenderState:Hc});function wg(t,s,a){const r=Yc(t,s,a);for(const n in t)if(Ls(t[n])||Ls(s[n])){const i=gn.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const A2=Ng({scrapeMotionValuesFromProps:wg,createRenderState:yg}),T2=Symbol.for("motionComponentSymbol");function Yr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function k2(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):Yr(a)&&(a.current=r))},[s])}const Kc=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),R2="framerAppearId",Cg="data-"+Kc(R2),Sg=h.createContext({});function D2(t,s,a,r,n){var b,f;const{visualElement:i}=h.useContext(ul),l=h.useContext(hg),o=h.useContext(dl),d=h.useContext(Uc).reducedMotion,c=h.useRef(null);r=r||l.renderer,!c.current&&r&&(c.current=r(t,{visualState:s,parent:i,props:a,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:d}));const m=c.current,p=h.useContext(Sg);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&F2(c.current,a,n,p);const x=h.useRef(!1);h.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const u=a[Cg],g=h.useRef(!!u&&!((b=window.MotionHandoffIsComplete)!=null&&b.call(window,u))&&((f=window.MotionHasOptimisedAnimation)==null?void 0:f.call(window,u)));return Np(()=>{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 F2(t,s,a,r){const{layoutId:n,layout:i,drag:l,dragConstraints:o,layoutScroll:d,layoutRoot:c,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:Ag(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&Yr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:d,layoutRoot:c})}function Ag(t){if(t)return t.options.allowProjection!==!1?t.projection:Ag(t.parent)}function Ul(t,{forwardMotionProps:s=!1}={},a,r){a&&r2(a);const n=Wc(t)?A2:S2;function i(o,d){let c;const m={...h.useContext(Uc),...o,layoutId:P2(o)},{isStatic:p}=m,x=c2(o),u=n(o,p);if(!p&&bc){I2();const g=E2(m);c=g.MeasureLayout,x.visualElement=D2(t,u,m,r,g.ProjectionNode)}return e.jsxs(ul.Provider,{value:x,children:[c&&x.visualElement?e.jsx(c,{visualElement:x.visualElement,...m}):null,N2(t,o,k2(u,x.visualElement,d),u,p,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=h.forwardRef(i);return l[T2]=t,l}function P2({layoutId:t}){const s=h.useContext(gc).id;return s&&t!==void 0?s+"-"+t:t}function I2(t,s){h.useContext(hg).strict}function E2(t){const{drag:s,layout:a}=nn;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 _2(t,s){if(typeof Proxy>"u")return Ul;const a=new Map,r=(i,l)=>Ul(i,l,t,s),n=(i,l)=>r(i,l);return new Proxy(n,{get:(i,l)=>l==="create"?r:(a.has(l)||a.set(l,Ul(l,void 0,t,s)),a.get(l))})}function Tg({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function M2({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function L2(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 Bl(t){return t===void 0||t===1}function Po({scale:t,scaleX:s,scaleY:a}){return!Bl(t)||!Bl(s)||!Bl(a)}function Sr(t){return Po(t)||kg(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function kg(t){return Ru(t.x)||Ru(t.y)}function Ru(t){return t&&t!=="0%"}function zi(t,s,a){const r=t-a,n=s*r;return a+n}function Du(t,s,a,r,n){return n!==void 0&&(t=zi(t,n,r)),zi(t,a,r)+s}function Io(t,s=0,a=1,r,n){t.min=Du(t.min,s,a,r,n),t.max=Du(t.max,s,a,r,n)}function Rg(t,{x:s,y:a}){Io(t.x,s.translate,s.scale,s.originPoint),Io(t.y,a.translate,a.scale,a.originPoint)}const Fu=.999999999999,Pu=1.0000000000001;function O2(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,l;for(let o=0;oFu&&(s.x=1),s.yFu&&(s.y=1)}function Kr(t,s){t.min=t.min+s,t.max=t.max+s}function Iu(t,s,a,r,n=.5){const i=rs(t.min,t.max,n);Io(t,s,a,i,r)}function Qr(t,s){Iu(t.x,s.x,s.scaleX,s.scale,s.originX),Iu(t.y,s.y,s.scaleY,s.scale,s.originY)}function Dg(t,s){return Tg(L2(t.getBoundingClientRect(),s))}function $2(t,s,a){const r=Dg(t,a),{scroll:n}=s;return n&&(Kr(r.x,n.offset.x),Kr(r.y,n.offset.y)),r}const Eu=()=>({translate:0,scale:1,origin:0,originPoint:0}),Xr=()=>({x:Eu(),y:Eu()}),_u=()=>({min:0,max:0}),us=()=>({x:_u(),y:_u()}),Eo={current:null},Fg={current:!1};function U2(){if(Fg.current=!0,!!bc)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>Eo.current=t.matches;t.addEventListener("change",s),s()}else Eo.current=!1}const B2=new WeakMap;function V2(t,s,a){for(const r in s){const n=s[r],i=a[r];if(Ls(n))t.addValue(r,n);else if(Ls(i))t.addValue(r,rn(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,rn(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Mu=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class z2{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=_c,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=Js.now();this.renderScheduledAtthis.bindToMotionValue(n,r)),Fg.current||U2(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Eo.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),cr(this.notifyUpdate),cr(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=fn.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&qt.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 nn){const a=nn[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):us()}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=rn(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"&&(wp(r)||Sp(r))?r=parseFloat(r):!JC(r)&&dr.test(a)&&(r=ig(s,a)),this.setBaseTarget(s,Ls(r)?r.get():r)),Ls(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=Gc(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&&!Ls(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 wc),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){Oc.render(this.render)}}class Pg extends z2{constructor(){super(...arguments),this.KeyframeResolver=$C}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;Ls(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function Ig(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 H2(t){return window.getComputedStyle(t)}class W2 extends Pg{constructor(){super(...arguments),this.type="html",this.renderInstance=Ig}readValueFromInstance(s,a){var r;if(fn.has(a))return(r=this.projection)!=null&&r.isProjecting?So(a):rC(s,a);{const n=H2(s),i=(Ac(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return Dg(s,a)}build(s,a,r){zc(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return Yc(s,a,r)}}const Eg=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 G2(t,s,a,r){Ig(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(Eg.has(n)?n:Kc(n),s.attrs[n])}class Y2 extends Pg{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=us}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(fn.has(a)){const r=ng(a);return r&&r.default||0}return a=Eg.has(a)?a:Kc(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return wg(s,a,r)}build(s,a,r){jg(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){G2(s,a,r,n)}mount(s){this.isSVGTag=vg(s.tagName),super.mount(s)}}const K2=(t,s)=>Wc(t)?new Y2(s):new W2(s,{allowProjection:t!==h.Fragment});function sn(t,s,a){const r=t.getProps();return Gc(r,s,a!==void 0?a:r.custom,t)}const _o=t=>Array.isArray(t);function Q2(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,rn(a))}function X2(t){return _o(t)?t[t.length-1]||0:t}function J2(t,s){const a=sn(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=X2(i[l]);Q2(t,l,o)}}function Z2(t){return!!(Ls(t)&&t.add)}function Mo(t,s){const a=t.getValue("willChange");if(Z2(a))return a.add(s);if(!a&&Ka.WillChange){const r=new Ka.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function _g(t){return t.props[Cg]}const q2=t=>t!==null;function eS(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(q2),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const tS={type:"spring",stiffness:500,damping:25,restSpeed:10},sS=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),aS={type:"keyframes",duration:.8},rS={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},nS=(t,{keyframes:s})=>s.length>2?aS:fn.has(t)?t.startsWith("scale")?sS(s[1]):tS:rS;function iS({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:l,repeatDelay:o,from:d,elapsed:c,...m}){return!!Object.keys(m).length}const Qc=(t,s,a,r={},n,i)=>l=>{const o=Mc(r,t)||{},d=o.delay||r.delay||0;let{elapsed:c=0}=r;c=c-Ia(d);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-c,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};iS(o)||Object.assign(m,nS(t,m)),m.duration&&(m.duration=Ia(m.duration)),m.repeatDelay&&(m.repeatDelay=Ia(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let p=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(Do(m),m.delay===0&&(p=!0)),(Ka.instantAnimations||Ka.skipAnimations)&&(p=!0,Do(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,p&&!i&&s.get()!==void 0){const x=eS(m.keyframes,o);if(x!==void 0){qt.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new Ec(m):new TC(m)};function lS({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Mg(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const d=[],c=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||c&&lS(c,m))continue;const u={delay:a,...Mc(i||{},m)},g=p.get();if(g!==void 0&&!p.isAnimating&&!Array.isArray(x)&&x===g&&!u.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const j=_g(t);if(j){const y=window.MotionHandoffAnimation(j,m,qt);y!==null&&(u.startTime=y,b=!0)}}Mo(t,m),p.start(Qc(m,p,x,t.shouldReduceMotion&&sg.has(m)?{type:!1}:u,t,b));const f=p.animation;f&&d.push(f)}return l&&Promise.all(d).then(()=>{qt.update(()=>{l&&J2(t,l)})}),d}function Lg(t,s,a,r=0,n=1){const i=Array.from(t).sort((c,m)=>c.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 Lo(t,s,a={}){var d;const r=sn(t,s,a.type==="exit"?(d=t.presenceContext)==null?void 0:d.custom:void 0);let{transition:n=t.getDefaultTransition()||{}}=r||{};a.transitionOverride&&(n=a.transitionOverride);const i=r?()=>Promise.all(Mg(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:m=0,staggerChildren:p,staggerDirection:x}=n;return oS(t,s,c,m,p,x,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[c,m]=o==="beforeChildren"?[i,l]:[l,i];return c().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function oS(t,s,a=0,r=0,n=0,i=1,l){const o=[];for(const d of t.variantChildren)d.notify("AnimationStart",s),o.push(Lo(d,s,{...l,delay:a+(typeof r=="function"?0:r)+Lg(t.variantChildren,d,r,n,i)}).then(()=>d.notify("AnimationComplete",s)));return Promise.all(o)}function cS(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>Lo(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=Lo(t,s,a);else{const n=typeof s=="function"?sn(t,s,a.custom):s;r=Promise.all(Mg(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function Og(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})=>cS(t,a,r)))}function hS(t){let s=xS(t),a=Lu(),r=!0;const n=d=>(c,m)=>{var x;const p=sn(t,m,d==="exit"?(x=t.presenceContext)==null?void 0:x.custom:void 0);if(p){const{transition:u,transitionEnd:g,...b}=p;c={...c,...b,...g}}return c};function i(d){s=d(t)}function l(d){const{props:c}=t,m=$g(t.parent)||{},p=[],x=new Set;let u={},g=1/0;for(let f=0;fg&&w,T=!1;const N=Array.isArray(v)?v:[v];let _=N.reduce(n(j),{});S===!1&&(_={});const{prevResolvedValues:A={}}=y,z={...A,..._},F=k=>{D=!0,x.has(k)&&(T=!0,x.delete(k)),y.needsAnimating[k]=!0;const R=t.getValue(k);R&&(R.liveStyle=!1)};for(const k in z){const R=_[k],V=A[k];if(u.hasOwnProperty(k))continue;let M=!1;_o(R)&&_o(V)?M=!Og(R,V):M=R!==V,M?R!=null?F(k):x.add(k):R!==void 0&&x.has(k)?F(k):y.protectedKeys[k]=!0}y.prevProp=v,y.prevResolvedValues=_,y.isActive&&(u={...u,..._}),r&&t.blockInitialAnimation&&(D=!1);const O=C&&I;D&&(!O||T)&&p.push(...N.map(k=>{const R={type:j};if(typeof k=="string"&&r&&!O&&t.manuallyAnimateOnMount&&t.parent){const{parent:V}=t,M=sn(V,k);if(V.enteringChildren&&M){const{delayChildren:L}=M.transition||{};R.delay=Lg(V.enteringChildren,t,L)}}return{animation:k,options:R}}))}if(x.size){const f={};if(typeof c.initial!="boolean"){const j=sn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);j&&j.transition&&(f.transition=j.transition)}x.forEach(j=>{const y=t.getBaseTarget(j),v=t.getValue(j);v&&(v.liveStyle=!0),f[j]=y??null}),p.push({animation:f})}let b=!!p.length;return r&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(b=!1),r=!1,b?s(p):Promise.resolve()}function o(d,c){var p;if(a[d].isActive===c)return Promise.resolve();(p=t.variantChildren)==null||p.forEach(x=>{var u;return(u=x.animationState)==null?void 0:u.setActive(d,c)}),a[d].isActive=c;const m=l(d);for(const x in a)a[x].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=Lu()}}}function pS(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!Og(s,t):!1}function vr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Lu(){return{animate:vr(!0),whileInView:vr(),whileHover:vr(),whileTap:vr(),whileDrag:vr(),whileFocus:vr(),exit:vr()}}class mr{constructor(s){this.isMounted=!1,this.node=s}update(){}}class gS extends mr{constructor(s){super(s),s.animationState||(s.animationState=hS(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();xl(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 fS=0;class bS extends mr{constructor(){super(...arguments),this.id=fS++}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 jS={animation:{Feature:gS},exit:{Feature:bS}};function Gn(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function ri(t){return{point:{x:t.pageX,y:t.pageY}}}const yS=t=>s=>$c(s)&&t(s,ri(s));function Mn(t,s,a,r){return Gn(t,s,yS(a),r)}const Ug=1e-4,vS=1-Ug,NS=1+Ug,Bg=.01,wS=0-Bg,CS=0+Bg;function Bs(t){return t.max-t.min}function SS(t,s,a){return Math.abs(t-s)<=a}function Ou(t,s,a,r=.5){t.origin=r,t.originPoint=rs(s.min,s.max,t.origin),t.scale=Bs(a)/Bs(s),t.translate=rs(a.min,a.max,t.origin)-t.originPoint,(t.scale>=vS&&t.scale<=NS||isNaN(t.scale))&&(t.scale=1),(t.translate>=wS&&t.translate<=CS||isNaN(t.translate))&&(t.translate=0)}function Ln(t,s,a,r){Ou(t.x,s.x,a.x,r?r.originX:void 0),Ou(t.y,s.y,a.y,r?r.originY:void 0)}function $u(t,s,a){t.min=a.min+s.min,t.max=t.min+Bs(s)}function AS(t,s,a){$u(t.x,s.x,a.x),$u(t.y,s.y,a.y)}function Uu(t,s,a){t.min=s.min-a.min,t.max=t.min+Bs(s)}function On(t,s,a){Uu(t.x,s.x,a.x),Uu(t.y,s.y,a.y)}function pa(t){return[t("x"),t("y")]}const Vg=({current:t})=>t?t.ownerDocument.defaultView:null,Bu=(t,s)=>Math.abs(t-s);function TS(t,s){const a=Bu(t.x,s.x),r=Bu(t.y,s.y);return Math.sqrt(a**2+r**2)}class zg{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=zl(this.lastMoveEventInfo,this.history),u=this.startEvent!==null,g=TS(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!u&&!g)return;const{point:b}=x,{timestamp:f}=Fs;this.history.push({...b,timestamp:f});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=Vl(u,this.transformPagePoint),qt.update(this.updatePoint,!0)},this.handlePointerUp=(x,u)=>{this.end();const{onEnd:g,onSessionEnd:b,resumeAnimation:f}=this.handlers;if(this.dragSnapToOrigin&&f&&f(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const j=zl(x.type==="pointercancel"?this.lastMoveEventInfo:Vl(u,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,j),b&&b(x,j)},!$c(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=ri(s),d=Vl(o,this.transformPagePoint),{point:c}=d,{timestamp:m}=Fs;this.history=[{...c,timestamp:m}];const{onSessionStart:p}=a;p&&p(s,zl(d,this.history)),this.removeListeners=ti(Mn(this.contextWindow,"pointermove",this.handlePointerMove),Mn(this.contextWindow,"pointerup",this.handlePointerUp),Mn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),cr(this.updatePoint)}}function Vl(t,s){return s?{point:s(t.point)}:t}function Vu(t,s){return{x:t.x-s.x,y:t.y-s.y}}function zl({point:t},s){return{point:t,delta:Vu(t,Hg(s)),offset:Vu(t,kS(s)),velocity:RS(s,.1)}}function kS(t){return t[0]}function Hg(t){return t[t.length-1]}function RS(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=Hg(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>Ia(s)));)a--;if(!r)return{x:0,y:0};const i=ga(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 DS(t,{min:s,max:a},r){return s!==void 0&&ta&&(t=r?rs(a,t,r.max):Math.min(t,a)),t}function zu(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 FS(t,{top:s,left:a,bottom:r,right:n}){return{x:zu(t.x,a,n),y:zu(t.y,s,r)}}function Hu(t,s){let a=s.min-t.min,r=s.max-t.max;return s.max-s.minr?a=Bn(s.min,s.max-r,t.min):r>n&&(a=Bn(t.min,t.max-n,s.min)),Ya(0,1,a)}function ES(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 Oo=.35;function _S(t=Oo){return t===!1?t=0:t===!0&&(t=Oo),{x:Wu(t,"left","right"),y:Wu(t,"top","bottom")}}function Wu(t,s,a){return{min:Gu(t,s),max:Gu(t,a)}}function Gu(t,s){return typeof t=="number"?t:t[s]||0}const MS=new WeakMap;class LS{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=us(),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(ri(p).point)},l=(p,x)=>{const{drag:u,dragPropagation:g,onDragStart:b}=this.getProps();if(u&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=zC(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),pa(j=>{let y=this.getAxisMotionValue(j).get()||0;if(Ea.test(y)){const{projection:v}=this.visualElement;if(v&&v.layout){const w=v.layout.layoutBox[j];w&&(y=Bs(w)*(parseFloat(y)/100))}}this.originPoint[j]=y}),b&&qt.postRender(()=>b(p,x)),Mo(this.visualElement,"transform");const{animationState:f}=this.visualElement;f&&f.setActive("whileDrag",!0)},o=(p,x)=>{this.latestPointerEvent=p,this.latestPanInfo=x;const{dragPropagation:u,dragDirectionLock:g,onDirectionLock:b,onDrag:f}=this.getProps();if(!u&&!this.openDragLock)return;const{offset:j}=x;if(g&&this.currentDirection===null){this.currentDirection=OS(j),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",x.point,j),this.updateAxis("y",x.point,j),this.visualElement.render(),f&&f(p,x)},d=(p,x)=>{this.latestPointerEvent=p,this.latestPanInfo=x,this.stop(p,x),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>pa(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 zg(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:d,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:Vg(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&&qt.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||!xi(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=DS(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&&Yr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=FS(r.layoutBox,s):this.constraints=!1,this.elastic=_S(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&pa(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=ES(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!Yr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=$2(r,n.root,this.visualElement.getTransformPagePoint());let l=PS(n.layout.layoutBox,i);if(a){const o=a(M2(l));this.hasMutatedConstraints=!!o,o&&(l=Tg(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),d=this.constraints||{},c=pa(m=>{if(!xi(m,a,this.currentDirection))return;let p=d&&d[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(c).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return Mo(this.visualElement,s),r.start(Qc(s,r,0,a,this.visualElement,!1))}stopAnimation(){pa(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){pa(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){pa(a=>{const{drag:r}=this.getProps();if(!xi(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]-rs(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!Yr(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};pa(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const d=o.get();n[l]=IS({min:d,max:d},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(),pa(l=>{if(!xi(l,s,null))return;const o=this.getAxisMotionValue(l),{min:d,max:c}=this.constraints[l];o.set(rs(d,c,n[l]))})}addListeners(){if(!this.visualElement.current)return;MS.set(this.visualElement,this);const s=this.visualElement.current,a=Mn(s,"pointerdown",d=>{const{drag:c,dragListener:m=!0}=this.getProps();c&&m&&this.start(d)}),r=()=>{const{dragConstraints:d}=this.getProps();Yr(d)&&d.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,i=n.addEventListener("measure",r);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),qt.read(r);const l=Gn(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:d,hasLayoutChanged:c})=>{this.isDragging&&c&&(pa(m=>{const p=this.getAxisMotionValue(m);p&&(this.originPoint[m]+=d[m].translate,p.set(p.get()+d[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=Oo,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function xi(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function OS(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class $S extends mr{constructor(s){super(s),this.removeGroupControls=fa,this.removeListeners=fa,this.controls=new LS(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||fa}unmount(){this.removeGroupControls(),this.removeListeners()}}const Yu=t=>(s,a)=>{t&&qt.postRender(()=>t(s,a))};class US extends mr{constructor(){super(...arguments),this.removePointerDownListener=fa}onPointerDown(s){this.session=new zg(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Vg(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Yu(s),onStart:Yu(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&qt.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=Mn(this.node.current,"pointerdown",s=>this.onPointerDown(s))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const Ti={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ku(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const Cn={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(it.test(t))t=parseFloat(t);else return t;const a=Ku(t,s.target.x),r=Ku(t,s.target.y);return`${a}% ${r}%`}},BS={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=dr.parse(t);if(n.length>5)return r;const i=dr.createTransformer(t),l=typeof n[0]!="number"?1:0,o=a.x.scale*s.x,d=a.y.scale*s.y;n[0+l]/=o,n[1+l]/=d;const c=rs(o,d,.5);return typeof n[2+l]=="number"&&(n[2+l]/=c),typeof n[3+l]=="number"&&(n[3+l]/=c),i(n)}};let Hl=!1;class VS extends h.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;d2(zS),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),Hl&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Ti.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,Hl=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||qt.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Oc.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;Hl=!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 Wg(t){const[s,a]=xg(),r=h.useContext(gc);return e.jsx(VS,{...t,layoutGroup:r,switchLayoutGroup:h.useContext(Sg),isPresent:s,safeToRemove:a})}const zS={borderRadius:{...Cn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Cn,borderTopRightRadius:Cn,borderBottomLeftRadius:Cn,borderBottomRightRadius:Cn,boxShadow:BS};function HS(t,s,a){const r=Ls(t)?t:rn(t);return r.start(Qc("",r,s,a)),r.animation}const WS=(t,s)=>t.depth-s.depth;class GS{constructor(){this.children=[],this.isDirty=!1}add(s){jc(this.children,s),this.isDirty=!0}remove(s){yc(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(WS),this.isDirty=!1,this.children.forEach(s)}}function YS(t,s){const a=Js.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(cr(r),t(i-s))};return qt.setup(r,!0),()=>cr(r)}const Gg=["TopLeft","TopRight","BottomLeft","BottomRight"],KS=Gg.length,Qu=t=>typeof t=="string"?parseFloat(t):t,Xu=t=>typeof t=="number"||it.test(t);function QS(t,s,a,r,n,i){n?(t.opacity=rs(0,a.opacity??1,XS(r)),t.opacityExit=rs(s.opacity??1,0,JS(r))):i&&(t.opacity=rs(s.opacity??1,a.opacity??1,r));for(let l=0;lrs?1:a(Bn(t,s,r))}function Zu(t,s){t.min=s.min,t.max=s.max}function ha(t,s){Zu(t.x,s.x),Zu(t.y,s.y)}function qu(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function ex(t,s,a,r,n){return t-=s,t=zi(t,1/a,r),n!==void 0&&(t=zi(t,1/n,r)),t}function ZS(t,s=0,a=1,r=.5,n,i=t,l=t){if(Ea.test(s)&&(s=parseFloat(s),s=rs(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=rs(i.min,i.max,r);t===i&&(o-=s),t.min=ex(t.min,s,a,o,n),t.max=ex(t.max,s,a,o,n)}function tx(t,s,[a,r,n],i,l){ZS(t,s[a],s[r],s[n],s.scale,i,l)}const qS=["x","scaleX","originX"],eA=["y","scaleY","originY"];function sx(t,s,a,r){tx(t.x,s,qS,a?a.x:void 0,r?r.x:void 0),tx(t.y,s,eA,a?a.y:void 0,r?r.y:void 0)}function ax(t){return t.translate===0&&t.scale===1}function Kg(t){return ax(t.x)&&ax(t.y)}function rx(t,s){return t.min===s.min&&t.max===s.max}function tA(t,s){return rx(t.x,s.x)&&rx(t.y,s.y)}function nx(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function Qg(t,s){return nx(t.x,s.x)&&nx(t.y,s.y)}function ix(t){return Bs(t.x)/Bs(t.y)}function lx(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class sA{constructor(){this.members=[]}add(s){jc(this.members,s),s.scheduleRender()}remove(s){if(yc(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 aA(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:c,rotate:m,rotateX:p,rotateY:x,skewX:u,skewY:g}=a;c&&(r=`perspective(${c}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,d=t.y.scale*s.y;return(o!==1||d!==1)&&(r+=`scale(${o}, ${d})`),r||"none"}const Wl=["","X","Y","Z"],rA=1e3;let nA=0;function Gl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Xg(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=_g(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",qt,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Xg(r)}function Jg({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=nA++,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(oA),this.nodes.forEach(uA),this.nodes.forEach(xA),this.nodes.forEach(cA)},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 d=0;dthis.root.updateBlockedByResize=!1;qt.read(()=>{p=window.innerWidth}),t(l,()=>{const u=window.innerWidth;u!==p&&(p=u,this.root.updateBlockedByResize=!0,m&&m(),m=YS(x,250),Ti.hasAnimatedSinceResize&&(Ti.hasAnimatedSinceResize=!1,this.nodes.forEach(dx)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&c&&(o||d)&&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||c.getDefaultTransition()||bA,{onLayoutAnimationStart:b,onLayoutAnimationComplete:f}=c.getProps(),j=!this.targetLayout||!Qg(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 v={...Mc(g,"layout"),onPlay:b,onComplete:f};(c.shouldReduceMotion||this.options.layoutRoot)&&(v.delay=0,v.type=!1),this.startAnimation(v),this.setAnimationOrigin(m,y)}else p||dx(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(),cr(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(hA),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&&Xg(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&&!Bs(this.snapshot.measuredBox.x)&&!Bs(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 d=0;d{const S=w/1e3;mx(p.x,l.x,S),mx(p.y,l.y,S),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(On(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),gA(this.relativeTarget,this.relativeTargetOrigin,x,S),v&&tA(this.relativeTarget,v)&&(this.isProjectionDirty=!1),v||(v=us()),ha(v,this.relativeTarget)),b&&(this.animationValues=m,QS(m,c,this.latestValues,S,y,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=S},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,d,c;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(c=(d=this.resumingFrom)==null?void 0:d.currentAnimation)==null||c.stop(),this.pendingAnimation&&(cr(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=qt.update(()=>{Ti.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=rn(0)),this.currentAnimation=HS(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(rA),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:d,layout:c,latestValues:m}=l;if(!(!o||!d||!c)){if(this!==l&&this.layout&&c&&Zg(this.options.animationType,this.layout.layoutBox,c.layoutBox)){d=this.target||us();const p=Bs(this.layout.layoutBox.x);d.x.min=l.target.x.min,d.x.max=d.x.min+p;const x=Bs(this.layout.layoutBox.y);d.y.min=l.target.y.min,d.y.max=d.y.min+x}ha(o,d),Qr(o,m),Ln(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new sA),this.sharedNodes.get(l).add(o);const c=o.options.initialPromotionConfig;o.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.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:d}={}){const c=this.getStack();c&&c.promote(this,d),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:d}=l;if((d.z||d.rotate||d.rotateX||d.rotateY||d.rotateZ||d.skewX||d.skewY)&&(o=!0),!o)return;const c={};d.z&&Gl("z",l,c,this.animationValues);for(let m=0;m{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(ox),this.root.sharedNodes.clear()}}}function iA(t){t.updateLayout()}function lA(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"?pa(p=>{const x=l?s.measuredBox[p]:s.layoutBox[p],u=Bs(x);x.min=r[p].min,x.max=x.min+u}):Zg(i,s.layoutBox,r)&&pa(p=>{const x=l?s.measuredBox[p]:s.layoutBox[p],u=Bs(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=Xr();Ln(o,r,s.layoutBox);const d=Xr();l?Ln(d,t.applyTransform(n,!0),s.measuredBox):Ln(d,r,s.layoutBox);const c=!Kg(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=us();On(g,s.layoutBox,x.layoutBox);const b=us();On(b,r,u.layoutBox),Qg(g,b)||(m=!0),p.options.layoutRoot&&(t.relativeTarget=b,t.relativeTargetOrigin=g,t.relativeParent=p)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:d,layoutDelta:o,hasLayoutChanged:c,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function oA(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 cA(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function dA(t){t.clearSnapshot()}function ox(t){t.clearMeasurements()}function cx(t){t.isLayoutDirty=!1}function mA(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function dx(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function uA(t){t.resolveTargetDelta()}function xA(t){t.calcProjection()}function hA(t){t.resetSkewAndRotation()}function pA(t){t.removeLeadSnapshot()}function mx(t,s,a){t.translate=rs(s.translate,0,a),t.scale=rs(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function ux(t,s,a,r){t.min=rs(s.min,a.min,r),t.max=rs(s.max,a.max,r)}function gA(t,s,a,r){ux(t.x,s.x,a.x,r),ux(t.y,s.y,a.y,r)}function fA(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const bA={duration:.45,ease:[.4,0,.1,1]},xx=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),hx=xx("applewebkit/")&&!xx("chrome/")?Math.round:fa;function px(t){t.min=hx(t.min),t.max=hx(t.max)}function jA(t){px(t.x),px(t.y)}function Zg(t,s,a){return t==="position"||t==="preserve-aspect"&&!SS(ix(s),ix(a),.2)}function yA(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const vA=Jg({attachResizeListener:(t,s)=>Gn(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Yl={current:void 0},qg=Jg({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Yl.current){const t=new vA({});t.mount(window),t.setOptions({layoutScroll:!0}),Yl.current=t}return Yl.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),NA={pan:{Feature:US},drag:{Feature:$S,ProjectionNode:qg,MeasureLayout:Wg}};function gx(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&&qt.postRender(()=>i(s,ri(s)))}class wA extends mr{mount(){const{current:s}=this.node;s&&(this.unmount=HC(s,(a,r)=>(gx(this.node,r,"Start"),n=>gx(this.node,n,"End"))))}unmount(){}}class CA extends mr{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=ti(Gn(this.node.current,"focus",()=>this.onFocus()),Gn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function fx(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&&qt.postRender(()=>i(s,ri(s)))}class SA extends mr{mount(){const{current:s}=this.node;s&&(this.unmount=KC(s,(a,r)=>(fx(this.node,r,"Start"),(n,{success:i})=>fx(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const $o=new WeakMap,Kl=new WeakMap,AA=t=>{const s=$o.get(t.target);s&&s(t)},TA=t=>{t.forEach(AA)};function kA({root:t,...s}){const a=t||document;Kl.has(a)||Kl.set(a,{});const r=Kl.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(TA,{root:t,...s})),r[n]}function RA(t,s,a){const r=kA(s);return $o.set(t,a),r.observe(t),()=>{$o.delete(t),r.unobserve(t)}}const DA={some:0,all:1};class FA extends mr{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:DA[n]},o=d=>{const{isIntersecting:c}=d;if(this.isInView===c||(this.isInView=c,i&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:m,onViewportLeave:p}=this.node.getProps(),x=c?m:p;x&&x(d)};return RA(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(PA(s,a))&&this.startObserver()}unmount(){}}function PA({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const IA={inView:{Feature:FA},tap:{Feature:SA},focus:{Feature:CA},hover:{Feature:wA}},EA={layout:{ProjectionNode:qg,MeasureLayout:Wg}},_A={...jS,...IA,...NA,...EA},Wt=_2(_A,K2),Sn=[{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:mh,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 MA({open:t,onClose:s,onSelectTemplate:a}){var c,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=Sn.find(g=>g.id===x);u!=null&&u.disabled||n(x)},d=()=>{r&&(a(r),s())};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(ut,{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(xt,{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(ws,{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(Wt.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(Ji,{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:Sn.map((x,u)=>{const g=x.icon,b=r===x.id,f=i||x.disabled;return e.jsx(Wt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:u*.1},whileHover:f?{}:{scale:1.03},whileTap:f?{}:{scale:.98},children:e.jsxs(Z,{className:`h-full transition-all duration-300 border-2 ${f?"opacity-50 cursor-not-allowed border-gray-200":b?"cursor-pointer border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"cursor-pointer border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>o(x.id),children:[e.jsxs(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"})}),b&&e.jsx(Wt.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(Wa,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(ce,{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(te,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(re,{variant:"secondary",className:"text-xs",children:x.category})}),e.jsx(Jt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(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(es,{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($e,{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(Wt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"flex flex-col sm:flex-row justify-center gap-4 mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(E,{onClick:d,disabled:!r||i||((c=Sn.find(x=>x.id===r))==null?void 0:c.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=Sn.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(ml,{children:r&&e.jsx(Wt.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=Sn.find(x=>x.id===r))==null?void 0:p.name})]})})})]})})]})})}function Or({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[d,c]=h.useState(100),[m,p]=h.useState(0),[x,u]=h.useState(null),[g,b]=h.useState(!1),[f,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"),v=s.toLowerCase().includes("pdf"),w=y||v;h.useEffect(()=>{if(!l||!w||!a){u(null);return}return(async()=>{b(!0),j(null);try{let A=a;a.startsWith("/")&&!a.startsWith("//")&&(A=`${window.location.origin}${a}`);const F=await fetch(A,{headers:{Accept:v?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!F.ok){const k=await F.text().catch(()=>"");throw new Error(`Failed to load file: ${F.status} ${F.statusText}. ${k}`)}const O=await F.blob();if(O.size===0)throw new Error("File is empty or could not be loaded");v&&!O.type.includes("pdf")&&O.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${O.type}`);const P=window.URL.createObjectURL(O);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{b(!1)}})(),()=>{x&&(window.URL.revokeObjectURL(x),u(null))}},[l,a,w,v]);const S=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},C=()=>c(T=>Math.min(T+25,200)),I=()=>c(T=>Math.max(T-25,50)),D=()=>p(T=>(T+90)%360);return e.jsx(pt,{open:l,onOpenChange:o,children:e.jsx(ut,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(gt,{className:"pb-4 flex-shrink-0 pr-8",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(Nt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(xt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`• ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[y&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:I,disabled:d<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(Tb,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[d,"%"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:C,disabled:d>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(kb,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:D,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(uh,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(E,{variant:"outline",size:"sm",onClick:S,className:"gap-2 h-9",children:[e.jsx(At,{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(Ke,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):f?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(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:f}),i&&n&&e.jsxs(E,{onClick:S,className:"gap-2",children:[e.jsx(At,{className:"h-4 w-4"}),"Download ",t]})]}):w&&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(${d/100}) rotate(${m}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),v&&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(Nt,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),i&&n&&e.jsxs(E,{onClick:S,className:"gap-2",children:[e.jsx(At,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function ni({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(ut,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(xt,{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(It,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const ma=async t=>{const s=t?{category:t}:{};return(await be.get("/users/configurations",{params:s})).data.data},pl=async t=>{const s=t?{category:t}:{};return(await be.get("/admin/configurations",{params:s})).data.data},Us=async(t,s)=>{await be.put(`/admin/configurations/${t}`,{configValue:s})},LA=async t=>{await be.post(`/admin/configurations/${t}/reset`)},OA=async()=>{const t=await be.get("/admin/form16-config");return t.data.data??t.data},$A=async t=>{await be.put("/admin/form16-config",t)},UA=async t=>{const s=t?{year:t}:{};return(await be.get("/admin/holidays",{params:s})).data.data},BA=async t=>(await be.post("/admin/holidays",t)).data.data,VA=async(t,s)=>(await be.put(`/admin/holidays/${t}`,s)).data.data,zA=async t=>{await be.delete(`/admin/holidays/${t}`)},HA=async()=>(await be.get("/config/activity-types")).data.data,WA=async t=>{const s={activeOnly:t.toString()};return(await be.get("/admin/activity-types",{params:s})).data.data},GA=async t=>(await be.post("/admin/activity-types",t)).data.data,YA=async(t,s)=>(await be.put(`/admin/activity-types/${t}`,s)).data.data,KA=async t=>{await be.delete(`/admin/activity-types/${t}`)},QA={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 XA(t,s,a){const[r,n]=h.useState(QA),[i,l]=h.useState(null),[o,d]=h.useState(t),[c,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 ma("DOCUMENT_POLICY"),v={};y.forEach(_=>{v[_.configKey]=_.configValue});const w=parseInt(v.MAX_FILE_SIZE_MB||"10"),C=(v.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(_=>_.trim().toLowerCase());x({maxFileSizeMB:w,allowedFileTypes:C});const I=await ma("SYSTEM_SETTINGS"),D=await ma("WORKFLOW_SHARING"),T=[...I,...D],N={};T.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 f=!0;return(async()=>{try{d(!0);const j=await Ps(s);if(!f||!j)return;const y=j.workflow||{},v=Array.isArray(j.approvals)?j.approvals:[],w=Array.isArray(j.participants)?j.participants:[],S=Array.isArray(j.documents)?j.documents.filter(A=>!A.isDeleted):[];g(S);const C=(y.priority||"").toString().toLowerCase(),I={standard:"standard",express:"express"},D=y.templateType==="TEMPLATE"?"existing-template":"custom",T=a.find(A=>A.id===D)||a[0]||null;l(T);const N=v.sort((A,z)=>(A.levelNumber||0)-(z.levelNumber||0)).map(A=>{const z=Number(A.tatHours||24),F=Math.floor(z/24),O=z%24;return{id:A.approverId||`temp-${A.levelNumber}`,name:A.approverName||A.approverEmail||"",email:A.approverEmail||"",role:A.levelName||`Level ${A.levelNumber}`,department:"",avatar:(A.approverName||A.approverEmail||"XX").substring(0,2).toUpperCase(),level:A.levelNumber||1,canClose:!1,tat:F>0?F:O,tatType:F>0?"days":"hours",userId:A.approverId}}),_=w.filter(A=>(A.participantType||A.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(A.userEmail||A.user_email||A.email):!1).map((A,z)=>{const F=A.userId||A.user_id||A.id,O=A.userName||A.user_name||A.name||"",P=A.userEmail||A.user_email||A.email||"",R=(O||P||"XX").split(" ").map(V=>V[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:F||`spectator-${s}-${z}-${Date.now()}`,userId:F,name:O||P||"Spectator",email:P,role:"Spectator",department:A.department||"",avatar:R,level:1,canClose:!1}});n(A=>({...A,template:D,title:y.title||"",description:y.description||"",priority:I[C]||"standard",approvers:N,approverCount:N.length||1,spectators:_,maxLevel:Math.max(...N.map(z=>z.level||1),1)}))}catch(j){console.error("Failed to load draft:",j)}finally{f&&d(!1)}})(),()=>{f=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(f,j)=>{n(y=>({...y,[f]:j}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:c,documentPolicy:p,existingDocuments:u,setExistingDocuments:g}}const bx=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function JA(t,s,a){const[r,n]=h.useState(t?2:1),i=bx.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:bx,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 ZA(){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 qA(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function eT(t,s,a){var n;const r=qA(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 tT(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return eT(a,n,n===s)})}function jx(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 yx(t,s,a,r=!1){const n=tT(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 sT(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 vx(t,s){return{id:(await hc(t,s||[],"SUPPORTING")).id}}async function Nx(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await $w(t,s,a||[],r):await Ow(t,s)}function aT({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[d,c]=h.useState(!1),[m,p]=h.useState(!1);return{submitting:d,savingDraft:m,handleSubmit:async()=>{var b,f;if(d||m)return;const g=sT(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}c(!0);try{if(i&&l){const j=yx(t,n,r,!1);await Nx(l,j,a,r),G.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=jx(t,s,n,!1),y=await vx(j,a);G.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),G.error("Failed to Submit Request",{description:((f=(b=j==null?void 0:j.response)==null?void 0:b.data)==null?void 0:f.message)||(j==null?void 0:j.message)||"An error occurred while submitting the request.",duration:5e3}),c(!1)}},handleSaveDraft:async()=>{var g,b;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(d||m)){p(!0);try{if(i&&l){const f=yx(t,n,r,!0);await Nx(l,f,a,r),G.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const f=jx(t,s,n,!0),j=await vx(f,a);G.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(f){console.error("Failed to save draft:",f),G.error("Failed to Save Draft",{description:((b=(g=f==null?void 0:f.response)==null?void 0:g.data)==null?void 0:b.message)||(f==null?void 0:f.message)||"An error occurred while saving the draft.",duration:5e3}),p(!1)}}}}}async function ya(t,s=10,a="default"){return await be.get("/users/search",{params:{q:t,limit:s,source:a}})}async function ba(t){var a;const s=await be.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function rT(t,s){return await be.post("/admin/users/assign-role",{email:t,role:s})}async function nT(t,s){return await be.put(`/admin/users/${t}/role`,{role:s})}async function iT(t,s=1,a=10){return await be.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function lT(){return await be.get("/admin/users/role-statistics")}async function oT(t){var a;const s=await be.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function cT(){var s,a;return((a=(s=(await be.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const ia={searchUsers:ya,getUserById:oT,ensureUserExists:ba,assignRole:rT,updateUserRole:nT,getUsersByRole:iT,getRoleStatistics:lT,getAllUsers:cT};async function dT(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 ya(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 ba({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 mT(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 T=new Date;T.setDate(T.getDate()+D.suggestedSLA),a("slaEndDate",T),D.id!=="custom"&&D.id!=="existing-template"&&u(`/create-admin-request/${D.id}`)},handleTemplateSelection:D=>{D==="claim-management"?u("/claim-management"):D==="vendor-payment"?u("/vendor-payment"):x&&x({templateType:D})},nextStep:async()=>{var D;if(i()){if(n===1&&(t==null?void 0:t.id)==="existing-template"){b(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&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 T=((D=d==null?void 0:d.email)==null?void 0:D.toLowerCase())||"",N=await mT(r.approvers,T);if(!N.success&&N.error){c(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,T)=>{if(T){const N=D.documentId||D.document_id||"";j({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:hn(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:()=>{f!=null&&f.fileUrl&&(f!=null&&f.file)&&URL.revokeObjectURL(f.fileUrl),j(null)}}}const wx=[{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:Zi,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:De,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let Er=null;const Cx=()=>Er,xT=async t=>{const a=(await be.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 Er&&Er.push(r),r},gl=async()=>{var r;const a=(((r=(await be.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 Er=a,a},hT=async(t,s)=>{const r=(await be.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 Er&&(Er=Er.map(i=>i.id===t?n:i)),n};function e0({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 pT({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:l,submitting:o,savingDraft:d,loadingDraft:c,isEditing:m}){return e.jsx("div",{className:"fixed sm:relative bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0 shadow-lg sm:shadow-none z-50","data-testid":"wizard-footer",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2 sm:gap-4 max-w-6xl mx-auto",children:[e.jsxs(E,{variant:"outline",onClick:r,disabled:t===1,size:"sm",className:"sm:size-lg order-2 sm:order-1","data-testid":"wizard-footer-prev-button",children:[e.jsx(ws,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Previous"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 order-1 sm:order-2","data-testid":"wizard-footer-actions",children:[e.jsx(E,{variant:"outline",onClick:l,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:c||o||d,"data-testid":"wizard-footer-save-draft-button",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),e.jsx("span",{children:m?"Updating...":"Saving..."})]}):e.jsx("span",{children:m?"Update Draft":"Save Draft"})}),t===s?e.jsx(E,{onClick:i,disabled:!a||c||o||d,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(Ke,{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(xh,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(E,{onClick:n,disabled:!a,size:"sm",className:"sm:size-lg flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-next-button",children:[e.jsx("span",{className:"hidden sm:inline",children:"Next Step"}),e.jsx("span",{className:"sm:hidden",children:"Next"}),e.jsx(fs,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const Sx=t=>{switch(t){case"high":return e.jsx(Ra,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(es,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(zs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(es,{className:"w-4 h-4 text-gray-600"})}};function gT({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var c;const[n,i]=h.useState("main"),l=Cs(),o=m=>{m.id==="admin-templates-category"?i("admin"):n==="admin"?l(`/create-admin-request/${m.id}`):a(m)},d=n==="main"?[...t]:r;return e.jsxs(Wt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"min-h-full flex flex-col items-center justify-center py-8","data-testid":"template-selection-step",children:[e.jsxs("div",{className:"text-center mb-12 max-w-3xl","data-testid":"template-selection-header",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4","data-testid":"template-selection-title",children:n==="main"?"Choose Your Request Type":"Organization Templates"}),e.jsx("p",{className:"text-lg text-gray-600","data-testid":"template-selection-description",children:n==="main"?"Start with a pre-built template for faster approvals, or create a custom request tailored to your needs.":"Select a pre-configured workflow template defined by your organization."})]}),n==="admin"&&e.jsx("div",{className:"w-full max-w-6xl mb-6 flex justify-start",children:e.jsxs(E,{variant:"ghost",className:"gap-2",onClick:()=>i("main"),children:[e.jsx(ws,{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:d.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(Rb,{className:"w-12 h-12 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No admin templates available yet."})]}):d.map(m=>{var g;const x=m.id==="admin-templates-category",u=(s==null?void 0:s.id)===m.id;return e.jsx(Wt.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${m.id}`,children:e.jsxs(Z,{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(Wt.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(Wa,{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(ce,{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(re,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),Sx(m.priority)]})]})]}),e.jsxs(te,{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(Jt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${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(Zt,{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(ml,{children:s&&e.jsx(Wt.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(Z,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Mr,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(te,{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(ae,{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(ae,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[Sx(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(ae,{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(ae,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((c=s.commonApprovers)==null?void 0:c.length)>0?s.commonApprovers.map((m,p)=>e.jsx(re,{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 ke({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 fT({className:t,...s}){return e.jsx(Mf,{"data-slot":"radio-group",className:Me("grid gap-3",t),...s})}function Ax({className:t,...s}){return e.jsx(Lf,{"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(Of,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(Ko,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function bT({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(Wt.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(De,{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(ae,{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(ke,{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(ae,{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(ei,{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(ae,{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(fT,{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(Ax,{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(Xi,{className:"w-4 h-4 text-red-600"}),e.jsx(ae,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(re,{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(Ax,{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(ae,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(re,{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(ae,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(ke,{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(ae,{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(Q,{value:"USD",children:"USD ($)"}),e.jsx(Q,{value:"EUR",children:"EUR (€)"}),e.jsx(Q,{value:"GBP",children:"GBP (£)"}),e.jsx(Q,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(ae,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(ke,{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(ae,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(ke,{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(ae,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(ke,{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 t0(){const[t,s]=h.useState([]),[a,r]=h.useState(!1),n=h.useRef(null);return{searchResults:t,searchLoading:a,searchUsersDebounced:async(d,c=10)=>{if(n.current&&clearTimeout(n.current),!d||!d.startsWith("@")||d.length<2){s([]),r(!1);return}r(!0),n.current=setTimeout(async()=>{var m;try{const p=d.slice(1),u=((m=(await ya(p,c)).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 d=>{try{return await ba({userId:d.userId,email:d.email,displayName:d.displayName,firstName:d.firstName,lastName:d.lastName,department:d.department,phone:d.phone,mobilePhone:d.mobilePhone,designation:d.designation,jobTitle:d.jobTitle,manager:d.manager,employeeId:d.employeeId,employeeNumber:d.employeeNumber,secondEmail:d.secondEmail,location:d.location})}catch(c){throw console.error("Failed to ensure user exists:",c),c}}}}function s0(){const[t,s]=h.useState({}),[a,r]=h.useState({}),n=h.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(o,d,c=10)=>{if(n.current[o]&&clearTimeout(n.current[o]),!d||!d.startsWith("@")||d.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=d.slice(1),u=((m=(await ya(p,c)).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(d=>({...d,[o]:[]})),r(d=>({...d,[o]:!1}))}}}function jT({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var p;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:d}=s0();h.useEffect(()=>{const x=t.approverCount||1,u=t.approvers||[];if(u.lengthx&&s("approvers",u.slice(0,x))},[t.approverCount,s]);const c=(x,u)=>{var j,y,v,w,S;const g=[...t.approvers],f=((j=g[x])==null?void 0:j.email)!==u;if(g[x]={...g[x],email:u,level:x+1,userId:f||(y=g[x])==null?void 0:y.userId,name:f||(v=g[x])==null?void 0:v.name,department:f||(w=g[x])==null?void 0:w.department,avatar:f||(S=g[x])==null?void 0:S.avatar},s("approvers",g),!u||!u.startsWith("@")||u.length<2){d(x);return}o(x,u,10)},m=async(x,u)=>{var g,b;try{if((g=t.approvers)==null?void 0:g.some((w,S)=>{var C,I;return S!==x&&(w.userId===u.userId||((C=w.email)==null?void 0:C.toLowerCase())===((I=u.email)==null?void 0:I.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((b=t.spectators)==null?void 0:b.some(w=>{var S,C;return w.userId===u.userId||((S=w.email)==null?void 0:S.toLowerCase())===((C=u.email)==null?void 0:C.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 ba({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}),v=[...t.approvers];v[x]={...v[x],email:u.email,name:u.displayName||[u.firstName,u.lastName].filter(Boolean).join(" "),userId:y.userId,level:x+1},s("approvers",v),d(x)}catch(f){console.error("Failed to ensure user exists:",f),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(Wt.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(Zt,{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(Z,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(ir,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(ye,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(te,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(ae,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const x=t.approverCount||1,u=Math.max(1,x-1);s("approverCount",u),t.approvers.length>u&&s("approvers",t.approvers.slice(0,u))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(Qo,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-2xl font-semibold w-12 text-center","data-testid":"approval-workflow-count-display",children:t.approverCount||1}),e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const u=(t.approverCount||1)+1;if(u>r.maxApprovalLevels){n([{type:"Maximum Approval Levels Exceeded",message:`Cannot add more than ${r.maxApprovalLevels} approval levels. Please remove an approver level or contact your administrator.`,currentValue:u,maxValue:r.maxApprovalLevels}]);return}s("approverCount",u)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(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(Z,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(oe,{children:[e.jsxs(ce,{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(te,{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(zt,{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(re,{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,b=g===(t.approverCount||1),f=t.approvers[u]||{email:"",tat:""};return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${g}`,children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-6 bg-gray-300"})}),e.jsx("div",{className:`p-4 rounded-lg border-2 transition-all ${f.email?"border-green-200 bg-green-50":"border-gray-200 bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${f.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:g})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",g]}),b&&e.jsx(re,{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(ae,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),f.email&&f.userId&&e.jsxs(re,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx($e,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(ke,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:f.email||"",onChange:v=>c(u,v.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(v=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(u,v),"data-testid":`approval-workflow-approver-${g}-search-result-${v.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:v.displayName||v.email}),e.jsx("div",{className:"text-xs text-gray-600",children:v.email})]},v.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-tat-field`,children:[e.jsx(ae,{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(ke,{id:`tat-${g}`,type:"number",placeholder:f.tatType==="days"?"7":"24",min:"1",max:f.tatType==="days"?"30":"720",value:f.tat||"",onChange:v=>{const w=[...t.approvers];w[u]={...w[u],tat:parseInt(v.target.value)||"",level:g,tatType:f.tatType||"hours"},s("approvers",w)},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:f.tatType||"hours",onValueChange:v=>{const w=[...t.approvers];w[u]={...w[u],tatType:v,level:g,tat:""},s("approvers",w)},"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(Q,{value:"hours",children:"Hours"}),e.jsx(Q,{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(Mr,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900 mb-1",children:"Approval Flow Summary"}),e.jsxs("p",{className:"text-sm text-blue-700",children:["Your request will follow this sequence: ",e.jsx("strong",{children:"You (Initiator)"})," → ",Array.from({length:t.approverCount||1},(x,u)=>`Level ${u+1} Approver`).join(" → "),". The final approver can close the request."]})]})]})}),e.jsx("div",{className:"p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-lg border border-emerald-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(st,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const j=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+j:b+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),f=(x.tatType||"hours")==="days"?g*24:g;return g?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",u+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[f," ",f===1?"hour":"hours"]})]})},u):null})}),(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const j=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+j*24:b+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 yT({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=h.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:d,clearSearch:c,ensureUser:m}=t0(),p=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){c();return}d(g,10)},x=async g=>{var b,f;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const j=t.spectators.some(v=>{var w,S;return v.userId===g.userId||((w=v.email)==null?void 0:w.toLowerCase())===((S=g.email)==null?void 0:S.toLowerCase())}),y=(b=t.approvers)==null?void 0:b.some(v=>{var w,S;return v.userId===g.userId||((w=v.email)==null?void 0:w.toLowerCase())===((S=g.email)==null?void 0:S.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 v=await m(g),w={id:v.userId,userId:v.userId,name:v.displayName||g.email.split("@")[0],email:v.email,avatar:(v.displayName||v.email).substring(0,2).toUpperCase(),role:"Spectator",department:v.department||"",level:1,canClose:!1},S=[...t.spectators,w];s("spectators",S),i(""),c()}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(v=>{var w;return((w=v.email)==null?void 0:w.toLowerCase())===n.toLowerCase()}),y=(f=t.approvers)==null?void 0:f.some(v=>{var w;return((w=v.email)==null?void 0:w.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 b=t.spectators.filter(f=>f.id!==g);s("spectators",b)};return e.jsxs(Wt.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(Nt,{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(Z,{"data-testid":"participants-spectators-card",children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center justify-between text-base","data-testid":"participants-spectators-title",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nt,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(re,{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(te,{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(ke,{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(E,{size:"sm",onClick:()=>x(),disabled:!n||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n),"data-testid":"participants-spectators-add-button",children:"Add"})]}),e.jsxs("p",{className:"text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded p-2 flex items-center gap-1",children:[e.jsx(Mr,{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(os,{className:"h-6 w-6",children:e.jsx(cs,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(jt,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function vT({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:d,onDocumentErrors:c,fileInputRef:m}){const p=b=>{const f=Array.from(b.target.files||[]);if(f.length===0)return;const j=t.maxFileSizeMB*1024*1024,y=[],v=[];f.forEach(w=>{if(w.size>j){y.push({fileName:w.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(w.size/1048576).toFixed(2)}MB`});return}const S=w.name.toLowerCase(),C=S.substring(S.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(C)){y.push({fileName:w.name,reason:`File type "${C}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}v.push(w)}),v.length>0&&i([...a,...v]),y.length>0&&c&&c(y),b.target&&(b.target.value="")},x=b=>{const f=a.filter((j,y)=>y!==b);i(f)},u=b=>{o([...n,b])},g=(b,f=!1)=>{if(f){const j=(b.fileType||b.file_type||"").toLowerCase(),y=(b.originalFileName||b.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=(b.type||"").toLowerCase(),y=(b.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(Wt.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(Z,{"data-testid":"documents-upload-card",children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(De,{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(te,{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(b=>`.${b}`).join(","),onChange:p,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(E,{variant:"outline",size:"lg",type:"button",onClick:()=>{var b;return(b=m.current)==null?void 0:b.click()},"data-testid":"documents-browse-button",children:[e.jsx(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(b=>b.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(Z,{"data-testid":"documents-existing-card",children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(re,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length," file",r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length!==1?"s":""]})]})}),e.jsx(te,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(b=>{const f=b.documentId||b.document_id||"";return n.includes(f)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${f}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(De,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.originalFileName||b.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:b.fileSize?(Number(b.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!0)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>d(b,!0),"data-testid":`documents-existing-${f}-preview`,children:e.jsx(Nt,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(f),"data-testid":`documents-existing-${f}-delete`,children:e.jsx(jt,{className:"h-4 w-4 text-red-600"})})]})]},f)})})})]}),a.length>0&&e.jsxs(Z,{"data-testid":"documents-new-card",children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(re,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(te,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((b,f)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${f}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(De,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(b.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!1)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>d(b,!1),"data-testid":`documents-new-${f}-preview`,children:e.jsx(Nt,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>x(f),"data-testid":`documents-new-${f}-remove`,children:e.jsx(jt,{className:"h-4 w-4"})})]})]},f))})})]})]})]})}const NT=t=>{switch(t){case"high":return e.jsx(Ra,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(es,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(zs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(es,{className:"w-4 h-4 text-gray-600"})}};function wT({formData:t,selectedTemplate:s}){return e.jsxs(Wt.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($e,{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(Z,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(xh,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(te,{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(ae,{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(re,{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(ae,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[NT(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(ae,{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(ae,{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(Z,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(De,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(te,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(ae,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(Is,{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(Ga,{className:"w-4 h-4 text-blue-600"}),e.jsx(ae,{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(Z,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(Zt,{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(te,{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(re,{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(Z,{"data-testid":"review-submit-participants-card",children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(Nt,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(te,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(ae,{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(re,{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(Z,{"data-testid":"review-submit-documents-card",children:[e.jsxs(oe,{children:[e.jsxs(ce,{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(te,{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(De,{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(Z,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(te,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx($e,{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 CT({isEditing:t,currentStep:s,totalSteps:a,stepNames:r,onBack:n}){return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0","data-testid":"create-request-header",children:e.jsxs("div",{className:"flex items-center justify-between max-w-6xl mx-auto gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-1 min-w-0",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"create-request-back-button",children:e.jsx(ws,{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 ST({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(ml,{mode:"wait",children:t})})})}function AT({modal:t,onClose:s}){return e.jsx(pt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(ut,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsxs(xt,{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(Zi,{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(It,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function TT({modal:t,documentPolicy:s,onClose:a}){return e.jsx(pt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(ut,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(xt,{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(It,{children:e.jsx(E,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function Tx({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Oa(),i=Cs(),l=n.requestId||a||"",o=r&&!!l,{user:d}=ds(),[c,m]=h.useState([]);h.useEffect(()=>{(async()=>{try{const ve=(await gl()).map(Ne=>({id:Ne.id,name:Ne.name,description:Ne.description,category:Ne.category,icon:De,estimatedTime:Ne.estimatedTime,commonApprovers:Ne.approvers.map(Ue=>Ue.name),workflowApprovers:Ne.approvers,suggestedSLA:Ne.suggestedSLA,priority:Ne.priority,fields:Ne.fields||{}}));m(ve)}catch(Pe){console.error("Failed to fetch admin templates:",Pe)}})()},[]);const p=h.useMemo(()=>[...wx,...c],[c]),{formData:x,updateFormData:u,selectedTemplate:g,setSelectedTemplate:b,loadingDraft:f,systemPolicy:j,documentPolicy:y,existingDocuments:v,setExistingDocuments:w}=XA(o,l,p),{currentStep:S,totalSteps:C,stepNames:I,isStepValid:D,nextStep:T,prevStep:N}=JA(o,g,x),[_,A]=h.useState([]),[z,F]=h.useState([]),O=h.useRef(null),{validationModal:P,policyViolationModal:k,documentErrorModal:R,openValidationModal:V,closeValidationModal:M,openPolicyViolationModal:L,closePolicyViolationModal:U,openDocumentErrorModal:H,closeDocumentErrorModal:X}=ZA(),{submitting:J,savingDraft:$,handleSubmit:B,handleSaveDraft:K}=aT({formData:x,selectedTemplate:g,documents:_,documentsToDelete:z,user:d,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:se,setShowTemplateModal:Y,previewDocument:ee,selectTemplate:me,handleTemplateSelection:Se,nextStep:Je,prevStep:Ve,handlePreviewDocument:Ee,closePreview:Oe}=uT({selectedTemplate:g,setSelectedTemplate:b,updateFormData:u,formData:x,currentStep:S,isStepValid:D,wizardNextStep:T,wizardPrevStep:N,user:d,openValidationModal:V,systemPolicy:j,onPolicyViolation:L,onSubmit:s}),ie=h.useCallback(()=>{if(S===1){i("/dashboard",{replace:!0});return}S===3||S===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Ve()},[S,t,i,Ve]),ge=h.useRef(!0),we=h.useRef(!1);h.useEffect(()=>{ge.current&&x.documents&&x.documents.length>0&&!we.current&&(A(x.documents),we.current=!0),ge.current=!1},[x.documents]);const Te=h.useRef(!1),de=h.useRef(_);h.useEffect(()=>{if(Te.current){Te.current=!1,de.current=_;return}de.current!==_&&(u("documents",_),de.current=_)},[_]);const q=()=>{switch(S){case 1:return e.jsx(gT,{templates:wx,selectedTemplate:g,onSelectTemplate:me,adminTemplates:c});case 2:return e.jsx(bT,{formData:x,selectedTemplate:g,updateFormData:u});case 3:return e.jsx(jT,{formData:x,updateFormData:u,systemPolicy:j,onValidationError:ue=>V(ue.type,ue.email,ue.message),onPolicyViolation:L});case 4:return e.jsx(yT,{formData:x,updateFormData:u,onValidationError:ue=>V(ue.type,ue.email,ue.message),initiatorEmail:(d==null?void 0:d.email)||""});case 5:return e.jsx(vT,{documentPolicy:y,isEditing:o,documents:_,existingDocuments:v,documentsToDelete:z,onDocumentsChange:A,onExistingDocumentsChange:w,onDocumentsToDeleteChange:F,onPreviewDocument:Ee,onDocumentErrors:ue=>H(ue),fileInputRef:O});case 6:return e.jsx(wT,{formData:x,selectedTemplate:g});default:return null}};return f?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center","data-testid":"create-request-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading draft..."})]})}):e.jsxs("div",{className:"h-full flex flex-col bg-gradient-to-br from-gray-50 to-white","data-testid":"create-request",children:[e.jsx(CT,{isEditing:o,currentStep:S,totalSteps:C,stepNames:I,onBack:ie}),e.jsx(e0,{currentStep:S,totalSteps:C,stepNames:I}),e.jsx(ST,{children:q()}),e.jsx(pT,{currentStep:S,totalSteps:C,isStepValid:D(),onPrev:Ve,onNext:Je,onSubmit:B,onSaveDraft:K,submitting:J,savingDraft:$,loadingDraft:f,isEditing:o}),e.jsx(MA,{open:se,onClose:()=>Y(!1),onSelectTemplate:Se}),ee&&e.jsx(Or,{fileName:ee.fileName,fileType:ee.fileType,fileUrl:ee.fileUrl,fileSize:ee.fileSize,open:!!ee,onClose:Oe,onDownload:async()=>{if(ee.file){const ue=document.createElement("a");ue.href=ee.fileUrl,ue.download=ee.fileName,document.body.appendChild(ue),ue.click(),document.body.removeChild(ue)}else ee.documentId&&await _s(ee.documentId)},attachmentId:ee.documentId}),e.jsx(AT,{modal:P,onClose:M}),e.jsx(TT,{modal:R,documentPolicy:y,onClose:X}),e.jsx(ni,{open:k.open,onClose:U,violations:k.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}function ii({className:t,...s}){return e.jsx($f,{"data-slot":"tabs",className:Me("flex flex-col gap-2",t),...s})}function li({className:t,...s}){return e.jsx(Uf,{"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 $t({className:t,...s}){return e.jsx(Bf,{"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 Ut({className:t,...s}){return e.jsx(Vf,{"data-slot":"tabs-content",className:Me("flex-1 outline-none",t),...s})}function Yn(t){return t?t.workflowType==="CLAIM_MANAGEMENT"||t.templateType==="claim-management"||t.template==="claim-management"||t.templateName==="Claim Management"||t.templateCode==="CLAIM_MANAGEMENT":!1}function Xc(t,s=[],a){const[r,n]=h.useState(null),[i,l]=h.useState(!1),[o,d]=h.useState(!0),[c,m]=h.useState(null),[p,x]=h.useState(null),[u,g]=h.useState(!1),b=(S,C)=>(S||C||"NA").toString().split(" ").map(D=>D[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),f=S=>{const C=(S||"").toUpperCase();return C==="IN_PROGRESS"?"in-review":C==="PENDING"?"pending":C==="APPROVED"?"approved":C==="REJECTED"?"rejected":C==="CLOSED"?"closed":C==="SKIPPED"?"skipped":(S||"").toLowerCase()},j=h.useCallback(async()=>{var S,C,I,D,T,N,_,A,z,F,O,P,k;l(!0);try{const R=await Hs.getWorkflowDetails(t);if(!R){console.warn("[useRequestDetails] No details returned from API");return}const V=R.workflow||{},M=Array.isArray(R.approvals)?R.approvals:[],L=Array.isArray(R.participants)?R.participants:[],U=Array.isArray(R.documents)?R.documents:[],H=R.summary||{},X=Array.isArray(R.tatAlerts)?R.tatAlerts:[];X.length>0;const J=(H==null?void 0:H.currentLevel)||V.currentLevel||1,$=M.map(q=>{const ue=q.levelNumber||0,Pe=(q.status||"").toString().toUpperCase(),ve=q.levelId||q.level_id;let Ne=f(q.status);ue>J&&Pe!=="APPROVED"&&Pe!=="REJECTED"?Ne="waiting":ue===J&&Pe==="PENDING"&&(Ne="pending");const Ue=X.filter(nt=>nt.levelId===ve);return{step:ue,levelId:ve,role:q.levelName||q.approverName||"Approver",status:Ne,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:Ue,skipReason:q.skipReason||void 0,isSkipped:Pe==="SKIPPED"||q.isSkipped||!1}}),B=L.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:b(q.userName||q.user_name,q.userEmail||q.user_email)})),K=q=>{var Pe,ve;if(!q)return;const ue=L.find(Ne=>Ne.userId===q||Ne.user_id===q);return ue!=null&&ue.userName||ue!=null&&ue.user_name?ue.userName||ue.user_name:V.initiatorId===q?((Pe=V.initiator)==null?void 0:Pe.displayName)||((ve=V.initiator)==null?void 0:ve.email):q},se=U.map(q=>{const ue=Number(q.fileSize||q.file_size||0),Pe=(ue/(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:ue,uploadedBy:K(q.uploadedBy||q.uploaded_by),uploadedAt:q.uploadedAt||q.uploaded_at}}),Y=Array.isArray(R.activities)?R.activities.filter(q=>(q.type||"").toLowerCase()!=="sla_warning"):[];let ee=null;if(V.isPaused||!1)try{ee=await eu(V.requestId)}catch{}let Se=null,Je=null,Ve=null,Ee=null,Oe=[],ie=null;if(Yn(V)){try{const q=await be.get(`/dealer-claims/${V.requestId}/credit-note-wfm`),ue=q.data??q;ie=Array.isArray(ue==null?void 0:ue.data)?ue.data:Array.isArray(ue)?ue:[]}catch(q){console.warn("[useRequestDetails] Error fetching credit note WFM data:",q)}try{const q=await be.get(`/dealer-claims/${V.requestId}`),ue=((S=q.data)==null?void 0:S.data)||q.data;if(ue){Se=ue.claimDetails||ue.claim_details,Je=ue.proposalDetails||ue.proposal_details,Ve=ue.completionDetails||ue.completion_details,Ee=ue.internalOrder||ue.internal_order||null,Oe=ue.internalOrders||ue.internal_orders||[];const Pe=ue.budgetTracking||ue.budget_tracking||null,ve=ue.invoice||null,Ne=ue.creditNote||ue.credit_note||null,Ue=ue.completionExpenses||ue.completion_expenses||null;Se&&(Se.budgetTracking=Pe,Se.invoice=ve,Se.creditNote=Ne,Se.completionExpenses=Ue,Se.creditNoteWfmData=ie)}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:(C=q==null?void 0:q.response)==null?void 0:C.status,statusText:(I=q==null?void 0:q.response)==null?void 0:I.statusText,responseData:(D=q==null?void 0:q.response)==null?void 0:D.data,requestId:V.requestId})}}const ge={...V,id:V.requestNumber||V.requestId,requestId:V.requestId,requestNumber:V.requestNumber,title:V.title,description:V.description,status:f(V.status),priority:(V.priority||"").toString().toLowerCase(),workflowType:V.workflowType||(V.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:$,approvals:M,participants:L,documents:se,spectators:B,summary:H,sla:(H==null?void 0:H.sla)||V.sla||null,initiator:{name:((T=V.initiator)==null?void 0:T.displayName)||((N=V.initiator)==null?void 0:N.email),role:((_=V.initiator)==null?void 0:_.designation)||void 0,department:((A=V.initiator)==null?void 0:A.department)||void 0,email:((z=V.initiator)==null?void 0:z.email)||void 0,phone:((F=V.initiator)==null?void 0:F.phone)||void 0,avatar:b((O=V.initiator)==null?void 0:O.displayName,(P=V.initiator)==null?void 0:P.email)},createdAt:V.createdAt,updatedAt:V.updatedAt,totalSteps:V.totalLevels||1,currentStepRaw:(H==null?void 0:H.currentLevel)||V.currentLevel||1,currentStep:Math.min(Math.max(1,(H==null?void 0:H.currentLevel)||V.currentLevel||1),V.totalLevels||1),auditTrail:Y,conclusionRemark:V.conclusionRemark||null,closureDate:V.closureDate||null,pauseInfo:ee||null,claimDetails:Se||null,proposalDetails:Je||null,completionDetails:Ve||null,internalOrder:Ee||null,internalOrders:Oe||[],budgetTracking:(Se==null?void 0:Se.budgetTracking)||null,invoice:(Se==null?void 0:Se.invoice)||(Se==null?void 0:Se.invoice)||null,creditNote:(Se==null?void 0:Se.creditNote)||null,creditNoteWfmData:ie||(Se==null?void 0:Se.creditNoteWfmData)||null,completionExpenses:(Se==null?void 0:Se.completionExpenses)||null,templateType:V.templateType||V.template_type,form16Submission:R.form16Submission||null};n(ge);const we=(k=a==null?void 0:a.email)==null?void 0:k.toLowerCase(),Te=M.find(q=>{const ue=(q.status||"").toString().toUpperCase(),Pe=(q.approverEmail||"").toLowerCase(),ve=q.levelNumber||0;return(ue==="PENDING"||ue==="IN_PROGRESS"||ue==="PAUSED")&&Pe===we&&ve===J});x(Te||null);const de=a==null?void 0:a.userId;if(de){const q=L.some(ue=>(ue.participantType||ue.participant_type||"").toUpperCase()==="SPECTATOR"&&(ue.userId||ue.user_id)===de);g(q)}else g(!1)}catch(R){console.error("[useRequestDetails] Error refreshing details:",R),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);h.useEffect(()=>{if(!t){d(!1);return}let S=!0;return d(!0),m(null),(async()=>{var C,I,D,T,N,_,A,z,F,O,P,k,R,V;try{const M=await Hs.getWorkflowDetails(t);if(!S||!M){S&&d(!1);return}const L=M.workflow||{},U=Array.isArray(M.approvals)?M.approvals:[],H=Array.isArray(M.participants)?M.participants:[],X=Array.isArray(M.documents)?M.documents:[],J=M.summary||{},$=Array.isArray(M.tatAlerts)?M.tatAlerts:[],B=(L.priority||"").toString().toLowerCase(),K=(J==null?void 0:J.currentLevel)||L.currentLevel||1,se=U.map(ve=>{const Ne=ve.levelNumber||0,Ue=(ve.status||"").toString().toUpperCase(),nt=ve.levelId||ve.level_id;let ot=f(ve.status);Ue==="PAUSED"?ot="paused":Ne>K&&Ue!=="APPROVED"&&Ue!=="REJECTED"?ot="waiting":Ne===K&&(Ue==="PENDING"||Ue==="IN_PROGRESS")&&(ot=Ue==="IN_PROGRESS"?"in-review":"pending");const Tt=$.filter(Mt=>Mt.levelId===nt);return{step:Ne,levelId:nt,role:ve.levelName||ve.approverName||"Approver",status:ot,approver:ve.approverName||ve.approverEmail,approverId:ve.approverId||ve.approver_id,approverEmail:ve.approverEmail,tatHours:Number(ve.tatHours||0),elapsedHours:Number(ve.elapsedHours||0),remainingHours:Number(ve.remainingHours||0),tatPercentageUsed:Number(ve.tatPercentageUsed||0),actualHours:ve.elapsedHours!==void 0&&ve.elapsedHours!==null?Number(ve.elapsedHours):void 0,comment:ve.comments||void 0,timestamp:ve.actionDate||void 0,levelStartTime:ve.levelStartTime||ve.tatStartTime,tatAlerts:Tt}}),Y=H.filter(ve=>(ve.participantType||"").toUpperCase()==="SPECTATOR").map(ve=>({name:ve.userName||ve.userEmail,role:"Spectator",avatar:b(ve.userName,ve.userEmail)})),ee=ve=>{var Ue,nt;if(!ve)return;const Ne=H.find(ot=>ot.userId===ve);return Ne!=null&&Ne.userName?Ne.userName:L.initiatorId===ve?((Ue=L.initiator)==null?void 0:Ue.displayName)||((nt=L.initiator)==null?void 0:nt.email):ve},me=X.map(ve=>{const Ne=Number(ve.fileSize||0),Ue=(Ne/(1024*1024)).toFixed(2)+" MB";return{documentId:ve.documentId||ve.document_id,name:ve.originalFileName||ve.fileName,fileType:ve.fileType||ve.file_type||"",size:Ue,sizeBytes:Ne,uploadedBy:ee(ve.uploadedBy),uploadedAt:ve.uploadedAt}}),Se=Array.isArray(M.activities)?M.activities.filter(ve=>(ve.type||"").toLowerCase()!=="sla_warning"):[];let Je=null;if(L.isPaused||!1)try{Je=await eu(L.requestId)}catch{}let Ee=null,Oe=null,ie=null,ge=null,we=[],Te=null;if(Yn(L)){try{const ve=await be.get(`/dealer-claims/${L.requestId}/credit-note-wfm`),Ne=ve.data??ve;Te=Array.isArray(Ne==null?void 0:Ne.data)?Ne.data:Array.isArray(Ne)?Ne:[]}catch(ve){console.warn("[useRequestDetails] Error fetching credit note WFM data:",ve)}try{const ve=await be.get(`/dealer-claims/${L.requestId}`),Ne=((C=ve.data)==null?void 0:C.data)||ve.data;if(Ne){Ee=Ne.claimDetails||Ne.claim_details,Oe=Ne.proposalDetails||Ne.proposal_details,ie=Ne.completionDetails||Ne.completion_details,ge=Ne.internalOrder||Ne.internal_order||null,we=Ne.internalOrders||Ne.internal_orders||[];const Ue=Ne.budgetTracking||Ne.budget_tracking||null,nt=Ne.invoice||null,ot=Ne.creditNote||Ne.credit_note||null,Tt=Ne.completionExpenses||Ne.completion_expenses||null;Ee&&(Ee.budgetTracking=Ue,Ee.invoice=nt,Ee.creditNote=ot,Ee.completionExpenses=Tt,Ee.creditNoteWfmData=Te)}}catch(ve){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(ve==null?void 0:ve.message)||ve,status:(I=ve==null?void 0:ve.response)==null?void 0:I.status,requestId:L.requestId})}}const de={id:L.requestNumber||L.requestId,requestId:L.requestId,title:L.title,description:L.description,priority:B,status:f(L.status),workflowType:L.workflowType||(L.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:J,initiator:{name:((D=L.initiator)==null?void 0:D.displayName)||((T=L.initiator)==null?void 0:T.email),role:((N=L.initiator)==null?void 0:N.designation)||void 0,department:((_=L.initiator)==null?void 0:_.department)||void 0,email:((A=L.initiator)==null?void 0:A.email)||void 0,phone:((z=L.initiator)==null?void 0:z.phone)||void 0,avatar:b((F=L.initiator)==null?void 0:F.displayName,(O=L.initiator)==null?void 0:O.email)},createdAt:L.createdAt,updatedAt:L.updatedAt,totalSteps:L.totalLevels||1,currentStepRaw:(J==null?void 0:J.currentLevel)||L.currentLevel||1,currentStep:Math.min(Math.max(1,(J==null?void 0:J.currentLevel)||L.currentLevel||1),L.totalLevels||1),approvalFlow:se,approvals:U,documents:me,spectators:Y,auditTrail:Se,conclusionRemark:L.conclusionRemark||null,closureDate:L.closureDate||null,pauseInfo:Je||null,claimDetails:Ee||null,proposalDetails:Oe||null,completionDetails:ie||null,internalOrder:ge||null,internalOrders:we||[],budgetTracking:(Ee==null?void 0:Ee.budgetTracking)||null,invoice:(Ee==null?void 0:Ee.invoice)||null,creditNote:(Ee==null?void 0:Ee.creditNote)||null,creditNoteWfmData:Te||(Ee==null?void 0:Ee.creditNoteWfmData)||null,completionExpenses:(Ee==null?void 0:Ee.completionExpenses)||null,templateType:L.templateType||L.template_type,form16Submission:M.form16Submission||null};n(de);const q=(P=a==null?void 0:a.email)==null?void 0:P.toLowerCase(),ue=U.find(ve=>{const Ne=(ve.status||"").toString().toUpperCase(),Ue=(ve.approverEmail||"").toLowerCase(),nt=ve.levelNumber||0;return(Ne==="PENDING"||Ne==="IN_PROGRESS"||Ne==="PAUSED")&&Ue===q&&nt===K});x(ue||null);const Pe=a==null?void 0:a.userId;if(Pe){const ve=H.some(Ne=>(Ne.participantType||"").toUpperCase()==="SPECTATOR"&&Ne.userId===Pe);g(ve)}else g(!1)}catch(M){if(console.error("[useRequestDetails] Error loading request details:",M),S){if(((k=M==null?void 0:M.response)==null?void 0:k.status)===403){const L=((V=(R=M==null?void 0:M.response)==null?void 0:R.data)==null?void 0:V.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:L})}n(null)}}finally{S&&d(!1)}})(),()=>{S=!1}},[t,a]);const y=h.useMemo(()=>{if(r)return r;const S=s.find(C=>C.id===t||C.requestNumber===t||C.request_number===t);return S||null},[t,s,r]),v=h.useMemo(()=>{var I,D,T;if(!y||!a)return!1;const S=(I=a==null?void 0:a.email)==null?void 0:I.toLowerCase(),C=(T=(D=y.initiator)==null?void 0:D.email)==null?void 0:T.toLowerCase();return S===C},[y,a]),w=h.useMemo(()=>{var C;if(!y)return[];const S=[];return(C=y.initiator)!=null&&C.email&&S.push({email:y.initiator.email.toLowerCase(),participantType:"INITIATOR",name:y.initiator.name}),y.approvalFlow&&Array.isArray(y.approvalFlow)&&y.approvalFlow.forEach(I=>{I.approverEmail&&S.push({email:I.approverEmail.toLowerCase(),participantType:"APPROVER",name:I.approver})}),y.spectators&&Array.isArray(y.spectators)&&y.spectators.forEach(I=>{I.email&&S.push({email:I.email.toLowerCase(),participantType:"SPECTATOR",name:I.name})}),y.participants&&Array.isArray(y.participants)&&y.participants.forEach(I=>{const D=(I.userEmail||I.email||"").toLowerCase(),T=(I.participantType||I.participant_type||"").toUpperCase(),N=I.userName||I.user_name||I.name;D&&T&&!S.find(_=>_.email===D)&&S.push({email:D,participantType:T,name:N})}),S},[y]);return h.useEffect(()=>{if(!t||!r)return;const S=an();if(!S)return;const C=I=>{((I==null?void 0:I.requestId)===r.requestId||(I==null?void 0:I.requestNumber)===t)&&j()};return S.on("request:updated",C),()=>{S.off("request:updated",C)}},[t,r,j]),{request:y,apiRequest:r,loading:o,refreshing:i,refreshDetails:j,currentApprovalLevel:p,isSpectator:u,isInitiator:v,existingParticipants:w,accessDenied:c}}function a0(t,s,a,r){const[n,i]=h.useState([]),[l,o]=h.useState(0),[d,c]=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 b;try{const f=await Hs.getWorkflowDetails(t);(b=f==null?void 0:f.workflow)!=null&&b.requestId&&m&&(p=f.workflow.requestId)}catch(f){console.error("[useRequestSocket] Failed to resolve UUID:",f)}if(!m)return;const x=an();if(!x){console.error("[useRequestSocket] Socket not available");return}const u=r==null?void 0:r.userId,g=()=>{bo(x,p,u)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),Jh(x,p))}})(),()=>{m=!1}},[t,r]),h.useEffect(()=>{!t||!s||(async()=>{try{const m=await tn(t),p=s.auditTrail||[],x=[...m,...p];x.sort((u,g)=>{const b=new Date(u.createdAt||u.created_at||u.timestamp||0).getTime(),f=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return b-f}),i(x)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),h.useEffect(()=>{if(!t)return;const m=an();if(!m)return;const p=u=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await tn(t),b=(s==null?void 0:s.auditTrail)||[],f=[...g,...b].sort((j,y)=>{const v=new Date(j.createdAt||j.created_at||j.timestamp||0).getTime(),w=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime();return v-w});i(f)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},x=u=>{const g=u.type==="breach"?"⏰":u.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const b=await Hs.getWorkflowDetails(t);b&&(Array.isArray(b.tatAlerts)&&b.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:u.message,icon:"/favicon.ico",tag:`tat-${u.requestId}-${u.type}`,requireInteraction:!1}))}catch(b){console.error("[useRequestSocket] Failed to refresh after TAT alert:",b)}})()};return m.on("noteHandler",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:d,setWorkNoteAttachments:c}}async function Pn(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 be.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 kT=["MALWARE_DETECTED","FILE_VALIDATION_FAILED","CONTENT_THREAT_DETECTED","SCAN_UNAVAILABLE","SCAN_ERROR"],RT={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 Jc(t){var l,o,d,c;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(!kT.includes(a))return!1;const r=RT[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(", ")}`:(d=s.details.errors)!=null&&d.length?i=s.details.errors[0]||"":(c=s.details.threats)!=null&&c.length&&(i=s.details.threats.map(m=>m.description).join(", "))),G.error(r,{description:i||n,duration:8e3,style:{background:"#fef2f2",border:"1px solid #fca5a5",color:"#991b1b"}}),!0}function r0(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"]}),[d,c]=h.useState({show:!1,errors:[]});h.useEffect(()=>{(async()=>{try{const g=await ma("DOCUMENT_POLICY"),b={};g.forEach(v=>{b[v.configKey]=v.configValue});const f=parseInt(b.MAX_FILE_SIZE_MB||"10"),y=(b.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(v=>v.trim().toLowerCase());o({maxFileSizeMB:f,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 b=u.name.toLowerCase(),f=b.substring(b.lastIndexOf(".")+1);return l.allowedFileTypes.includes(f)?{valid:!0}:{valid:!1,reason:`File type "${f}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},p=async u=>{var y,v;const g=u.target.files;if(!g||g.length===0)return;const b=Array.from(g),f=[],j=[];if(b.forEach(w=>{const S=m(w);S.valid?j.push(w):f.push({fileName:w.name,reason:S.reason||"Unknown validation error"})}),f.length>0&&c({show:!0,errors:f}),j.length===0){u.target&&(u.target.value="");return}r(!0);try{const w=j[0],S=t==null?void 0:t.requestId;if(!S){G.error("Request ID not found");return}w&&await Pn(w,S,"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:d,setDocumentError:c}}const DT="modulepreload",FT=function(t){return"/"+t},kx={},Ql=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(d=>{if(d=FT(d),d in kx)return;kx[d]=!0;const c=d.endsWith(".css"),m=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${m}`))return;const p=document.createElement("link");if(p.rel=c?"stylesheet":DT,c||(p.as="script"),p.crossOrigin="",p.href=d,o&&p.setAttribute("nonce",o),document.head.appendChild(p),c)return new Promise((x,u)=>{p.addEventListener("load",x),p.addEventListener("error",()=>u(new Error(`Unable to preload CSS for ${d}`)))})}))}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 n0(t,s,a,r,n,i,l){const[o,d]=h.useState(""),[c,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(!1),[b,f]=h.useState(0),[j,y]=h.useState(!1),[v,w]=h.useState(!1),[S,C]=h.useState(0),I=async()=>{var A;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||_){d(N||_),g(!!_);return}try{const{getConclusion:z}=await Ql(async()=>{const{getConclusion:O}=await import("./conclusionApi-C6tUM9Rq.js");return{getConclusion:O}},__vite__mapDeps([0,1,2,3,4,5,6,7])),F=await z(t.requestId||s);F&&(F.aiGeneratedRemark||F.finalRemark)&&(d(F.finalRemark||F.aiGeneratedRemark||""),g(!!F.aiGeneratedRemark))}catch(z){((A=z==null?void 0:z.response)==null?void 0:A.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",z)}},D=async()=>{if(!v)try{m(!0),y(!1);const{generateConclusion:N}=await Ql(async()=>{const{generateConclusion:F}=await import("./conclusionApi-C6tUM9Rq.js");return{generateConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7])),_=await N(t.requestId||s),A=b+1;if(f(A),!(_!=null&&_.aiGeneratedRemark)||_.aiGeneratedRemark.toLowerCase().includes("unable to generate")||_.aiGeneratedRemark.toLowerCase().includes("sorry")){const F=S+1;C(F),F>=2?(w(!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),d((_==null?void 0:_.aiGeneratedRemark)||""),g(!1);return}d(_.aiGeneratedRemark),g(!0),C(0),A>=2&&(w(!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 _=S+1;C(_),g(!1),_>=2?(w(!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)}},T=async()=>{var _,A;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:z}=await Ql(async()=>{const{finalizeConclusion:F}=await import("./conclusionApi-C6tUM9Rq.js");return{finalizeConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await z(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(z){i==null||i({success:!1,title:"Error",message:((A=(_=z.response)==null?void 0:_.data)==null?void 0:A.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 A=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),z=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);A||z?(d(A||z),g(!!z)):I()},[t==null?void 0:t.status,t==null?void 0:t.conclusionRemark,t==null?void 0:t.aiGeneratedConclusion,a,o]),{conclusionRemark:o,setConclusionRemark:d,conclusionLoading:c,conclusionSubmitting:p,aiGenerated:u,handleGenerateConclusion:D,handleFinalizeConclusion:T,generationAttempts:b,generationFailed:j,maxAttemptsReached:v}}function i0(t,s,a){const[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,d]=h.useState(!1),[c,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(!1),[b,f]=h.useState(null),[j,y]=h.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:d,showAddSpectatorModal:c,setShowAddSpectatorModal:m,showSkipApproverModal:p,setShowSkipApproverModal:x,showActionStatusModal:u,setShowActionStatusModal:g,skipApproverData:b,setSkipApproverData:f,actionStatus:j,setActionStatus:y,handleApproveConfirm:async D=>{var N,_;const T=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!T){alert("Approval level not found");return}await Dn(t,T,D||""),await new Promise(A=>setTimeout(A,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 T=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!T){alert("Approval level not found");return}await Cr(t,T,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,T,N)=>{var _,A;try{await xp(t,D,T,N),await a(),d(!1),y==null||y({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${T}h TAT`}),g==null||g(!0)}catch(z){throw y==null||y({success:!1,title:"Failed to Add Approver",message:((A=(_=z==null?void 0:z.response)==null?void 0:_.data)==null?void 0:A.error)||"Failed to add approver. Please try again."}),g==null||g(!0),z}},handleSkipApprover:async D=>{var T,N;if(b)try{await Iw(t,b.levelId,D),await a(),x(!1),f(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=(T=_==null?void 0:_.response)==null?void 0:T.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),_}},handleAddSpectator:async D=>{var T,N;try{await hp(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=(T=_==null?void 0:_.response)==null?void 0:T.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),_}}}}function PT({requestId:t,request:s,onRefresh:a}){const[r,n]=h.useState(null),[i,l]=h.useState(!0),[o,d]=h.useState(null),m=!!(s==null?void 0:s.form16Submission),p=!!r&&r.status!=="withdrawn";h.useEffect(()=>{if(!t){l(!1);return}let g=!1;return(async()=>{try{const b=await Qh(t);g||n(b?{id:typeof b.id=="number"?b.id:Number(b.id),status:b.status||""}:null)}catch{g||n(null)}finally{g||l(!1)}})(),()=>{g=!0}},[t]);const x=async()=>{if(!(!t||!window.confirm("Cancel this Form 16 submission? The request will be marked as rejected."))){d("cancel");try{await ky(t),G.success("Submission cancelled"),a==null||a()}catch(g){G.error(g instanceof Error?g.message:"Failed to cancel submission")}finally{d(null)}}},u=async()=>{if(!(!t||!window.confirm("Mark this submission as resubmission needed? The dealer will need to resubmit Form 16."))){d("resubmit");try{await Ry(t),G.success("Marked as resubmission needed"),a==null||a()}catch(g){G.error(g instanceof Error?g.message:"Failed to update")}finally{d(null)}}};return i||!m||p?null:e.jsxs(Z,{className:"border-blue-200 bg-blue-50/30","data-testid":"form16-quick-actions-card",children:[e.jsxs(oe,{className:"pb-2",children:[e.jsxs(ce,{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 or mark resubmission needed."})]}),e.jsxs(te,{className:"space-y-2",children:[e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start border-red-300 text-red-700 hover:bg-red-50",onClick:x,disabled:!!o,children:[o==="cancel"?e.jsx(Ke,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(jt,{className:"w-3 h-3 mr-1"}),"Cancel submission"]}),e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start border-amber-300 text-amber-700 hover:bg-amber-50",onClick:u,disabled:!!o,children:[o==="resubmit"?e.jsx(Ke,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(hh,{className:"w-3 h-3 mr-1"}),"Resubmission needed"]})]})]})}const IT=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 _r({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(De,{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&&IT(t.fileType)&&s&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>s({fileName:t.name,fileType:t.fileType,documentId:t.documentId,fileSize:t.sizeBytes}),title:"Preview file","data-testid":`${n}-preview-btn`,children:e.jsx(Nt,{className:"w-4 h-4"})}),a&&e.jsx(E,{variant:"ghost",size:"sm",onClick:async()=>{if(!t.documentId){alert("Document ID not available");return}try{await a(t.documentId)}catch{alert("Failed to download document")}},title:"Download file","data-testid":`${n}-download-btn`,children:e.jsx(At,{className:"w-4 h-4"})})]})]})}function ET({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l,isSpectator:o=!1}){var c,m,p,x;const d=((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:[d&&((m=(c=t==null?void 0:t.form16Submission)==null?void 0:c.previousDocuments)==null?void 0:m.length)>0&&e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-sm sm:text-base text-amber-800",children:[e.jsx(De,{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 (",(p=t==null?void 0:t.form16Submission)==null?void 0:p.financialYear," ",(x=t==null?void 0:t.form16Submission)==null?void 0:x.quarter,")"]})]}),e.jsx(te,{children:e.jsx("div",{className:"space-y-4",children:(()=>{const u=new Map;for(const g of t.form16Submission.previousDocuments){const b=g.requestId||g.request_id,f=g.requestNumber||b;u.has(f)||u.set(f,[]),u.get(f).push(g)}return Array.from(u.entries()).map(([g,b])=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600",children:["Request ",g]}),e.jsx("div",{className:"space-y-2 pl-2 border-l-2 border-amber-200",children:b.map((f,j)=>{const y=f.documentId??f.document_id,v=f.originalFileName??f.original_file_name??f.fileName??f.file_name??"Document",w=Number(f.fileSize??f.file_size??0),S=w>0?(w/(1024*1024)).toFixed(2)+" MB":"—";return e.jsx(_r,{document:{documentId:y,name:v,fileType:f.fileType??f.file_type??"",size:S,sizeBytes:w,uploadedBy:f.uploadedBy??f.uploaded_by,uploadedAt:f.uploadedAt??f.uploaded_at},onPreview:C=>i(C),onDownload:l,testId:"form16-previous-document"},y||j)})})]},g))})()})})]}),e.jsxs(Z,{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(ce,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(De,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),d?"Current submission":"Request Documents"]}),e.jsx(ye,{className:"text-xs sm:text-sm mt-1",children:d?"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(E,{size:"sm",onClick:n,disabled:a||t.status==="closed"||o,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(te,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((u,g)=>e.jsx(_r,{document:u,onPreview:b=>i(b),onDownload:l,testId:"request-document"},g))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-documents",children:"No documents uploaded yet"})})]}),!d&&e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Vs,{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(te,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((u,g)=>e.jsx(_r,{document:{documentId:u.attachmentId||"",name:u.name,fileType:u.type||"",size:u.size?`${(u.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:u.size,uploadedBy:u.uploadedBy,uploadedAt:u.uploadedAt},onPreview:b=>i(b),onDownload:async b=>{const{downloadWorkNoteAttachment:f}=require("@/services/workflowApi");await f(b)},testId:"worknote-attachment"},u.attachmentId||g))}):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 _T=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"}}},Rx=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:ts,iconColor:"text-gray-600"};case"in-review":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"in-review",icon:Et,iconColor:"text-blue-600"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:$e,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected",icon:Ct,iconColor:"text-red-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-300",label:"closed",icon:$e,iconColor:"text-gray-600"};case"skipped":return{color:"bg-orange-100 text-orange-800 border-orange-200",label:"skipped",icon:Bt,iconColor:"text-orange-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:ts,iconColor:"text-gray-600"}}},MT=t=>{switch(t){case"approval":case"approved":return e.jsx($e,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(Ct,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(Vs,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(Et,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(qi,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(De,{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(Qi,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(ts,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(Bt,{className:"w-5 h-5 text-gray-600"})}};function LT(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||"",b=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:b}),u.creditNoteNumber){const f=u.creditNoteIssueDate?new Date(u.creditNoteIssueDate).toISOString():b;a.push({type:"status_change",action:"Credit note issued",details:`Credit note ${u.creditNoteNumber} issued for previous submission (${g}).`,timestamp:f})}}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||""||"",d=(s.displayStatus||"").toLowerCase(),c=!!(s.ocrExtractedData&&typeof s.ocrExtractedData=="object"&&Object.keys(s.ocrExtractedData).length>0),m=!!s.creditNoteNumber,p=d==="balance mismatch"||l==="failed"&&!m||l==="failed"&&/mismatch|26as|value/i.test(o),x=d==="duplicate"||l==="duplicate";if(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:c?"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"||m?"26AS matching completed.":"26AS matching was performed.",timestamp:i}),m){const u=s.creditNoteIssueDate?new Date(s.creditNoteIssueDate).toISOString():i;a.push({type:"status_change",action:"Credit note issued",details:`Credit note ${s.creditNoteNumber} issued for this submission.`,timestamp:u})}return a.sort((u,g)=>new Date(u.timestamp).getTime()-new Date(g.timestamp).getTime())}function OT({request:t}){const s=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",a=s?LT(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,d=l.timestamp?new Date(l.timestamp).getTime():0;return o-d}):r;return e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Bt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(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(te,{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:MT(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(Bt,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No activity recorded yet"}),e.jsx("p",{className:"text-xs text-gray-400 mt-2",children:"Actions and updates will appear here"})]})})})]})}function l0({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(ut,{className:"sm:max-w-md",children:[e.jsx(gt,{children:e.jsxs(xt,{className:"flex items-center gap-2",children:[a?e.jsx($e,{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($e,{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(Ct,{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(It,{children:e.jsx(E,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function o0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=h.useState(""),[l,o]=h.useState(!1),[d,c]=h.useState([]),[m,p]=h.useState(!1),[x,u]=h.useState(null),g=h.useRef(null),b=h.useRef(null),[f,j]=h.useState({open:!1,type:"error",email:"",message:""}),[y,v]=h.useState({open:!1,violations:[]}),[w,S]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});h.useEffect(()=>{t&&(async()=>{var _;try{const A=await ma("WORKFLOW_SHARING"),z=await ma("TAT_SETTINGS"),F=[...A,...z],O={};F.forEach(P=>{O[P.configKey]=P.configValue}),S({maxApprovalLevels:parseInt(O.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(O.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((_=O.ALLOW_ADD_SPECTATOR)==null?void 0:_.toLowerCase())==="true",maxSpectators:parseInt(O.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(A){console.error("Failed to load system policy:",A)}})()},[t]);const C=async()=>{var k,R;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 A=r.find(V=>(V.email||"").toLowerCase()===N);if(A){const V=((k=A.participantType)==null?void 0:k.toUpperCase())||"PARTICIPANT",M=A.name||N;if(V==="INITIATOR"){j({open:!0,type:"error",email:N,message:`${M} is the request initiator and cannot be added as a spectator.`});return}else if(V==="APPROVER"){j({open:!0,type:"error",email:N,message:`${M} is already an approver on this request and cannot be added as a spectator.`});return}else if(V==="SPECTATOR"){j({open:!0,type:"error",email:N,message:`${M} is already a spectator on this request.`});return}else{j({open:!0,type:"error",email:N,message:`${M} is already a participant on this request.`});return}}const z=[];w.allowSpectators||z.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const O=r.filter(V=>(V.participantType||"").toUpperCase()==="SPECTATOR").length;O>=w.maxSpectators&&z.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:O,maxValue:w.maxSpectators});const P=r.length+1;if(P>w.maxParticipants&&z.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:P,maxValue:w.maxParticipants}),z.length>0){v({open:!0,violations:z});return}if(!x||x.email.toLowerCase()!==N)try{const M=((R=(await ya(N,1)).data)==null?void 0:R.data)||[];if(M.length===0){j({open:!0,type:"not-found",email:N,message:""});return}const L=M[0];await ba({userId:L.userId,email:L.email,displayName:L.displayName,firstName:L.firstName,lastName:L.lastName,department:L.department,phone:L.phone,mobilePhone:L.mobilePhone,designation:L.designation,jobTitle:L.jobTitle,manager:L.manager,employeeId:L.employeeId,employeeNumber:L.employeeNumber,secondEmail:L.secondEmail,location:L.location})}catch(V){console.error("Failed to validate spectator:",V),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(V){console.error("Failed to add spectator:",V)}finally{o(!1)}},I=()=>{l||(i(""),u(null),c([]),p(!1),s())};h.useEffect(()=>{d.length>0&&b.current&&b.current.scrollTo({top:b.current.scrollHeight,behavior:"smooth"})},[d.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){c([]),p(!1);return}p(!0),g.current=setTimeout(async()=>{var _;try{const A=N.slice(1),F=((_=(await ya(A,10)).data)==null?void 0:_.data)||[];c(F)}catch(A){console.error("Search failed:",A),c([])}finally{p(!1)}},300)},T=async N=>{try{await ba({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),c([]),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(pt,{open:t,onOpenChange:I,children:[e.jsxs(ut,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:I,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(gt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center",children:e.jsx(Nt,{className:"w-5 h-5 text-purple-600"})}),e.jsx(xt,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:b,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a spectator to this request. They will receive notifications but cannot approve or reject."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(el,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(ke,{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||d.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..."}):d.length>0?e.jsx("ul",{className:"divide-y",children:d.map(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>T(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(os,{className:"h-8 w-8",children:e.jsx(cs,{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(E,{type:"button",variant:"outline",onClick:I,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:C,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(pt,{open:f.open,onOpenChange:N=>j(_=>({..._,open:N})),children:e.jsxs(ut,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(xt,{className:"flex items-center gap-2",children:f.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[f.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:f.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Zi,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),f.type==="error"&&e.jsxs(e.Fragment,{children:[f.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:f.email}),"."]}),f.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:f.message})})]})]})})]}),e.jsx(It,{children:e.jsx(E,{onClick:()=>j(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(ni,{open:y.open,onClose:()=>v({open:!1,violations:[]}),violations:y.violations,policyDetails:{maxApprovalLevels:w.maxApprovalLevels,maxParticipants:w.maxParticipants,allowSpectators:w.allowSpectators,maxSpectators:w.maxSpectators}})]})}function c0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,d]=h.useState(""),[c,m]=h.useState(24),[p,x]=h.useState(null),[u,g]=h.useState(!1),[b,f]=h.useState([]),[j,y]=h.useState(!1),[v,w]=h.useState(null),S=h.useRef(null),C=h.useRef(null),[I,D]=h.useState({open:!1,type:"error",email:"",message:""}),T=n.filter(R=>R&&(R.status==="approved"||R.status==="rejected"||R.status==="skipped")),N=Math.max(1,T.length+1),_=Math.max(1,n.length+1),A=_>=N?Array.from({length:_-N+1},(R,V)=>N+V):[N];h.useEffect(()=>{A.length>0&&p===null&&x(A[0]||null)},[A.length,p]);const z=async()=>{var H,X;const R=o.trim().toLowerCase();if(!R){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(R)){D({open:!0,type:"error",email:R,message:"Please enter a valid email address"});return}if(!c||c<=0){D({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(c>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(J=>J.levelNumber),0):0,L=p>M?p:M+1;if(i&&L>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${p} would result in ${L} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:L,maxValue:i}]):D({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${M} level(s).`});return}const U=r.find(J=>(J.email||"").toLowerCase()===R);if(U){const J=((H=U.participantType)==null?void 0:H.toUpperCase())||"PARTICIPANT",$=U.name||R;if(J==="INITIATOR"){D({open:!0,type:"error",email:R,message:`${$} is the request initiator and cannot be added as an approver.`});return}else if(J==="APPROVER"){D({open:!0,type:"error",email:R,message:`${$} is already an approver on this request.`});return}else if(J==="SPECTATOR"){D({open:!0,type:"error",email:R,message:`${$} 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:R,message:`${$} is already a participant on this request.`});return}}if(!v||v.email.toLowerCase()!==R)try{const $=((X=(await ya(R,1)).data)==null?void 0:X.data)||[];if($.length===0){D({open:!0,type:"not-found",email:R,message:""});return}const B=$[0];await ba({userId:B.userId,email:B.email,displayName:B.displayName,firstName:B.firstName,lastName:B.lastName,department:B.department,phone:B.phone,mobilePhone:B.mobilePhone,designation:B.designation,jobTitle:B.jobTitle,manager:B.manager,employeeId:B.employeeId,employeeNumber:B.employeeNumber,secondEmail:B.secondEmail,location:B.location})}catch(J){console.error("Failed to validate approver:",J),D({open:!0,type:"error",email:R,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(R,c,p),d(""),m(24),x(null),w(null),s()}catch(J){console.error("Failed to add approver:",J)}finally{g(!1)}},F=()=>{u||(d(""),m(24),x(null),w(null),f([]),y(!1),s())},O=R=>{const V=R.toLowerCase();return V==="approved"?e.jsx($e,{className:"w-4 h-4 text-green-600"}):V==="rejected"?e.jsx(Ct,{className:"w-4 h-4 text-red-600"}):V==="skipped"?e.jsx(Ze,{className:"w-4 h-4 text-orange-600"}):V==="in-review"||V==="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(()=>{b.length>0&&C.current&&C.current.scrollTo({top:C.current.scrollHeight,behavior:"smooth"})},[b.length]),h.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const P=R=>{if(d(R),v&&v.email.toLowerCase()!==R.toLowerCase()&&w(null),S.current&&clearTimeout(S.current),!R||!R.startsWith("@")||R.length<2){f([]),y(!1);return}y(!0),S.current=setTimeout(async()=>{var V;try{const M=R.slice(1),U=((V=(await ya(M,10)).data)==null?void 0:V.data)||[];f(U)}catch(M){console.error("Search failed:",M),f([])}finally{y(!1)}},300)},k=async R=>{try{await ba({userId:R.userId,email:R.email,displayName:R.displayName,firstName:R.firstName,lastName:R.lastName,department:R.department,phone:R.phone,mobilePhone:R.mobilePhone,designation:R.designation,jobTitle:R.jobTitle,manager:R.manager,employeeId:R.employeeId,employeeNumber:R.employeeNumber,secondEmail:R.secondEmail,location:R.location}),d(R.email),w(R),f([]),y(!1)}catch(V){console.error("Failed to ensure user exists:",V),D({open:!0,type:"error",email:R.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(pt,{open:t,onOpenChange:F,children:[e.jsxs(ut,{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(gt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Zt,{className:"w-5 h-5 text-blue-600"})}),e.jsx(xt,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:C,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(R=>R.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ae,{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(R=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${R.status==="approved"?"bg-green-100 border border-green-200":R.status==="rejected"?"bg-red-100 border border-red-200":R.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:R.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:R.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[R.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[O(R.status),e.jsx(re,{variant:"outline",className:`text-xs ${R.status==="approved"?"bg-green-50 text-green-700 border-green-300":R.status==="rejected"?"bg-red-50 text-red-700 border-red-300":R.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:R.status})]})]},R.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(ae,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(He,{value:(p==null?void 0:p.toString())||"",onValueChange:R=>x(Number(R)),disabled:u,children:[e.jsx(Ge,{className:"h-11 border-gray-300",children:e.jsx(We,{placeholder:"Select level"})}),e.jsx(Ye,{children:A.map(R=>e.jsx(Q,{value:R.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 ",R]}),R<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",R,")"]})]})},R))})]}),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(ae,{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(ke,{type:"number",min:"1",max:"720",value:c,onChange:R=>m(Number(R.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(el,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(ke,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:R=>P(R.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(j||b.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:j?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):b.length>0?e.jsx("ul",{className:"divide-y",children:b.map(R=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>k(R),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(os,{className:"h-8 w-8",children:e.jsx(cs,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(R.displayName||R.email).split(" ").map(V=>V[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:R.displayName||[R.firstName,R.lastName].filter(Boolean).join(" ")||R.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:R.email}),R.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:R.designation})]})]})},R.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:F,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:z,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!o.trim()||!p||!c,children:[e.jsx(Zt,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${p||"?"}`]})]})]}),e.jsx(pt,{open:I.open,onOpenChange:R=>D(V=>({...V,open:R})),children:e.jsxs(ut,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(xt,{className:"flex items-center gap-2",children:I.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:[I.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:I.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(Zi,{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."]})})]}),I.type==="error"&&e.jsxs(e.Fragment,{children:[I.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:I.email}),"."]}),I.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:I.message})})]})]})})]}),e.jsx(It,{children:e.jsx(E,{onClick:()=>D(R=>({...R,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const $T=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"}},UT=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},BT=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 Pa(s)},VT=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",Dx=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(De,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(gh,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(De,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(De,{className:`${s} text-blue-600`}):a.includes("image")||a.includes("png")||a.includes("jpg")||a.includes("jpeg")||a.includes("gif")||a.includes("webp")?e.jsx(bi,{className:`${s} text-purple-600`}):e.jsx(Qi,{className:`${s} text-gray-600`})};function d0({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:d=[],onAddApprover:c,maxApprovalLevels:m,onPolicyViolation:p}){const x=Oa(),u=t||x.requestId||"",[g,b]=h.useState(""),[f,j]=h.useState(""),[y,v]=h.useState(!1),[w,S]=h.useState([]),[C,I]=h.useState(!1),[D,T]=h.useState([]),[N,_]=h.useState(null),[A,z]=h.useState(null),[F,O]=h.useState(!1),[P,k]=h.useState(!1),[R,V]=h.useState(!1),[M,L]=h.useState({success:!0,title:"",message:""}),U=h.useRef(null),H=h.useRef(null),X=h.useRef(null),J=h.useRef(!1),[$,B]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[K,se]=h.useState({open:!1,errors:[]}),Y=h.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[ee,me]=h.useState([]),Se=ee.filter(ne=>ne.status==="online"),Je=w.filter(ne=>ne.content.toLowerCase().includes(f.toLowerCase())||ne.user.name.toLowerCase().includes(f.toLowerCase())),Ve=h.useMemo(()=>o!==void 0?o:!N||ee.length===0?!1:ee.some(ne=>{const Ie=ne.userId||ne.user_id,le=(ne.role||"").toString().toUpperCase(),Xe=(ne.participantType||ne.participant_type||"").toString().toUpperCase();return Ie===N&&(le==="SPECTATOR"||Xe==="SPECTATOR")}),[o,N,ee]);h.useEffect(()=>{},[ee]),h.useEffect(()=>{!u||!N||s||(async()=>{try{const ne=await tn(u),Ie=Array.isArray(ne)?ne.map(le=>{const Xe=le.userId||le.user_id;return{id:le.noteId||le.id||String(Math.random()),user:{name:le.userName||"User",avatar:(le.userName||"U").slice(0,2).toUpperCase(),role:le.userRole||"Participant"},content:le.message||"",timestamp:le.createdAt||new Date().toISOString(),isCurrentUser:Xe===N,attachments:Array.isArray(le.attachments)?le.attachments.map(ze=>({attachmentId:ze.attachmentId||ze.attachment_id,name:ze.fileName||ze.file_name||ze.name,fileName:ze.fileName||ze.file_name||ze.name,url:ze.storageUrl||ze.storage_url||ze.url||"#",type:ze.fileType||ze.file_type||ze.type||"file",fileType:ze.fileType||ze.file_type||ze.type||"file",fileSize:ze.fileSize||ze.file_size})):void 0}}):[];S(Ie)}catch(ne){console.error("[WorkNoteChat] Failed to load messages:",ne)}})()},[u,N,s]);const Ee=h.useMemo(()=>{const ne=[];return w.forEach(Ie=>{Ie.attachments&&Ie.attachments.length>0&&Ie.attachments.forEach(le=>{ne.push({attachmentId:le.attachmentId||le.attachment_id,name:le.fileName||le.file_name||le.name||"Untitled",fileName:le.fileName||le.file_name||le.name||"Untitled",size:le.fileSize||le.file_size,type:le.fileType||le.file_type||le.type||"file",uploadedBy:Ie.user.name,uploadedAt:Ie.timestamp,url:le.storageUrl||le.storage_url||le.url||"#"})})}),ne},[w]);h.useEffect(()=>{i&&Ee.length>=0&&i(Ee)},[Ee,i]);const Oe=h.useMemo(()=>ee.map(ne=>({email:(ne.email||"").toLowerCase(),participantType:ne.role==="Initiator"?"INITIATOR":ne.role==="Approver"?"APPROVER":ne.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:ne.name})),[ee]),ie=ne=>{if(!ne)return"Participant";switch(ne.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return ne.charAt(0).toUpperCase()+ne.slice(1).toLowerCase()}},ge=()=>{var ne;(ne=U.current)==null||ne.scrollIntoView({behavior:"smooth"})};h.useEffect(()=>{ge()},[w]);const we=ne=>{switch(ne.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return ne.charAt(0).toUpperCase()+ne.slice(1).toLowerCase()}};h.useEffect(()=>{J.current||u&&(async()=>{try{const ne=await Ps(u),Ie=Array.isArray(ne==null?void 0:ne.participants)?ne.participants:[];if(Ie.length===0)return;const le=Ie.map(Qe=>{const rt=Qe.participantType||Qe.participant_type||"participant",qe=Qe.userId||Qe.user_id||"";return{name:Qe.userName||Qe.user_name||Qe.user_email||Qe.userEmail||"User",avatar:(Qe.userName||Qe.user_name||Qe.user_email||"U").toString().split(" ").map(ct=>ct[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:we(rt.toString()),status:"offline",email:Qe.userEmail||Qe.user_email||"",permissions:["read","write","mention"],userId:qe}});J.current=!0,me(le);let Xe=0;const ze=3,tt=()=>{X.current&&X.current.connected?(X.current.emit("request:online-users",{requestId:u}),Xe++,Xe()=>{u&&(J.current=!1)},[u]),h.useEffect(()=>{const ne=localStorage.getItem("userData");if(ne)try{const Ie=JSON.parse(ne),le=(Ie==null?void 0:Ie.id)||(Ie==null?void 0:Ie.userId)||(Ie==null?void 0:Ie.user_id)||null;_(le)}catch(Ie){console.error("[WorkNoteChat] Failed to parse userData:",Ie)}},[]),h.useEffect(()=>{(async()=>{try{const Ie=await ma("DOCUMENT_POLICY"),le={};Ie.forEach(Qe=>{le[Qe.configKey]=Qe.configValue});const Xe=parseInt(le.MAX_FILE_SIZE_MB||"10"),tt=(le.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Qe=>Qe.trim().toLowerCase());B({maxFileSizeMB:Xe,allowedFileTypes:tt})}catch(Ie){console.error("Failed to load document policy:",Ie)}})()},[]),h.useEffect(()=>{if(!N)return;let ne=u;return(async()=>{var Ie;try{const le=await Ps(u);(Ie=le==null?void 0:le.workflow)!=null&&Ie.requestId&&(ne=le.workflow.requestId)}catch{}try{const le=an();r?me(yt=>yt.map(Ft=>Ft.userId===N?{...Ft,status:"online"}:Ft)):(bo(le,ne,N),me(yt=>yt.map(Ft=>Ft.userId===N?{...Ft,status:"online"}:Ft)));const Xe=yt=>{const mt=(yt==null?void 0:yt.note)||yt;if(!mt)return;const Ft=mt.noteId||mt.id;S(Ss=>{if(Ss.some(Lt=>Lt.id===Ft))return Ss;const ss=mt.userName||mt.user_name||"User",$a=mt.userRole||mt.user_role,Ua=ie($a),ur=mt.userId||mt.user_id,va={id:Ft||String(Date.now()),user:{name:ss,avatar:ss.split(" ").map(Lt=>Lt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ua},content:mt.message||"",timestamp:mt.createdAt||new Date().toISOString(),isCurrentUser:ur===N,attachments:Array.isArray(mt.attachments)?mt.attachments.map(Lt=>({attachmentId:Lt.attachmentId||Lt.attachment_id,name:Lt.fileName||Lt.file_name||Lt.name,fileName:Lt.fileName||Lt.file_name||Lt.name,url:Lt.storageUrl||Lt.storage_url||Lt.url||"#",type:Lt.fileType||Lt.file_type||Lt.type||"file",fileType:Lt.fileType||Lt.file_type||Lt.type||"file",fileSize:Lt.fileSize||Lt.file_size})):void 0};return[...Ss,va]})},ze=yt=>{me(mt=>mt.length===0||!mt.find(ss=>ss.userId===yt.userId)?mt:mt.map(ss=>ss.userId===yt.userId?{...ss,status:"online"}:ss))},tt=yt=>{yt.userId!==N&&me(mt=>mt.length===0||!mt.find(ss=>ss.userId===yt.userId)?mt:mt.map(ss=>ss.userId===yt.userId?{...ss,status:"offline"}:ss))},Qe=yt=>{me(mt=>mt.length===0?mt:mt.map(Ss=>{const ss=Ss.userId||"";if(ss===N)return{...Ss,status:"online"};const Ua=yt.userIds.includes(ss);return{...Ss,status:Ua?"online":"offline"}}))},rt=()=>{me(yt=>yt.map(Ft=>Ft.userId===N?{...Ft,status:"online"}:Ft)),r||bo(le,ne,N),J.current&&(le.emit("request:online-users",{requestId:ne}),setTimeout(()=>le.emit("request:online-users",{requestId:ne}),300),setTimeout(()=>le.emit("request:online-users",{requestId:ne}),800))},qe=yt=>{console.error("[WorkNoteChat] ❌ Socket error:",yt)},ct=yt=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",yt),me(mt=>mt.map(Ft=>Ft.userId===N?Ft:{...Ft,status:"offline"}))},$s=yt=>{yt.includes("presence")||yt.includes("worknote")||yt.includes("request")};le.on("connect",rt),le.on("disconnect",ct),le.on("error",qe),le.on("worknote:new",Xe),le.on("presence:join",ze),le.on("presence:leave",tt),le.on("presence:online",Qe),le.onAny($s),X.current=le,le.connected&&J.current&&(le.emit("request:online-users",{requestId:ne}),setTimeout(()=>{le.emit("request:online-users",{requestId:ne})},300),setTimeout(()=>{le.emit("request:online-users",{requestId:ne})},800),setTimeout(()=>{le.emit("request:online-users",{requestId:ne})},1500));const ns=()=>{le.off("connect",rt),le.off("disconnect",ct),le.off("error",qe),le.off("worknote:new",Xe),le.off("presence:join",ze),le.off("presence:leave",tt),le.off("presence:online",Qe),le.offAny($s),r||Jh(le,ne),X.current=null};window.__wn_cleanup=ns}catch{}})(),()=>{var Ie;try{(Ie=window.__wn_cleanup)==null||Ie.call(window)}catch{}}},[u,N,r]);const Te=async()=>{if(g.trim()||D.length>0){const ne=ot(g),Ie=ne.map(ze=>{const tt=ee.find(Qe=>Qe.name.toLowerCase().includes(ze.toLowerCase()));return tt==null?void 0:tt.userId}).filter(Boolean),le=D.map(ze=>({name:ze.name,url:URL.createObjectURL(ze),type:ze.type.split("/")[1]||"file"})),Xe={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:ne,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:le.length>0?le:void 0,isCurrentUser:!0};if(a)try{await a(g,D)}catch{}else try{await up(u,{message:g,mentions:Ie},D);const ze=await tn(u),tt=Array.isArray(ze)?ze.map(Qe=>{const rt=Qe.userId||Qe.user_id;return{id:Qe.noteId||Qe.id||String(Math.random()),user:{name:Qe.userName||"User",avatar:(Qe.userName||"U").slice(0,2).toUpperCase(),role:Qe.userRole||"Participant"},content:Qe.message||"",timestamp:Qe.createdAt||new Date().toISOString(),isCurrentUser:rt===N,attachments:Array.isArray(Qe.attachments)?Qe.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}}):[];S(tt)}catch{S(ze=>[...ze,Xe])}b(""),T([])}};h.useEffect(()=>{if(s&&Array.isArray(s))try{const Ie=s.filter(le=>(le.type||"").toLowerCase()!=="sla_warning").map(le=>{var ze;if(le.type||le.activityType||le.isSystem)return{id:le.id||`activity-${le.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:le.details||le.action||le.content||"",timestamp:le.timestamp||le.createdAt||le.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const tt=le.userName||le.user_name||((ze=le.user)==null?void 0:ze.name)||"User",Qe=le.userRole||le.user_role,rt=ie(Qe),qe=le.userId||le.user_id;return{id:le.noteId||le.note_id||le.id||String(Math.random()),user:{name:tt,avatar:tt.split(" ").map(ct=>ct[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:rt},content:le.message||le.content||"",timestamp:le.createdAt||le.created_at||le.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(le.attachments)?le.attachments.map(ct=>({attachmentId:ct.attachmentId||ct.attachment_id,name:ct.fileName||ct.file_name||ct.name,fileName:ct.fileName||ct.file_name||ct.name,url:ct.storageUrl||ct.storage_url||ct.url||"#",type:ct.fileType||ct.file_type||ct.type||"file",fileType:ct.fileType||ct.file_type||ct.type||"file",fileSize:ct.fileSize||ct.file_size})):void 0,isCurrentUser:qe===N}}}).sort((le,Xe)=>new Date(le.timestamp).getTime()-new Date(Xe.timestamp).getTime());S(Ie)}catch(ne){console.error("[WorkNoteChat] Error mapping messages:",ne)}else(async()=>{try{const ne=await tn(u),Ie=Array.isArray(ne)?ne.map(le=>{const Xe=le.userName||le.user_name||"User",ze=le.userRole||le.user_role,tt=ie(ze),Qe=le.userId||le.user_id;return{id:le.noteId||le.note_id||le.id||String(Math.random()),user:{name:Xe,avatar:Xe.split(" ").map(rt=>rt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:tt},content:le.message||"",timestamp:le.createdAt||le.created_at||new Date().toISOString(),attachments:Array.isArray(le.attachments)?le.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:Qe===N}}):[];S(Ie)}catch(ne){console.error("[WorkNoteChat] Error loading work notes:",ne)}})()},[s,u,ee]);const de=ne=>{const Ie=$.maxFileSizeMB*1024*1024;if(ne.size>Ie)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${$.maxFileSizeMB}MB. Current size: ${(ne.size/(1024*1024)).toFixed(2)}MB`};const le=ne.name.toLowerCase(),Xe=le.substring(le.lastIndexOf(".")+1);return $.allowedFileTypes.includes(Xe)?{valid:!0}:{valid:!1,reason:`File type "${Xe}" is not allowed. Allowed types: ${$.allowedFileTypes.join(", ")}`}},q=ne=>{if(!ne.target.files||ne.target.files.length===0)return;const Ie=Array.from(ne.target.files),le=[],Xe=[];Ie.forEach(ze=>{const tt=de(ze);tt.valid?Xe.push(ze):le.push({fileName:ze.name,reason:tt.reason||"Unknown validation error"})}),le.length>0&&se({open:!0,errors:le}),Xe.length>0&&(T(ze=>[...ze,...Xe]),Xe.length{T(Ie=>Ie.filter((le,Xe)=>Xe!==ne)),H.current&&(H.current.value="")},Pe=ne=>{b(Ie=>Ie+ne),v(!1)},ve=()=>{var ne;(ne=H.current)==null||ne.click()},Ne=async ne=>{var Ie,le;try{await hp(u,ne);const Xe=await Ps(u),ze=Array.isArray(Xe==null?void 0:Xe.participants)?Xe.participants:[];if(ze.length){const tt=ze.map(Qe=>{const rt=Qe.participantType||Qe.participant_type||"participant",qe=Qe.userId||Qe.user_id||"",ct=Qe.userName||Qe.user_name||Qe.userEmail||Qe.user_email||"User",$s=Qe.userEmail||Qe.user_email||"",ns=ct.split(" ").map(yt=>yt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:ct,avatar:ns,role:we(rt),status:"offline",email:$s,lastSeen:void 0,permissions:["read"],userId:qe}});me(tt),X.current&&X.current.connected&&X.current.emit("request:online-users",{requestId:u})}O(!1),L({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),V(!0)}catch(Xe){throw console.error("Failed to add spectator:",Xe),L({success:!1,title:"Failed to Add Spectator",message:((le=(Ie=Xe==null?void 0:Xe.response)==null?void 0:Ie.data)==null?void 0:le.error)||"Failed to add spectator. Please try again."}),V(!0),Xe}},Ue=async(ne,Ie,le)=>{var Xe,ze;if(c)await c(ne,Ie,le),k(!1);else try{await xp(u,ne,Ie,le);const tt=await Ps(u),Qe=Array.isArray(tt==null?void 0:tt.participants)?tt.participants:[];if(Qe.length){const rt=Qe.map(qe=>{const ct=qe.participantType||qe.participant_type||"participant",$s=qe.userId||qe.user_id||"",ns=qe.userName||qe.user_name||qe.userEmail||qe.user_email||"User",yt=qe.userEmail||qe.user_email||"",mt=ns.split(" ").map(Ft=>Ft[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:ns,avatar:mt,role:we(ct),status:"offline",email:yt,lastSeen:void 0,permissions:["read"],userId:$s}});me(rt),X.current&&X.current.connected&&X.current.emit("request:online-users",{requestId:u})}k(!1),L({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${le} with ${Ie}h TAT`}),V(!0)}catch(tt){throw console.error("Failed to add approver:",tt),L({success:!1,title:"Failed to Add Approver",message:((ze=(Xe=tt==null?void 0:tt.response)==null?void 0:Xe.data)==null?void 0:ze.error)||"Failed to add approver. Please try again."}),V(!0),tt}},nt=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],ot=ne=>{const Ie=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,le=[];let Xe;for(;(Xe=Ie.exec(ne))!==null;)if(Xe[1]){const ze=Xe.index+Xe[0].length,tt=ne.slice(ze),Qe=ne[ze];(tt.startsWith("@")||!Qe||/\s|[.,!?;:]|@/.test(Qe))&&le.push(Xe[1].trim())}return le},Tt=ne=>{ne.key==="Enter"&&!ne.shiftKey&&(ne.preventDefault(),Te())},Mt=(ne,Ie)=>{S(le=>le.map(Xe=>{if(Xe.id===ne){const ze=Xe.reactions||[],tt=ze.find(Qe=>Qe.emoji===Ie);if(tt)if(tt.users.includes("You")){if(tt.users=tt.users.filter(Qe=>Qe!=="You"),tt.users.length===0)return{...Xe,reactions:ze.filter(Qe=>Qe.emoji!==Ie)}}else tt.users.push("You");else ze.push({emoji:Ie,users:["You"]});return{...Xe,reactions:ze}}return Xe}))};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(Vs,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"text-lg sm:text-2xl font-bold text-gray-900",children:"Work Notes"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("p",{className:"text-gray-600 text-sm sm:text-base truncate",children:Y.title}),e.jsx(re,{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:[Se.slice(0,3).map((ne,Ie)=>e.jsx(os,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(cs,{className:"bg-blue-500 text-white text-xs font-semibold",children:ne.avatar})},Ie)),Se.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:["+",Se.length-3]})]})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>I(!C),className:"lg:hidden",children:e.jsx(Zt,{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(ys,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(ke,{placeholder:"Search messages...",value:f,onChange:ne=>j(ne.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:[Je.map(ne=>{const Ie=ne.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${ne.isSystem?"justify-center":Ie?"justify-end":""}`,children:[!ne.isSystem&&!Ie&&e.jsx(os,{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(cs,{className:`text-white font-semibold text-xs sm:text-sm ${ne.user.role==="Initiator"?"bg-green-600":ne.user.role==="Current User"?"bg-blue-500":ne.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:ne.user.avatar})}),e.jsx("div",{className:`${Ie?"max-w-[70%]":"flex-1"} min-w-0 ${ne.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:ne.isSystem?e.jsxs("div",{className:"inline-flex items-center gap-2 sm:gap-3 px-3 sm:px-4 py-1.5 sm:py-2 bg-gray-100 rounded-full",children:[e.jsx(Bt,{className:"w-3 h-3 sm:w-4 sm:h-4 text-gray-500 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm text-gray-700",children:ne.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:gs(ne.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${Ie?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[ne.user.name," ",Ie&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(re,{variant:"outline",className:"text-xs flex-shrink-0",children:ne.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(ne.timestamp)]}),ne.isHighPriority&&e.jsxs(re,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(Db,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${Ie?"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:BT(ne.content)}}),ne.attachments&&ne.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:ne.attachments.map((le,Xe)=>{const ze=le.fileSize||le.file_size,tt=le.fileName||le.file_name||le.name,Qe=le.fileType||le.file_type||le.type||"",rt=le.attachmentId||le.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(Dx,{type:Qe})}),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}),ze&&e.jsx("p",{className:"text-xs text-gray-500",children:VT(ze)})]}),rt&&(()=>{const qe=(Qe||"").toLowerCase();return qe.includes("image")||qe.includes("pdf")||qe.includes("jpg")||qe.includes("jpeg")||qe.includes("png")||qe.includes("gif")})()&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-purple-100 hover:text-purple-600",onClick:qe=>{qe.preventDefault(),qe.stopPropagation();const ct=Lw(rt);z({fileName:tt,fileType:Qe,fileUrl:ct,fileSize:ze,attachmentId:rt})},title:"Preview file",children:e.jsx(Nt,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-blue-100 hover:text-blue-600",onClick:async qe=>{if(qe.preventDefault(),qe.stopPropagation(),!rt){G.error("Cannot download: Attachment ID missing");return}try{await tu(rt)}catch{G.error("Failed to download file")}},title:"Download file",children:e.jsx(At,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Xe)})})}),ne.reactions&&ne.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:[ne.reactions.map((le,Xe)=>e.jsxs("button",{onClick:()=>Mt(ne.id,le.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${le.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:le.emoji}),e.jsx("span",{className:"text-xs font-medium",children:le.users.length})]},Xe)),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>v(!y),children:e.jsx(bs,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!ne.isSystem&&Ie&&e.jsx(os,{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(cs,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:ne.user.avatar})})]},ne.id)}),e.jsx("div",{ref:U})]})}),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:H,onChange:q,className:"hidden",multiple:!0,accept:$.allowedFileTypes.map(ne=>`.${ne}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((ne,Ie)=>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(Dx,{type:ne.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:ne.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(ne.size/1024).toFixed(1)," KB"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>ue(Ie),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"})})]},Ie))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const ne=g.lastIndexOf("@"),Ie=ne>=0;if(!Ie)return null;const le=g.slice(ne+1),Xe=le.trim(),ze=le.endsWith(" "),tt=Xe.length>0,Qe=Xe.includes(" ")&&!ze,rt=ze&&tt;if(!(Ie&&le.length<=20&&!Qe&&!rt))return null;const ct=Xe.toLowerCase(),$s=ee.filter(ns=>ns.userId===N?!1:ct?ns.name.toLowerCase().includes(ct):!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:$s.length>0?$s.map((ns,yt)=>e.jsxs("button",{type:"button",onClick:mt=>{mt.preventDefault(),mt.stopPropagation();const Ft=g.lastIndexOf("@"),Ss=g.slice(0,Ft);b(Ss+"@"+ns.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(os,{className:"h-10 w-10",children:e.jsx(cs,{className:`text-white text-sm font-semibold ${ns.role==="Initiator"?"bg-green-600":ns.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:ns.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:ns.name}),e.jsx("p",{className:"text-xs text-gray-600",children:ns.role})]})]},yt)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:ct?`No participants found matching "${ct}"`:"No other participants available"})})]})})(),e.jsx(Os,{placeholder:Ve?"Spectators cannot send messages":"Type your message... Use @username to mention someone",value:g,onChange:ne=>b(ne.target.value),onKeyPress:Tt,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,disabled:Ve}),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(E,{variant:"ghost",size:"sm",onClick:()=>v(!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:nt.map((ne,Ie)=>e.jsx("button",{onClick:()=>Pe(ne),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:ne,children:ne},Ie))})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-shrink-0",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:ve,disabled:Ve,title:Ve?"Spectators cannot attach files":"Attach file",children:e.jsx(Qi,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>v(!y),disabled:Ve,title:Ve?"Spectators cannot add emojis":"Add emoji",children:e.jsx(Fb,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>b(ne=>ne+"@"),disabled:Ve,title:Ve?"Spectators cannot mention users":"Mention someone",children:e.jsx(el,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto flex-shrink-0",children:[e.jsxs("span",{className:"text-xs text-gray-500 hidden md:inline whitespace-nowrap",children:[g.length,"/2000"]}),e.jsxs(E,{onClick:Te,disabled:!g.trim()&&D.length===0||Ve,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",title:Ve?"Spectators cannot send messages":"Send",children:[e.jsx(ph,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),C&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>I(!1)}),e.jsxs("div",{className:` + `),()=>{f.contains(b)&&f.removeChild(b)}},[s]),e.jsx(e2,{isPresent:s,childRef:i,sizeRef:l,children:h.cloneElement(t,{ref:d})})}const s2=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:d})=>{const c=fc(a2),m=h.useId();let p=!0,x=h.useMemo(()=>(p=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:u=>{c.set(u,!0);for(const g of c.values())if(!g)return;r&&r()},register:u=>(c.set(u,!1),()=>c.delete(u))}),[a,c,r]);return i&&p&&(x={...x}),h.useMemo(()=>{c.forEach((u,g)=>c.set(g,!1))},[a]),h.useEffect(()=>{!a&&!c.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(t2,{isPresent:a,anchorX:o,root:d,children:t})),e.jsx(dl.Provider,{value:x,children:t})};function a2(){return new Map}function xg(t=!0){const s=h.useContext(dl);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 ui=t=>t.key||"";function Su(t){const s=[];return h.Children.forEach(t,a=>{h.isValidElement(a)&&s.push(a)}),s}const ml=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",root:d})=>{const[c,m]=xg(l),p=h.useMemo(()=>Su(t),[t]),x=l&&!c?[]:p.map(ui),u=h.useRef(!0),g=h.useRef(p),b=fc(()=>new Map),[f,j]=h.useState(p),[y,v]=h.useState(p);Np(()=>{u.current=!1,g.current=p;for(let C=0;C{const I=ui(C),D=l&&!c?!1:p===y||x.includes(I),T=()=>{if(b.has(I))b.set(I,!0);else return;let N=!0;b.forEach(_=>{_||(N=!1)}),N&&(S==null||S(),v(g.current),l&&(m==null||m()),r&&r())};return e.jsx(s2,{isPresent:D,initial:!u.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:d,onExitComplete:D?void 0:T,anchorX:o,children:C},I)})})},hg=h.createContext({strict:!1}),Au={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"]},nn={};for(const t in Au)nn[t]={isEnabled:s=>Au[t].some(a=>!!s[a])};function r2(t){for(const s in t)nn[s]={...nn[s],...t[s]}}const n2=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 Vi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||n2.has(t)}let pg=t=>!Vi(t);function i2(t){typeof t=="function"&&(pg=s=>s.startsWith("on")?!Vi(s):t(s))}try{i2(require("@emotion/is-prop-valid").default)}catch{}function l2(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(pg(n)||a===!0&&Vi(n)||!s&&!Vi(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const ul=h.createContext({});function xl(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Hn(t){return typeof t=="string"||Array.isArray(t)}const Bc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Vc=["initial",...Bc];function hl(t){return xl(t.animate)||Vc.some(s=>Hn(t[s]))}function gg(t){return!!(hl(t)||t.variants)}function o2(t,s){if(hl(t)){const{initial:a,animate:r}=t;return{initial:a===!1||Hn(a)?a:void 0,animate:Hn(r)?r:void 0}}return t.inherit!==!1?s:{}}function c2(t){const{initial:s,animate:a}=o2(t,h.useContext(ul));return h.useMemo(()=>({initial:s,animate:a}),[Tu(s),Tu(a)])}function Tu(t){return Array.isArray(t)?t.join(" "):t}const Wn={};function d2(t){for(const s in t)Wn[s]=t[s],Ac(s)&&(Wn[s].isCSSVariable=!0)}function fg(t,{layout:s,layoutId:a}){return fn.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!Wn[t]||t==="opacity")}const m2={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},u2=gn.length;function x2(t,s,a){let r="",n=!0;for(let i=0;i({style:{},transform:{},transformOrigin:{},vars:{}});function bg(t,s,a){for(const r in s)!Ls(s[r])&&!fg(r,a)&&(t[r]=s[r])}function h2({transformTemplate:t},s){return h.useMemo(()=>{const a=Hc();return zc(a,s,t),Object.assign({},a.vars,a.style)},[s])}function p2(t,s){const a=t.style||{},r={};return bg(r,a,t),Object.assign(r,h2(t,s)),r}function g2(t,s){const a={},r=p2(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 f2={offset:"stroke-dashoffset",array:"stroke-dasharray"},b2={offset:"strokeDashoffset",array:"strokeDasharray"};function j2(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?f2:b2;t[i.offset]=it.transform(-r);const l=it.transform(s),o=it.transform(a);t[i.array]=`${l} ${o}`}function jg(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},d,c,m){if(zc(t,o,c),d){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&&j2(p,n,i,l,!1)}const yg=()=>({...Hc(),attrs:{}}),vg=t=>typeof t=="string"&&t.toLowerCase()==="svg";function y2(t,s,a,r){const n=h.useMemo(()=>{const i=yg();return jg(i,s,vg(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};bg(i,t.style,t),n.style={...i,...n.style}}return n}const v2=["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 Wc(t){return typeof t!="string"||t.includes("-")?!1:!!(v2.indexOf(t)>-1||/[A-Z]/u.test(t))}function N2(t,s,a,{latestValues:r},n,i=!1){const o=(Wc(t)?y2:g2)(s,r,n,t),d=l2(s,typeof t=="string",i),c=t!==h.Fragment?{...d,...o,ref:a}:{},{children:m}=s,p=h.useMemo(()=>Ls(m)?m.get():m,[m]);return h.createElement(t,{...c,children:p})}function ku(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function Gc(t,s,a,r){if(typeof s=="function"){const[n,i]=ku(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]=ku(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Ai(t){return Ls(t)?t.get():t}function w2({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:C2(a,r,n,t),renderState:s()}}function C2(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=Ai(i[x]);let{initial:l,animate:o}=t;const d=hl(t),c=gg(t);s&&c&&!d&&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"&&!xl(p)){const x=Array.isArray(p)?p:[p];for(let u=0;u(s,a)=>{const r=h.useContext(ul),n=h.useContext(dl),i=()=>w2(t,s,r,n);return a?i():fc(i)};function Yc(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(Ls(r[l])||s.style&&Ls(s.style[l])||fg(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const S2=Ng({scrapeMotionValuesFromProps:Yc,createRenderState:Hc});function wg(t,s,a){const r=Yc(t,s,a);for(const n in t)if(Ls(t[n])||Ls(s[n])){const i=gn.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const A2=Ng({scrapeMotionValuesFromProps:wg,createRenderState:yg}),T2=Symbol.for("motionComponentSymbol");function Yr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function k2(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):Yr(a)&&(a.current=r))},[s])}const Kc=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),R2="framerAppearId",Cg="data-"+Kc(R2),Sg=h.createContext({});function D2(t,s,a,r,n){var b,f;const{visualElement:i}=h.useContext(ul),l=h.useContext(hg),o=h.useContext(dl),d=h.useContext(Uc).reducedMotion,c=h.useRef(null);r=r||l.renderer,!c.current&&r&&(c.current=r(t,{visualState:s,parent:i,props:a,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:d}));const m=c.current,p=h.useContext(Sg);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&F2(c.current,a,n,p);const x=h.useRef(!1);h.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const u=a[Cg],g=h.useRef(!!u&&!((b=window.MotionHandoffIsComplete)!=null&&b.call(window,u))&&((f=window.MotionHasOptimisedAnimation)==null?void 0:f.call(window,u)));return Np(()=>{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 F2(t,s,a,r){const{layoutId:n,layout:i,drag:l,dragConstraints:o,layoutScroll:d,layoutRoot:c,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:Ag(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&Yr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:d,layoutRoot:c})}function Ag(t){if(t)return t.options.allowProjection!==!1?t.projection:Ag(t.parent)}function Ul(t,{forwardMotionProps:s=!1}={},a,r){a&&r2(a);const n=Wc(t)?A2:S2;function i(o,d){let c;const m={...h.useContext(Uc),...o,layoutId:P2(o)},{isStatic:p}=m,x=c2(o),u=n(o,p);if(!p&&bc){I2();const g=E2(m);c=g.MeasureLayout,x.visualElement=D2(t,u,m,r,g.ProjectionNode)}return e.jsxs(ul.Provider,{value:x,children:[c&&x.visualElement?e.jsx(c,{visualElement:x.visualElement,...m}):null,N2(t,o,k2(u,x.visualElement,d),u,p,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=h.forwardRef(i);return l[T2]=t,l}function P2({layoutId:t}){const s=h.useContext(gc).id;return s&&t!==void 0?s+"-"+t:t}function I2(t,s){h.useContext(hg).strict}function E2(t){const{drag:s,layout:a}=nn;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 _2(t,s){if(typeof Proxy>"u")return Ul;const a=new Map,r=(i,l)=>Ul(i,l,t,s),n=(i,l)=>r(i,l);return new Proxy(n,{get:(i,l)=>l==="create"?r:(a.has(l)||a.set(l,Ul(l,void 0,t,s)),a.get(l))})}function Tg({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function M2({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function L2(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 Bl(t){return t===void 0||t===1}function Po({scale:t,scaleX:s,scaleY:a}){return!Bl(t)||!Bl(s)||!Bl(a)}function Sr(t){return Po(t)||kg(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function kg(t){return Ru(t.x)||Ru(t.y)}function Ru(t){return t&&t!=="0%"}function zi(t,s,a){const r=t-a,n=s*r;return a+n}function Du(t,s,a,r,n){return n!==void 0&&(t=zi(t,n,r)),zi(t,a,r)+s}function Io(t,s=0,a=1,r,n){t.min=Du(t.min,s,a,r,n),t.max=Du(t.max,s,a,r,n)}function Rg(t,{x:s,y:a}){Io(t.x,s.translate,s.scale,s.originPoint),Io(t.y,a.translate,a.scale,a.originPoint)}const Fu=.999999999999,Pu=1.0000000000001;function O2(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,l;for(let o=0;oFu&&(s.x=1),s.yFu&&(s.y=1)}function Kr(t,s){t.min=t.min+s,t.max=t.max+s}function Iu(t,s,a,r,n=.5){const i=rs(t.min,t.max,n);Io(t,s,a,i,r)}function Qr(t,s){Iu(t.x,s.x,s.scaleX,s.scale,s.originX),Iu(t.y,s.y,s.scaleY,s.scale,s.originY)}function Dg(t,s){return Tg(L2(t.getBoundingClientRect(),s))}function $2(t,s,a){const r=Dg(t,a),{scroll:n}=s;return n&&(Kr(r.x,n.offset.x),Kr(r.y,n.offset.y)),r}const Eu=()=>({translate:0,scale:1,origin:0,originPoint:0}),Xr=()=>({x:Eu(),y:Eu()}),_u=()=>({min:0,max:0}),us=()=>({x:_u(),y:_u()}),Eo={current:null},Fg={current:!1};function U2(){if(Fg.current=!0,!!bc)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>Eo.current=t.matches;t.addEventListener("change",s),s()}else Eo.current=!1}const B2=new WeakMap;function V2(t,s,a){for(const r in s){const n=s[r],i=a[r];if(Ls(n))t.addValue(r,n);else if(Ls(i))t.addValue(r,rn(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,rn(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Mu=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class z2{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=_c,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=Js.now();this.renderScheduledAtthis.bindToMotionValue(n,r)),Fg.current||U2(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Eo.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),cr(this.notifyUpdate),cr(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=fn.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&qt.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 nn){const a=nn[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):us()}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=rn(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"&&(wp(r)||Sp(r))?r=parseFloat(r):!JC(r)&&dr.test(a)&&(r=ig(s,a)),this.setBaseTarget(s,Ls(r)?r.get():r)),Ls(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=Gc(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&&!Ls(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 wc),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){Oc.render(this.render)}}class Pg extends z2{constructor(){super(...arguments),this.KeyframeResolver=$C}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;Ls(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function Ig(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 H2(t){return window.getComputedStyle(t)}class W2 extends Pg{constructor(){super(...arguments),this.type="html",this.renderInstance=Ig}readValueFromInstance(s,a){var r;if(fn.has(a))return(r=this.projection)!=null&&r.isProjecting?So(a):rC(s,a);{const n=H2(s),i=(Ac(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return Dg(s,a)}build(s,a,r){zc(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return Yc(s,a,r)}}const Eg=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 G2(t,s,a,r){Ig(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(Eg.has(n)?n:Kc(n),s.attrs[n])}class Y2 extends Pg{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=us}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(fn.has(a)){const r=ng(a);return r&&r.default||0}return a=Eg.has(a)?a:Kc(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return wg(s,a,r)}build(s,a,r){jg(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){G2(s,a,r,n)}mount(s){this.isSVGTag=vg(s.tagName),super.mount(s)}}const K2=(t,s)=>Wc(t)?new Y2(s):new W2(s,{allowProjection:t!==h.Fragment});function sn(t,s,a){const r=t.getProps();return Gc(r,s,a!==void 0?a:r.custom,t)}const _o=t=>Array.isArray(t);function Q2(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,rn(a))}function X2(t){return _o(t)?t[t.length-1]||0:t}function J2(t,s){const a=sn(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=X2(i[l]);Q2(t,l,o)}}function Z2(t){return!!(Ls(t)&&t.add)}function Mo(t,s){const a=t.getValue("willChange");if(Z2(a))return a.add(s);if(!a&&Ka.WillChange){const r=new Ka.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function _g(t){return t.props[Cg]}const q2=t=>t!==null;function eS(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(q2),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const tS={type:"spring",stiffness:500,damping:25,restSpeed:10},sS=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),aS={type:"keyframes",duration:.8},rS={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},nS=(t,{keyframes:s})=>s.length>2?aS:fn.has(t)?t.startsWith("scale")?sS(s[1]):tS:rS;function iS({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:l,repeatDelay:o,from:d,elapsed:c,...m}){return!!Object.keys(m).length}const Qc=(t,s,a,r={},n,i)=>l=>{const o=Mc(r,t)||{},d=o.delay||r.delay||0;let{elapsed:c=0}=r;c=c-Ia(d);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-c,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};iS(o)||Object.assign(m,nS(t,m)),m.duration&&(m.duration=Ia(m.duration)),m.repeatDelay&&(m.repeatDelay=Ia(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let p=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(Do(m),m.delay===0&&(p=!0)),(Ka.instantAnimations||Ka.skipAnimations)&&(p=!0,Do(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,p&&!i&&s.get()!==void 0){const x=eS(m.keyframes,o);if(x!==void 0){qt.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new Ec(m):new TC(m)};function lS({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function Mg(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const d=[],c=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||c&&lS(c,m))continue;const u={delay:a,...Mc(i||{},m)},g=p.get();if(g!==void 0&&!p.isAnimating&&!Array.isArray(x)&&x===g&&!u.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const j=_g(t);if(j){const y=window.MotionHandoffAnimation(j,m,qt);y!==null&&(u.startTime=y,b=!0)}}Mo(t,m),p.start(Qc(m,p,x,t.shouldReduceMotion&&sg.has(m)?{type:!1}:u,t,b));const f=p.animation;f&&d.push(f)}return l&&Promise.all(d).then(()=>{qt.update(()=>{l&&J2(t,l)})}),d}function Lg(t,s,a,r=0,n=1){const i=Array.from(t).sort((c,m)=>c.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 Lo(t,s,a={}){var d;const r=sn(t,s,a.type==="exit"?(d=t.presenceContext)==null?void 0:d.custom:void 0);let{transition:n=t.getDefaultTransition()||{}}=r||{};a.transitionOverride&&(n=a.transitionOverride);const i=r?()=>Promise.all(Mg(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:m=0,staggerChildren:p,staggerDirection:x}=n;return oS(t,s,c,m,p,x,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[c,m]=o==="beforeChildren"?[i,l]:[l,i];return c().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function oS(t,s,a=0,r=0,n=0,i=1,l){const o=[];for(const d of t.variantChildren)d.notify("AnimationStart",s),o.push(Lo(d,s,{...l,delay:a+(typeof r=="function"?0:r)+Lg(t.variantChildren,d,r,n,i)}).then(()=>d.notify("AnimationComplete",s)));return Promise.all(o)}function cS(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>Lo(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=Lo(t,s,a);else{const n=typeof s=="function"?sn(t,s,a.custom):s;r=Promise.all(Mg(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function Og(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})=>cS(t,a,r)))}function hS(t){let s=xS(t),a=Lu(),r=!0;const n=d=>(c,m)=>{var x;const p=sn(t,m,d==="exit"?(x=t.presenceContext)==null?void 0:x.custom:void 0);if(p){const{transition:u,transitionEnd:g,...b}=p;c={...c,...b,...g}}return c};function i(d){s=d(t)}function l(d){const{props:c}=t,m=$g(t.parent)||{},p=[],x=new Set;let u={},g=1/0;for(let f=0;fg&&w,T=!1;const N=Array.isArray(v)?v:[v];let _=N.reduce(n(j),{});S===!1&&(_={});const{prevResolvedValues:A={}}=y,z={...A,..._},F=k=>{D=!0,x.has(k)&&(T=!0,x.delete(k)),y.needsAnimating[k]=!0;const R=t.getValue(k);R&&(R.liveStyle=!1)};for(const k in z){const R=_[k],V=A[k];if(u.hasOwnProperty(k))continue;let M=!1;_o(R)&&_o(V)?M=!Og(R,V):M=R!==V,M?R!=null?F(k):x.add(k):R!==void 0&&x.has(k)?F(k):y.protectedKeys[k]=!0}y.prevProp=v,y.prevResolvedValues=_,y.isActive&&(u={...u,..._}),r&&t.blockInitialAnimation&&(D=!1);const O=C&&I;D&&(!O||T)&&p.push(...N.map(k=>{const R={type:j};if(typeof k=="string"&&r&&!O&&t.manuallyAnimateOnMount&&t.parent){const{parent:V}=t,M=sn(V,k);if(V.enteringChildren&&M){const{delayChildren:L}=M.transition||{};R.delay=Lg(V.enteringChildren,t,L)}}return{animation:k,options:R}}))}if(x.size){const f={};if(typeof c.initial!="boolean"){const j=sn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);j&&j.transition&&(f.transition=j.transition)}x.forEach(j=>{const y=t.getBaseTarget(j),v=t.getValue(j);v&&(v.liveStyle=!0),f[j]=y??null}),p.push({animation:f})}let b=!!p.length;return r&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(b=!1),r=!1,b?s(p):Promise.resolve()}function o(d,c){var p;if(a[d].isActive===c)return Promise.resolve();(p=t.variantChildren)==null||p.forEach(x=>{var u;return(u=x.animationState)==null?void 0:u.setActive(d,c)}),a[d].isActive=c;const m=l(d);for(const x in a)a[x].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=Lu()}}}function pS(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!Og(s,t):!1}function vr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Lu(){return{animate:vr(!0),whileInView:vr(),whileHover:vr(),whileTap:vr(),whileDrag:vr(),whileFocus:vr(),exit:vr()}}class mr{constructor(s){this.isMounted=!1,this.node=s}update(){}}class gS extends mr{constructor(s){super(s),s.animationState||(s.animationState=hS(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();xl(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 fS=0;class bS extends mr{constructor(){super(...arguments),this.id=fS++}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 jS={animation:{Feature:gS},exit:{Feature:bS}};function Gn(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function ri(t){return{point:{x:t.pageX,y:t.pageY}}}const yS=t=>s=>$c(s)&&t(s,ri(s));function Mn(t,s,a,r){return Gn(t,s,yS(a),r)}const Ug=1e-4,vS=1-Ug,NS=1+Ug,Bg=.01,wS=0-Bg,CS=0+Bg;function Bs(t){return t.max-t.min}function SS(t,s,a){return Math.abs(t-s)<=a}function Ou(t,s,a,r=.5){t.origin=r,t.originPoint=rs(s.min,s.max,t.origin),t.scale=Bs(a)/Bs(s),t.translate=rs(a.min,a.max,t.origin)-t.originPoint,(t.scale>=vS&&t.scale<=NS||isNaN(t.scale))&&(t.scale=1),(t.translate>=wS&&t.translate<=CS||isNaN(t.translate))&&(t.translate=0)}function Ln(t,s,a,r){Ou(t.x,s.x,a.x,r?r.originX:void 0),Ou(t.y,s.y,a.y,r?r.originY:void 0)}function $u(t,s,a){t.min=a.min+s.min,t.max=t.min+Bs(s)}function AS(t,s,a){$u(t.x,s.x,a.x),$u(t.y,s.y,a.y)}function Uu(t,s,a){t.min=s.min-a.min,t.max=t.min+Bs(s)}function On(t,s,a){Uu(t.x,s.x,a.x),Uu(t.y,s.y,a.y)}function pa(t){return[t("x"),t("y")]}const Vg=({current:t})=>t?t.ownerDocument.defaultView:null,Bu=(t,s)=>Math.abs(t-s);function TS(t,s){const a=Bu(t.x,s.x),r=Bu(t.y,s.y);return Math.sqrt(a**2+r**2)}class zg{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=zl(this.lastMoveEventInfo,this.history),u=this.startEvent!==null,g=TS(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!u&&!g)return;const{point:b}=x,{timestamp:f}=Fs;this.history.push({...b,timestamp:f});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=Vl(u,this.transformPagePoint),qt.update(this.updatePoint,!0)},this.handlePointerUp=(x,u)=>{this.end();const{onEnd:g,onSessionEnd:b,resumeAnimation:f}=this.handlers;if(this.dragSnapToOrigin&&f&&f(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const j=zl(x.type==="pointercancel"?this.lastMoveEventInfo:Vl(u,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,j),b&&b(x,j)},!$c(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=ri(s),d=Vl(o,this.transformPagePoint),{point:c}=d,{timestamp:m}=Fs;this.history=[{...c,timestamp:m}];const{onSessionStart:p}=a;p&&p(s,zl(d,this.history)),this.removeListeners=ti(Mn(this.contextWindow,"pointermove",this.handlePointerMove),Mn(this.contextWindow,"pointerup",this.handlePointerUp),Mn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),cr(this.updatePoint)}}function Vl(t,s){return s?{point:s(t.point)}:t}function Vu(t,s){return{x:t.x-s.x,y:t.y-s.y}}function zl({point:t},s){return{point:t,delta:Vu(t,Hg(s)),offset:Vu(t,kS(s)),velocity:RS(s,.1)}}function kS(t){return t[0]}function Hg(t){return t[t.length-1]}function RS(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=Hg(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>Ia(s)));)a--;if(!r)return{x:0,y:0};const i=ga(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 DS(t,{min:s,max:a},r){return s!==void 0&&ta&&(t=r?rs(a,t,r.max):Math.min(t,a)),t}function zu(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 FS(t,{top:s,left:a,bottom:r,right:n}){return{x:zu(t.x,a,n),y:zu(t.y,s,r)}}function Hu(t,s){let a=s.min-t.min,r=s.max-t.max;return s.max-s.minr?a=Bn(s.min,s.max-r,t.min):r>n&&(a=Bn(t.min,t.max-n,s.min)),Ya(0,1,a)}function ES(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 Oo=.35;function _S(t=Oo){return t===!1?t=0:t===!0&&(t=Oo),{x:Wu(t,"left","right"),y:Wu(t,"top","bottom")}}function Wu(t,s,a){return{min:Gu(t,s),max:Gu(t,a)}}function Gu(t,s){return typeof t=="number"?t:t[s]||0}const MS=new WeakMap;class LS{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=us(),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(ri(p).point)},l=(p,x)=>{const{drag:u,dragPropagation:g,onDragStart:b}=this.getProps();if(u&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=zC(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),pa(j=>{let y=this.getAxisMotionValue(j).get()||0;if(Ea.test(y)){const{projection:v}=this.visualElement;if(v&&v.layout){const w=v.layout.layoutBox[j];w&&(y=Bs(w)*(parseFloat(y)/100))}}this.originPoint[j]=y}),b&&qt.postRender(()=>b(p,x)),Mo(this.visualElement,"transform");const{animationState:f}=this.visualElement;f&&f.setActive("whileDrag",!0)},o=(p,x)=>{this.latestPointerEvent=p,this.latestPanInfo=x;const{dragPropagation:u,dragDirectionLock:g,onDirectionLock:b,onDrag:f}=this.getProps();if(!u&&!this.openDragLock)return;const{offset:j}=x;if(g&&this.currentDirection===null){this.currentDirection=OS(j),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",x.point,j),this.updateAxis("y",x.point,j),this.visualElement.render(),f&&f(p,x)},d=(p,x)=>{this.latestPointerEvent=p,this.latestPanInfo=x,this.stop(p,x),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>pa(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 zg(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:d,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:Vg(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&&qt.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||!xi(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=DS(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&&Yr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=FS(r.layoutBox,s):this.constraints=!1,this.elastic=_S(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&pa(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=ES(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!Yr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=$2(r,n.root,this.visualElement.getTransformPagePoint());let l=PS(n.layout.layoutBox,i);if(a){const o=a(M2(l));this.hasMutatedConstraints=!!o,o&&(l=Tg(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),d=this.constraints||{},c=pa(m=>{if(!xi(m,a,this.currentDirection))return;let p=d&&d[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(c).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return Mo(this.visualElement,s),r.start(Qc(s,r,0,a,this.visualElement,!1))}stopAnimation(){pa(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){pa(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){pa(a=>{const{drag:r}=this.getProps();if(!xi(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]-rs(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!Yr(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};pa(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const d=o.get();n[l]=IS({min:d,max:d},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(),pa(l=>{if(!xi(l,s,null))return;const o=this.getAxisMotionValue(l),{min:d,max:c}=this.constraints[l];o.set(rs(d,c,n[l]))})}addListeners(){if(!this.visualElement.current)return;MS.set(this.visualElement,this);const s=this.visualElement.current,a=Mn(s,"pointerdown",d=>{const{drag:c,dragListener:m=!0}=this.getProps();c&&m&&this.start(d)}),r=()=>{const{dragConstraints:d}=this.getProps();Yr(d)&&d.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,i=n.addEventListener("measure",r);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),qt.read(r);const l=Gn(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:d,hasLayoutChanged:c})=>{this.isDragging&&c&&(pa(m=>{const p=this.getAxisMotionValue(m);p&&(this.originPoint[m]+=d[m].translate,p.set(p.get()+d[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=Oo,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function xi(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function OS(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class $S extends mr{constructor(s){super(s),this.removeGroupControls=fa,this.removeListeners=fa,this.controls=new LS(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||fa}unmount(){this.removeGroupControls(),this.removeListeners()}}const Yu=t=>(s,a)=>{t&&qt.postRender(()=>t(s,a))};class US extends mr{constructor(){super(...arguments),this.removePointerDownListener=fa}onPointerDown(s){this.session=new zg(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Vg(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Yu(s),onStart:Yu(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&qt.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=Mn(this.node.current,"pointerdown",s=>this.onPointerDown(s))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const Ti={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ku(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const Cn={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(it.test(t))t=parseFloat(t);else return t;const a=Ku(t,s.target.x),r=Ku(t,s.target.y);return`${a}% ${r}%`}},BS={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=dr.parse(t);if(n.length>5)return r;const i=dr.createTransformer(t),l=typeof n[0]!="number"?1:0,o=a.x.scale*s.x,d=a.y.scale*s.y;n[0+l]/=o,n[1+l]/=d;const c=rs(o,d,.5);return typeof n[2+l]=="number"&&(n[2+l]/=c),typeof n[3+l]=="number"&&(n[3+l]/=c),i(n)}};let Hl=!1;class VS extends h.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;d2(zS),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),Hl&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Ti.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,Hl=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||qt.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Oc.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;Hl=!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 Wg(t){const[s,a]=xg(),r=h.useContext(gc);return e.jsx(VS,{...t,layoutGroup:r,switchLayoutGroup:h.useContext(Sg),isPresent:s,safeToRemove:a})}const zS={borderRadius:{...Cn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Cn,borderTopRightRadius:Cn,borderBottomLeftRadius:Cn,borderBottomRightRadius:Cn,boxShadow:BS};function HS(t,s,a){const r=Ls(t)?t:rn(t);return r.start(Qc("",r,s,a)),r.animation}const WS=(t,s)=>t.depth-s.depth;class GS{constructor(){this.children=[],this.isDirty=!1}add(s){jc(this.children,s),this.isDirty=!0}remove(s){yc(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(WS),this.isDirty=!1,this.children.forEach(s)}}function YS(t,s){const a=Js.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(cr(r),t(i-s))};return qt.setup(r,!0),()=>cr(r)}const Gg=["TopLeft","TopRight","BottomLeft","BottomRight"],KS=Gg.length,Qu=t=>typeof t=="string"?parseFloat(t):t,Xu=t=>typeof t=="number"||it.test(t);function QS(t,s,a,r,n,i){n?(t.opacity=rs(0,a.opacity??1,XS(r)),t.opacityExit=rs(s.opacity??1,0,JS(r))):i&&(t.opacity=rs(s.opacity??1,a.opacity??1,r));for(let l=0;lrs?1:a(Bn(t,s,r))}function Zu(t,s){t.min=s.min,t.max=s.max}function ha(t,s){Zu(t.x,s.x),Zu(t.y,s.y)}function qu(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function ex(t,s,a,r,n){return t-=s,t=zi(t,1/a,r),n!==void 0&&(t=zi(t,1/n,r)),t}function ZS(t,s=0,a=1,r=.5,n,i=t,l=t){if(Ea.test(s)&&(s=parseFloat(s),s=rs(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=rs(i.min,i.max,r);t===i&&(o-=s),t.min=ex(t.min,s,a,o,n),t.max=ex(t.max,s,a,o,n)}function tx(t,s,[a,r,n],i,l){ZS(t,s[a],s[r],s[n],s.scale,i,l)}const qS=["x","scaleX","originX"],eA=["y","scaleY","originY"];function sx(t,s,a,r){tx(t.x,s,qS,a?a.x:void 0,r?r.x:void 0),tx(t.y,s,eA,a?a.y:void 0,r?r.y:void 0)}function ax(t){return t.translate===0&&t.scale===1}function Kg(t){return ax(t.x)&&ax(t.y)}function rx(t,s){return t.min===s.min&&t.max===s.max}function tA(t,s){return rx(t.x,s.x)&&rx(t.y,s.y)}function nx(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function Qg(t,s){return nx(t.x,s.x)&&nx(t.y,s.y)}function ix(t){return Bs(t.x)/Bs(t.y)}function lx(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class sA{constructor(){this.members=[]}add(s){jc(this.members,s),s.scheduleRender()}remove(s){if(yc(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 aA(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:c,rotate:m,rotateX:p,rotateY:x,skewX:u,skewY:g}=a;c&&(r=`perspective(${c}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,d=t.y.scale*s.y;return(o!==1||d!==1)&&(r+=`scale(${o}, ${d})`),r||"none"}const Wl=["","X","Y","Z"],rA=1e3;let nA=0;function Gl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Xg(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=_g(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",qt,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Xg(r)}function Jg({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=nA++,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(oA),this.nodes.forEach(uA),this.nodes.forEach(xA),this.nodes.forEach(cA)},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 d=0;dthis.root.updateBlockedByResize=!1;qt.read(()=>{p=window.innerWidth}),t(l,()=>{const u=window.innerWidth;u!==p&&(p=u,this.root.updateBlockedByResize=!0,m&&m(),m=YS(x,250),Ti.hasAnimatedSinceResize&&(Ti.hasAnimatedSinceResize=!1,this.nodes.forEach(dx)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&c&&(o||d)&&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||c.getDefaultTransition()||bA,{onLayoutAnimationStart:b,onLayoutAnimationComplete:f}=c.getProps(),j=!this.targetLayout||!Qg(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 v={...Mc(g,"layout"),onPlay:b,onComplete:f};(c.shouldReduceMotion||this.options.layoutRoot)&&(v.delay=0,v.type=!1),this.startAnimation(v),this.setAnimationOrigin(m,y)}else p||dx(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(),cr(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(hA),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&&Xg(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&&!Bs(this.snapshot.measuredBox.x)&&!Bs(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 d=0;d{const S=w/1e3;mx(p.x,l.x,S),mx(p.y,l.y,S),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(On(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),gA(this.relativeTarget,this.relativeTargetOrigin,x,S),v&&tA(this.relativeTarget,v)&&(this.isProjectionDirty=!1),v||(v=us()),ha(v,this.relativeTarget)),b&&(this.animationValues=m,QS(m,c,this.latestValues,S,y,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=S},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,d,c;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(c=(d=this.resumingFrom)==null?void 0:d.currentAnimation)==null||c.stop(),this.pendingAnimation&&(cr(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=qt.update(()=>{Ti.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=rn(0)),this.currentAnimation=HS(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(rA),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:d,layout:c,latestValues:m}=l;if(!(!o||!d||!c)){if(this!==l&&this.layout&&c&&Zg(this.options.animationType,this.layout.layoutBox,c.layoutBox)){d=this.target||us();const p=Bs(this.layout.layoutBox.x);d.x.min=l.target.x.min,d.x.max=d.x.min+p;const x=Bs(this.layout.layoutBox.y);d.y.min=l.target.y.min,d.y.max=d.y.min+x}ha(o,d),Qr(o,m),Ln(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new sA),this.sharedNodes.get(l).add(o);const c=o.options.initialPromotionConfig;o.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.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:d}={}){const c=this.getStack();c&&c.promote(this,d),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:d}=l;if((d.z||d.rotate||d.rotateX||d.rotateY||d.rotateZ||d.skewX||d.skewY)&&(o=!0),!o)return;const c={};d.z&&Gl("z",l,c,this.animationValues);for(let m=0;m{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(ox),this.root.sharedNodes.clear()}}}function iA(t){t.updateLayout()}function lA(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"?pa(p=>{const x=l?s.measuredBox[p]:s.layoutBox[p],u=Bs(x);x.min=r[p].min,x.max=x.min+u}):Zg(i,s.layoutBox,r)&&pa(p=>{const x=l?s.measuredBox[p]:s.layoutBox[p],u=Bs(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=Xr();Ln(o,r,s.layoutBox);const d=Xr();l?Ln(d,t.applyTransform(n,!0),s.measuredBox):Ln(d,r,s.layoutBox);const c=!Kg(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=us();On(g,s.layoutBox,x.layoutBox);const b=us();On(b,r,u.layoutBox),Qg(g,b)||(m=!0),p.options.layoutRoot&&(t.relativeTarget=b,t.relativeTargetOrigin=g,t.relativeParent=p)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:d,layoutDelta:o,hasLayoutChanged:c,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function oA(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 cA(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function dA(t){t.clearSnapshot()}function ox(t){t.clearMeasurements()}function cx(t){t.isLayoutDirty=!1}function mA(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function dx(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function uA(t){t.resolveTargetDelta()}function xA(t){t.calcProjection()}function hA(t){t.resetSkewAndRotation()}function pA(t){t.removeLeadSnapshot()}function mx(t,s,a){t.translate=rs(s.translate,0,a),t.scale=rs(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function ux(t,s,a,r){t.min=rs(s.min,a.min,r),t.max=rs(s.max,a.max,r)}function gA(t,s,a,r){ux(t.x,s.x,a.x,r),ux(t.y,s.y,a.y,r)}function fA(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const bA={duration:.45,ease:[.4,0,.1,1]},xx=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),hx=xx("applewebkit/")&&!xx("chrome/")?Math.round:fa;function px(t){t.min=hx(t.min),t.max=hx(t.max)}function jA(t){px(t.x),px(t.y)}function Zg(t,s,a){return t==="position"||t==="preserve-aspect"&&!SS(ix(s),ix(a),.2)}function yA(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const vA=Jg({attachResizeListener:(t,s)=>Gn(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Yl={current:void 0},qg=Jg({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Yl.current){const t=new vA({});t.mount(window),t.setOptions({layoutScroll:!0}),Yl.current=t}return Yl.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),NA={pan:{Feature:US},drag:{Feature:$S,ProjectionNode:qg,MeasureLayout:Wg}};function gx(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&&qt.postRender(()=>i(s,ri(s)))}class wA extends mr{mount(){const{current:s}=this.node;s&&(this.unmount=HC(s,(a,r)=>(gx(this.node,r,"Start"),n=>gx(this.node,n,"End"))))}unmount(){}}class CA extends mr{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=ti(Gn(this.node.current,"focus",()=>this.onFocus()),Gn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function fx(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&&qt.postRender(()=>i(s,ri(s)))}class SA extends mr{mount(){const{current:s}=this.node;s&&(this.unmount=KC(s,(a,r)=>(fx(this.node,r,"Start"),(n,{success:i})=>fx(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const $o=new WeakMap,Kl=new WeakMap,AA=t=>{const s=$o.get(t.target);s&&s(t)},TA=t=>{t.forEach(AA)};function kA({root:t,...s}){const a=t||document;Kl.has(a)||Kl.set(a,{});const r=Kl.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(TA,{root:t,...s})),r[n]}function RA(t,s,a){const r=kA(s);return $o.set(t,a),r.observe(t),()=>{$o.delete(t),r.unobserve(t)}}const DA={some:0,all:1};class FA extends mr{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:DA[n]},o=d=>{const{isIntersecting:c}=d;if(this.isInView===c||(this.isInView=c,i&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:m,onViewportLeave:p}=this.node.getProps(),x=c?m:p;x&&x(d)};return RA(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(PA(s,a))&&this.startObserver()}unmount(){}}function PA({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const IA={inView:{Feature:FA},tap:{Feature:SA},focus:{Feature:CA},hover:{Feature:wA}},EA={layout:{ProjectionNode:qg,MeasureLayout:Wg}},_A={...jS,...IA,...NA,...EA},Wt=_2(_A,K2),Sn=[{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:mh,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 MA({open:t,onClose:s,onSelectTemplate:a}){var c,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=Sn.find(g=>g.id===x);u!=null&&u.disabled||n(x)},d=()=>{r&&(a(r),s())};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(ut,{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(xt,{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(ws,{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(Wt.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(Ji,{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:Sn.map((x,u)=>{const g=x.icon,b=r===x.id,f=i||x.disabled;return e.jsx(Wt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:u*.1},whileHover:f?{}:{scale:1.03},whileTap:f?{}:{scale:.98},children:e.jsxs(Z,{className:`h-full transition-all duration-300 border-2 ${f?"opacity-50 cursor-not-allowed border-gray-200":b?"cursor-pointer border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"cursor-pointer border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>o(x.id),children:[e.jsxs(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"})}),b&&e.jsx(Wt.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(Wa,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(ce,{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(te,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(re,{variant:"secondary",className:"text-xs",children:x.category})}),e.jsx(Jt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(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(es,{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($e,{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(Wt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"flex flex-col sm:flex-row justify-center gap-4 mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(E,{onClick:d,disabled:!r||i||((c=Sn.find(x=>x.id===r))==null?void 0:c.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=Sn.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(ml,{children:r&&e.jsx(Wt.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=Sn.find(x=>x.id===r))==null?void 0:p.name})]})})})]})})]})})}function Or({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[d,c]=h.useState(100),[m,p]=h.useState(0),[x,u]=h.useState(null),[g,b]=h.useState(!1),[f,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"),v=s.toLowerCase().includes("pdf"),w=y||v;h.useEffect(()=>{if(!l||!w||!a){u(null);return}return(async()=>{b(!0),j(null);try{let A=a;a.startsWith("/")&&!a.startsWith("//")&&(A=`${window.location.origin}${a}`);const F=await fetch(A,{headers:{Accept:v?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!F.ok){const k=await F.text().catch(()=>"");throw new Error(`Failed to load file: ${F.status} ${F.statusText}. ${k}`)}const O=await F.blob();if(O.size===0)throw new Error("File is empty or could not be loaded");v&&!O.type.includes("pdf")&&O.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${O.type}`);const P=window.URL.createObjectURL(O);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{b(!1)}})(),()=>{x&&(window.URL.revokeObjectURL(x),u(null))}},[l,a,w,v]);const S=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},C=()=>c(T=>Math.min(T+25,200)),I=()=>c(T=>Math.max(T-25,50)),D=()=>p(T=>(T+90)%360);return e.jsx(pt,{open:l,onOpenChange:o,children:e.jsx(ut,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(gt,{className:"pb-4 flex-shrink-0 pr-8",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(Nt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(xt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`• ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[y&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:I,disabled:d<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(Tb,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[d,"%"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:C,disabled:d>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(kb,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:D,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(uh,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(E,{variant:"outline",size:"sm",onClick:S,className:"gap-2 h-9",children:[e.jsx(At,{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(Ke,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):f?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(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:f}),i&&n&&e.jsxs(E,{onClick:S,className:"gap-2",children:[e.jsx(At,{className:"h-4 w-4"}),"Download ",t]})]}):w&&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(${d/100}) rotate(${m}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),v&&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(Nt,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),i&&n&&e.jsxs(E,{onClick:S,className:"gap-2",children:[e.jsx(At,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function ni({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(ut,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(xt,{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(It,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const ma=async t=>{const s=t?{category:t}:{};return(await be.get("/users/configurations",{params:s})).data.data},pl=async t=>{const s=t?{category:t}:{};return(await be.get("/admin/configurations",{params:s})).data.data},Us=async(t,s)=>{await be.put(`/admin/configurations/${t}`,{configValue:s})},LA=async t=>{await be.post(`/admin/configurations/${t}/reset`)},OA=async()=>{const t=await be.get("/admin/form16-config");return t.data.data??t.data},$A=async t=>{await be.put("/admin/form16-config",t)},UA=async t=>{const s=t?{year:t}:{};return(await be.get("/admin/holidays",{params:s})).data.data},BA=async t=>(await be.post("/admin/holidays",t)).data.data,VA=async(t,s)=>(await be.put(`/admin/holidays/${t}`,s)).data.data,zA=async t=>{await be.delete(`/admin/holidays/${t}`)},HA=async()=>(await be.get("/config/activity-types")).data.data,WA=async t=>{const s={activeOnly:t.toString()};return(await be.get("/admin/activity-types",{params:s})).data.data},GA=async t=>(await be.post("/admin/activity-types",t)).data.data,YA=async(t,s)=>(await be.put(`/admin/activity-types/${t}`,s)).data.data,KA=async t=>{await be.delete(`/admin/activity-types/${t}`)},QA={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 XA(t,s,a){const[r,n]=h.useState(QA),[i,l]=h.useState(null),[o,d]=h.useState(t),[c,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 ma("DOCUMENT_POLICY"),v={};y.forEach(_=>{v[_.configKey]=_.configValue});const w=parseInt(v.MAX_FILE_SIZE_MB||"10"),C=(v.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(_=>_.trim().toLowerCase());x({maxFileSizeMB:w,allowedFileTypes:C});const I=await ma("SYSTEM_SETTINGS"),D=await ma("WORKFLOW_SHARING"),T=[...I,...D],N={};T.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 f=!0;return(async()=>{try{d(!0);const j=await Ps(s);if(!f||!j)return;const y=j.workflow||{},v=Array.isArray(j.approvals)?j.approvals:[],w=Array.isArray(j.participants)?j.participants:[],S=Array.isArray(j.documents)?j.documents.filter(A=>!A.isDeleted):[];g(S);const C=(y.priority||"").toString().toLowerCase(),I={standard:"standard",express:"express"},D=y.templateType==="TEMPLATE"?"existing-template":"custom",T=a.find(A=>A.id===D)||a[0]||null;l(T);const N=v.sort((A,z)=>(A.levelNumber||0)-(z.levelNumber||0)).map(A=>{const z=Number(A.tatHours||24),F=Math.floor(z/24),O=z%24;return{id:A.approverId||`temp-${A.levelNumber}`,name:A.approverName||A.approverEmail||"",email:A.approverEmail||"",role:A.levelName||`Level ${A.levelNumber}`,department:"",avatar:(A.approverName||A.approverEmail||"XX").substring(0,2).toUpperCase(),level:A.levelNumber||1,canClose:!1,tat:F>0?F:O,tatType:F>0?"days":"hours",userId:A.approverId}}),_=w.filter(A=>(A.participantType||A.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(A.userEmail||A.user_email||A.email):!1).map((A,z)=>{const F=A.userId||A.user_id||A.id,O=A.userName||A.user_name||A.name||"",P=A.userEmail||A.user_email||A.email||"",R=(O||P||"XX").split(" ").map(V=>V[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:F||`spectator-${s}-${z}-${Date.now()}`,userId:F,name:O||P||"Spectator",email:P,role:"Spectator",department:A.department||"",avatar:R,level:1,canClose:!1}});n(A=>({...A,template:D,title:y.title||"",description:y.description||"",priority:I[C]||"standard",approvers:N,approverCount:N.length||1,spectators:_,maxLevel:Math.max(...N.map(z=>z.level||1),1)}))}catch(j){console.error("Failed to load draft:",j)}finally{f&&d(!1)}})(),()=>{f=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(f,j)=>{n(y=>({...y,[f]:j}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:c,documentPolicy:p,existingDocuments:u,setExistingDocuments:g}}const bx=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function JA(t,s,a){const[r,n]=h.useState(t?2:1),i=bx.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:bx,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 ZA(){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 qA(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function eT(t,s,a){var n;const r=qA(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 tT(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return eT(a,n,n===s)})}function jx(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 yx(t,s,a,r=!1){const n=tT(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 sT(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 vx(t,s){return{id:(await hc(t,s||[],"SUPPORTING")).id}}async function Nx(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await $w(t,s,a||[],r):await Ow(t,s)}function aT({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[d,c]=h.useState(!1),[m,p]=h.useState(!1);return{submitting:d,savingDraft:m,handleSubmit:async()=>{var b,f;if(d||m)return;const g=sT(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}c(!0);try{if(i&&l){const j=yx(t,n,r,!1);await Nx(l,j,a,r),G.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=jx(t,s,n,!1),y=await vx(j,a);G.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),G.error("Failed to Submit Request",{description:((f=(b=j==null?void 0:j.response)==null?void 0:b.data)==null?void 0:f.message)||(j==null?void 0:j.message)||"An error occurred while submitting the request.",duration:5e3}),c(!1)}},handleSaveDraft:async()=>{var g,b;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(d||m)){p(!0);try{if(i&&l){const f=yx(t,n,r,!0);await Nx(l,f,a,r),G.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const f=jx(t,s,n,!0),j=await vx(f,a);G.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(f){console.error("Failed to save draft:",f),G.error("Failed to Save Draft",{description:((b=(g=f==null?void 0:f.response)==null?void 0:g.data)==null?void 0:b.message)||(f==null?void 0:f.message)||"An error occurred while saving the draft.",duration:5e3}),p(!1)}}}}}async function ya(t,s=10,a="default"){return await be.get("/users/search",{params:{q:t,limit:s,source:a}})}async function ba(t){var a;const s=await be.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function rT(t,s){return await be.post("/admin/users/assign-role",{email:t,role:s})}async function nT(t,s){return await be.put(`/admin/users/${t}/role`,{role:s})}async function iT(t,s=1,a=10){return await be.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function lT(){return await be.get("/admin/users/role-statistics")}async function oT(t){var a;const s=await be.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function cT(){var s,a;return((a=(s=(await be.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const ia={searchUsers:ya,getUserById:oT,ensureUserExists:ba,assignRole:rT,updateUserRole:nT,getUsersByRole:iT,getRoleStatistics:lT,getAllUsers:cT};async function dT(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 ya(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 ba({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 mT(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 T=new Date;T.setDate(T.getDate()+D.suggestedSLA),a("slaEndDate",T),D.id!=="custom"&&D.id!=="existing-template"&&u(`/create-admin-request/${D.id}`)},handleTemplateSelection:D=>{D==="claim-management"?u("/claim-management"):D==="vendor-payment"?u("/vendor-payment"):x&&x({templateType:D})},nextStep:async()=>{var D;if(i()){if(n===1&&(t==null?void 0:t.id)==="existing-template"){b(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&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 T=((D=d==null?void 0:d.email)==null?void 0:D.toLowerCase())||"",N=await mT(r.approvers,T);if(!N.success&&N.error){c(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,T)=>{if(T){const N=D.documentId||D.document_id||"";j({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:hn(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:()=>{f!=null&&f.fileUrl&&(f!=null&&f.file)&&URL.revokeObjectURL(f.fileUrl),j(null)}}}const wx=[{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:Zi,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:De,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let Er=null;const Cx=()=>Er,xT=async t=>{const a=(await be.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 Er&&Er.push(r),r},gl=async()=>{var r;const a=(((r=(await be.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 Er=a,a},hT=async(t,s)=>{const r=(await be.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 Er&&(Er=Er.map(i=>i.id===t?n:i)),n};function e0({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 pT({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:l,submitting:o,savingDraft:d,loadingDraft:c,isEditing:m}){return e.jsx("div",{className:"fixed sm:relative bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0 shadow-lg sm:shadow-none z-50","data-testid":"wizard-footer",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2 sm:gap-4 max-w-6xl mx-auto",children:[e.jsxs(E,{variant:"outline",onClick:r,disabled:t===1,size:"sm",className:"sm:size-lg order-2 sm:order-1","data-testid":"wizard-footer-prev-button",children:[e.jsx(ws,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Previous"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 order-1 sm:order-2","data-testid":"wizard-footer-actions",children:[e.jsx(E,{variant:"outline",onClick:l,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:c||o||d,"data-testid":"wizard-footer-save-draft-button",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),e.jsx("span",{children:m?"Updating...":"Saving..."})]}):e.jsx("span",{children:m?"Update Draft":"Save Draft"})}),t===s?e.jsx(E,{onClick:i,disabled:!a||c||o||d,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(Ke,{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(xh,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(E,{onClick:n,disabled:!a,size:"sm",className:"sm:size-lg flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-next-button",children:[e.jsx("span",{className:"hidden sm:inline",children:"Next Step"}),e.jsx("span",{className:"sm:hidden",children:"Next"}),e.jsx(fs,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const Sx=t=>{switch(t){case"high":return e.jsx(Ra,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(es,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(zs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(es,{className:"w-4 h-4 text-gray-600"})}};function gT({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var c;const[n,i]=h.useState("main"),l=Cs(),o=m=>{m.id==="admin-templates-category"?i("admin"):n==="admin"?l(`/create-admin-request/${m.id}`):a(m)},d=n==="main"?[...t]:r;return e.jsxs(Wt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"min-h-full flex flex-col items-center justify-center py-8","data-testid":"template-selection-step",children:[e.jsxs("div",{className:"text-center mb-12 max-w-3xl","data-testid":"template-selection-header",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4","data-testid":"template-selection-title",children:n==="main"?"Choose Your Request Type":"Organization Templates"}),e.jsx("p",{className:"text-lg text-gray-600","data-testid":"template-selection-description",children:n==="main"?"Start with a pre-built template for faster approvals, or create a custom request tailored to your needs.":"Select a pre-configured workflow template defined by your organization."})]}),n==="admin"&&e.jsx("div",{className:"w-full max-w-6xl mb-6 flex justify-start",children:e.jsxs(E,{variant:"ghost",className:"gap-2",onClick:()=>i("main"),children:[e.jsx(ws,{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:d.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(Rb,{className:"w-12 h-12 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No admin templates available yet."})]}):d.map(m=>{var g;const x=m.id==="admin-templates-category",u=(s==null?void 0:s.id)===m.id;return e.jsx(Wt.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${m.id}`,children:e.jsxs(Z,{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(Wt.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(Wa,{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(ce,{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(re,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),Sx(m.priority)]})]})]}),e.jsxs(te,{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(Jt,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${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(Zt,{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(ml,{children:s&&e.jsx(Wt.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(Z,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Mr,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(te,{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(ae,{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(ae,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[Sx(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(ae,{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(ae,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((c=s.commonApprovers)==null?void 0:c.length)>0?s.commonApprovers.map((m,p)=>e.jsx(re,{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 ke({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 fT({className:t,...s}){return e.jsx(Mf,{"data-slot":"radio-group",className:Me("grid gap-3",t),...s})}function Ax({className:t,...s}){return e.jsx(Lf,{"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(Of,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(Ko,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function bT({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(Wt.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(De,{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(ae,{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(ke,{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(ae,{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(ei,{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(ae,{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(fT,{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(Ax,{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(Xi,{className:"w-4 h-4 text-red-600"}),e.jsx(ae,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(re,{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(Ax,{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(ae,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(re,{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(ae,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(ke,{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(ae,{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(Q,{value:"USD",children:"USD ($)"}),e.jsx(Q,{value:"EUR",children:"EUR (€)"}),e.jsx(Q,{value:"GBP",children:"GBP (£)"}),e.jsx(Q,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(ae,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(ke,{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(ae,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(ke,{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(ae,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(ke,{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 t0(){const[t,s]=h.useState([]),[a,r]=h.useState(!1),n=h.useRef(null);return{searchResults:t,searchLoading:a,searchUsersDebounced:async(d,c=10)=>{if(n.current&&clearTimeout(n.current),!d||!d.startsWith("@")||d.length<2){s([]),r(!1);return}r(!0),n.current=setTimeout(async()=>{var m;try{const p=d.slice(1),u=((m=(await ya(p,c)).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 d=>{try{return await ba({userId:d.userId,email:d.email,displayName:d.displayName,firstName:d.firstName,lastName:d.lastName,department:d.department,phone:d.phone,mobilePhone:d.mobilePhone,designation:d.designation,jobTitle:d.jobTitle,manager:d.manager,employeeId:d.employeeId,employeeNumber:d.employeeNumber,secondEmail:d.secondEmail,location:d.location})}catch(c){throw console.error("Failed to ensure user exists:",c),c}}}}function s0(){const[t,s]=h.useState({}),[a,r]=h.useState({}),n=h.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(o,d,c=10)=>{if(n.current[o]&&clearTimeout(n.current[o]),!d||!d.startsWith("@")||d.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=d.slice(1),u=((m=(await ya(p,c)).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(d=>({...d,[o]:[]})),r(d=>({...d,[o]:!1}))}}}function jT({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var p;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:d}=s0();h.useEffect(()=>{const x=t.approverCount||1,u=t.approvers||[];if(u.lengthx&&s("approvers",u.slice(0,x))},[t.approverCount,s]);const c=(x,u)=>{var j,y,v,w,S;const g=[...t.approvers],f=((j=g[x])==null?void 0:j.email)!==u;if(g[x]={...g[x],email:u,level:x+1,userId:f||(y=g[x])==null?void 0:y.userId,name:f||(v=g[x])==null?void 0:v.name,department:f||(w=g[x])==null?void 0:w.department,avatar:f||(S=g[x])==null?void 0:S.avatar},s("approvers",g),!u||!u.startsWith("@")||u.length<2){d(x);return}o(x,u,10)},m=async(x,u)=>{var g,b;try{if((g=t.approvers)==null?void 0:g.some((w,S)=>{var C,I;return S!==x&&(w.userId===u.userId||((C=w.email)==null?void 0:C.toLowerCase())===((I=u.email)==null?void 0:I.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((b=t.spectators)==null?void 0:b.some(w=>{var S,C;return w.userId===u.userId||((S=w.email)==null?void 0:S.toLowerCase())===((C=u.email)==null?void 0:C.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 ba({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}),v=[...t.approvers];v[x]={...v[x],email:u.email,name:u.displayName||[u.firstName,u.lastName].filter(Boolean).join(" "),userId:y.userId,level:x+1},s("approvers",v),d(x)}catch(f){console.error("Failed to ensure user exists:",f),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(Wt.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(Zt,{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(Z,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(ir,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx(ye,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(te,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(ae,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const x=t.approverCount||1,u=Math.max(1,x-1);s("approverCount",u),t.approvers.length>u&&s("approvers",t.approvers.slice(0,u))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(Qo,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-2xl font-semibold w-12 text-center","data-testid":"approval-workflow-count-display",children:t.approverCount||1}),e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const u=(t.approverCount||1)+1;if(u>r.maxApprovalLevels){n([{type:"Maximum Approval Levels Exceeded",message:`Cannot add more than ${r.maxApprovalLevels} approval levels. Please remove an approver level or contact your administrator.`,currentValue:u,maxValue:r.maxApprovalLevels}]);return}s("approverCount",u)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(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(Z,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(oe,{children:[e.jsxs(ce,{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(te,{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(zt,{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(re,{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,b=g===(t.approverCount||1),f=t.approvers[u]||{email:"",tat:""};return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${g}`,children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-6 bg-gray-300"})}),e.jsx("div",{className:`p-4 rounded-lg border-2 transition-all ${f.email?"border-green-200 bg-green-50":"border-gray-200 bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${f.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:g})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",g]}),b&&e.jsx(re,{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(ae,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),f.email&&f.userId&&e.jsxs(re,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx($e,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(ke,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:f.email||"",onChange:v=>c(u,v.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(v=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(u,v),"data-testid":`approval-workflow-approver-${g}-search-result-${v.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:v.displayName||v.email}),e.jsx("div",{className:"text-xs text-gray-600",children:v.email})]},v.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-tat-field`,children:[e.jsx(ae,{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(ke,{id:`tat-${g}`,type:"number",placeholder:f.tatType==="days"?"7":"24",min:"1",max:f.tatType==="days"?"30":"720",value:f.tat||"",onChange:v=>{const w=[...t.approvers];w[u]={...w[u],tat:parseInt(v.target.value)||"",level:g,tatType:f.tatType||"hours"},s("approvers",w)},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:f.tatType||"hours",onValueChange:v=>{const w=[...t.approvers];w[u]={...w[u],tatType:v,level:g,tat:""},s("approvers",w)},"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(Q,{value:"hours",children:"Hours"}),e.jsx(Q,{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(Mr,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900 mb-1",children:"Approval Flow Summary"}),e.jsxs("p",{className:"text-sm text-blue-700",children:["Your request will follow this sequence: ",e.jsx("strong",{children:"You (Initiator)"})," → ",Array.from({length:t.approverCount||1},(x,u)=>`Level ${u+1} Approver`).join(" → "),". The final approver can close the request."]})]})]})}),e.jsx("div",{className:"p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-lg border border-emerald-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(st,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const j=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+j:b+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),f=(x.tatType||"hours")==="days"?g*24:g;return g?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",u+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[f," ",f===1?"hour":"hours"]})]})},u):null})}),(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const j=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+j*24:b+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 yT({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=h.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:d,clearSearch:c,ensureUser:m}=t0(),p=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){c();return}d(g,10)},x=async g=>{var b,f;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const j=t.spectators.some(v=>{var w,S;return v.userId===g.userId||((w=v.email)==null?void 0:w.toLowerCase())===((S=g.email)==null?void 0:S.toLowerCase())}),y=(b=t.approvers)==null?void 0:b.some(v=>{var w,S;return v.userId===g.userId||((w=v.email)==null?void 0:w.toLowerCase())===((S=g.email)==null?void 0:S.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 v=await m(g),w={id:v.userId,userId:v.userId,name:v.displayName||g.email.split("@")[0],email:v.email,avatar:(v.displayName||v.email).substring(0,2).toUpperCase(),role:"Spectator",department:v.department||"",level:1,canClose:!1},S=[...t.spectators,w];s("spectators",S),i(""),c()}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(v=>{var w;return((w=v.email)==null?void 0:w.toLowerCase())===n.toLowerCase()}),y=(f=t.approvers)==null?void 0:f.some(v=>{var w;return((w=v.email)==null?void 0:w.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 b=t.spectators.filter(f=>f.id!==g);s("spectators",b)};return e.jsxs(Wt.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(Nt,{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(Z,{"data-testid":"participants-spectators-card",children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center justify-between text-base","data-testid":"participants-spectators-title",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nt,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(re,{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(te,{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(ke,{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(E,{size:"sm",onClick:()=>x(),disabled:!n||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n),"data-testid":"participants-spectators-add-button",children:"Add"})]}),e.jsxs("p",{className:"text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded p-2 flex items-center gap-1",children:[e.jsx(Mr,{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(os,{className:"h-6 w-6",children:e.jsx(cs,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(jt,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function vT({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:d,onDocumentErrors:c,fileInputRef:m}){const p=b=>{const f=Array.from(b.target.files||[]);if(f.length===0)return;const j=t.maxFileSizeMB*1024*1024,y=[],v=[];f.forEach(w=>{if(w.size>j){y.push({fileName:w.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(w.size/1048576).toFixed(2)}MB`});return}const S=w.name.toLowerCase(),C=S.substring(S.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(C)){y.push({fileName:w.name,reason:`File type "${C}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}v.push(w)}),v.length>0&&i([...a,...v]),y.length>0&&c&&c(y),b.target&&(b.target.value="")},x=b=>{const f=a.filter((j,y)=>y!==b);i(f)},u=b=>{o([...n,b])},g=(b,f=!1)=>{if(f){const j=(b.fileType||b.file_type||"").toLowerCase(),y=(b.originalFileName||b.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=(b.type||"").toLowerCase(),y=(b.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(Wt.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(Z,{"data-testid":"documents-upload-card",children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(De,{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(te,{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(b=>`.${b}`).join(","),onChange:p,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(E,{variant:"outline",size:"lg",type:"button",onClick:()=>{var b;return(b=m.current)==null?void 0:b.click()},"data-testid":"documents-browse-button",children:[e.jsx(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(b=>b.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(Z,{"data-testid":"documents-existing-card",children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(re,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length," file",r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length!==1?"s":""]})]})}),e.jsx(te,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(b=>{const f=b.documentId||b.document_id||"";return n.includes(f)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${f}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(De,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.originalFileName||b.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:b.fileSize?(Number(b.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!0)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>d(b,!0),"data-testid":`documents-existing-${f}-preview`,children:e.jsx(Nt,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(f),"data-testid":`documents-existing-${f}-delete`,children:e.jsx(jt,{className:"h-4 w-4 text-red-600"})})]})]},f)})})})]}),a.length>0&&e.jsxs(Z,{"data-testid":"documents-new-card",children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(re,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(te,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((b,f)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${f}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(De,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(b.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!1)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>d(b,!1),"data-testid":`documents-new-${f}-preview`,children:e.jsx(Nt,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>x(f),"data-testid":`documents-new-${f}-remove`,children:e.jsx(jt,{className:"h-4 w-4"})})]})]},f))})})]})]})]})}const NT=t=>{switch(t){case"high":return e.jsx(Ra,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(es,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(zs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(es,{className:"w-4 h-4 text-gray-600"})}};function wT({formData:t,selectedTemplate:s}){return e.jsxs(Wt.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($e,{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(Z,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(xh,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(te,{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(ae,{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(re,{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(ae,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[NT(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(ae,{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(ae,{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(Z,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(De,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(te,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(ae,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(Is,{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(Ga,{className:"w-4 h-4 text-blue-600"}),e.jsx(ae,{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(Z,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(Zt,{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(te,{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(re,{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(Z,{"data-testid":"review-submit-participants-card",children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(Nt,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(te,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(ae,{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(re,{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(Z,{"data-testid":"review-submit-documents-card",children:[e.jsxs(oe,{children:[e.jsxs(ce,{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(te,{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(De,{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(Z,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(te,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx($e,{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 CT({isEditing:t,currentStep:s,totalSteps:a,stepNames:r,onBack:n}){return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0","data-testid":"create-request-header",children:e.jsxs("div",{className:"flex items-center justify-between max-w-6xl mx-auto gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-1 min-w-0",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"create-request-back-button",children:e.jsx(ws,{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 ST({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(ml,{mode:"wait",children:t})})})}function AT({modal:t,onClose:s}){return e.jsx(pt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(ut,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsxs(xt,{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(Zi,{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(It,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function TT({modal:t,documentPolicy:s,onClose:a}){return e.jsx(pt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(ut,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(xt,{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(It,{children:e.jsx(E,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function Tx({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Oa(),i=Cs(),l=n.requestId||a||"",o=r&&!!l,{user:d}=ds(),[c,m]=h.useState([]);h.useEffect(()=>{(async()=>{try{const ve=(await gl()).map(Ne=>({id:Ne.id,name:Ne.name,description:Ne.description,category:Ne.category,icon:De,estimatedTime:Ne.estimatedTime,commonApprovers:Ne.approvers.map(Ue=>Ue.name),workflowApprovers:Ne.approvers,suggestedSLA:Ne.suggestedSLA,priority:Ne.priority,fields:Ne.fields||{}}));m(ve)}catch(Pe){console.error("Failed to fetch admin templates:",Pe)}})()},[]);const p=h.useMemo(()=>[...wx,...c],[c]),{formData:x,updateFormData:u,selectedTemplate:g,setSelectedTemplate:b,loadingDraft:f,systemPolicy:j,documentPolicy:y,existingDocuments:v,setExistingDocuments:w}=XA(o,l,p),{currentStep:S,totalSteps:C,stepNames:I,isStepValid:D,nextStep:T,prevStep:N}=JA(o,g,x),[_,A]=h.useState([]),[z,F]=h.useState([]),O=h.useRef(null),{validationModal:P,policyViolationModal:k,documentErrorModal:R,openValidationModal:V,closeValidationModal:M,openPolicyViolationModal:L,closePolicyViolationModal:U,openDocumentErrorModal:H,closeDocumentErrorModal:X}=ZA(),{submitting:J,savingDraft:$,handleSubmit:B,handleSaveDraft:K}=aT({formData:x,selectedTemplate:g,documents:_,documentsToDelete:z,user:d,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:se,setShowTemplateModal:Y,previewDocument:ee,selectTemplate:me,handleTemplateSelection:Se,nextStep:Je,prevStep:Ve,handlePreviewDocument:Ee,closePreview:Oe}=uT({selectedTemplate:g,setSelectedTemplate:b,updateFormData:u,formData:x,currentStep:S,isStepValid:D,wizardNextStep:T,wizardPrevStep:N,user:d,openValidationModal:V,systemPolicy:j,onPolicyViolation:L,onSubmit:s}),ie=h.useCallback(()=>{if(S===1){i("/dashboard",{replace:!0});return}S===3||S===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Ve()},[S,t,i,Ve]),ge=h.useRef(!0),we=h.useRef(!1);h.useEffect(()=>{ge.current&&x.documents&&x.documents.length>0&&!we.current&&(A(x.documents),we.current=!0),ge.current=!1},[x.documents]);const Te=h.useRef(!1),de=h.useRef(_);h.useEffect(()=>{if(Te.current){Te.current=!1,de.current=_;return}de.current!==_&&(u("documents",_),de.current=_)},[_]);const q=()=>{switch(S){case 1:return e.jsx(gT,{templates:wx,selectedTemplate:g,onSelectTemplate:me,adminTemplates:c});case 2:return e.jsx(bT,{formData:x,selectedTemplate:g,updateFormData:u});case 3:return e.jsx(jT,{formData:x,updateFormData:u,systemPolicy:j,onValidationError:ue=>V(ue.type,ue.email,ue.message),onPolicyViolation:L});case 4:return e.jsx(yT,{formData:x,updateFormData:u,onValidationError:ue=>V(ue.type,ue.email,ue.message),initiatorEmail:(d==null?void 0:d.email)||""});case 5:return e.jsx(vT,{documentPolicy:y,isEditing:o,documents:_,existingDocuments:v,documentsToDelete:z,onDocumentsChange:A,onExistingDocumentsChange:w,onDocumentsToDeleteChange:F,onPreviewDocument:Ee,onDocumentErrors:ue=>H(ue),fileInputRef:O});case 6:return e.jsx(wT,{formData:x,selectedTemplate:g});default:return null}};return f?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center","data-testid":"create-request-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading draft..."})]})}):e.jsxs("div",{className:"h-full flex flex-col bg-gradient-to-br from-gray-50 to-white","data-testid":"create-request",children:[e.jsx(CT,{isEditing:o,currentStep:S,totalSteps:C,stepNames:I,onBack:ie}),e.jsx(e0,{currentStep:S,totalSteps:C,stepNames:I}),e.jsx(ST,{children:q()}),e.jsx(pT,{currentStep:S,totalSteps:C,isStepValid:D(),onPrev:Ve,onNext:Je,onSubmit:B,onSaveDraft:K,submitting:J,savingDraft:$,loadingDraft:f,isEditing:o}),e.jsx(MA,{open:se,onClose:()=>Y(!1),onSelectTemplate:Se}),ee&&e.jsx(Or,{fileName:ee.fileName,fileType:ee.fileType,fileUrl:ee.fileUrl,fileSize:ee.fileSize,open:!!ee,onClose:Oe,onDownload:async()=>{if(ee.file){const ue=document.createElement("a");ue.href=ee.fileUrl,ue.download=ee.fileName,document.body.appendChild(ue),ue.click(),document.body.removeChild(ue)}else ee.documentId&&await _s(ee.documentId)},attachmentId:ee.documentId}),e.jsx(AT,{modal:P,onClose:M}),e.jsx(TT,{modal:R,documentPolicy:y,onClose:X}),e.jsx(ni,{open:k.open,onClose:U,violations:k.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}function ii({className:t,...s}){return e.jsx($f,{"data-slot":"tabs",className:Me("flex flex-col gap-2",t),...s})}function li({className:t,...s}){return e.jsx(Uf,{"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 $t({className:t,...s}){return e.jsx(Bf,{"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 Ut({className:t,...s}){return e.jsx(Vf,{"data-slot":"tabs-content",className:Me("flex-1 outline-none",t),...s})}function Yn(t){return t?t.workflowType==="CLAIM_MANAGEMENT"||t.templateType==="claim-management"||t.template==="claim-management"||t.templateName==="Claim Management"||t.templateCode==="CLAIM_MANAGEMENT":!1}function Xc(t,s=[],a){const[r,n]=h.useState(null),[i,l]=h.useState(!1),[o,d]=h.useState(!0),[c,m]=h.useState(null),[p,x]=h.useState(null),[u,g]=h.useState(!1),b=(S,C)=>(S||C||"NA").toString().split(" ").map(D=>D[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),f=S=>{const C=(S||"").toUpperCase();return C==="IN_PROGRESS"?"in-review":C==="PENDING"?"pending":C==="APPROVED"?"approved":C==="REJECTED"?"rejected":C==="CLOSED"?"closed":C==="SKIPPED"?"skipped":(S||"").toLowerCase()},j=h.useCallback(async()=>{var S,C,I,D,T,N,_,A,z,F,O,P,k;l(!0);try{const R=await Hs.getWorkflowDetails(t);if(!R){console.warn("[useRequestDetails] No details returned from API");return}const V=R.workflow||{},M=Array.isArray(R.approvals)?R.approvals:[],L=Array.isArray(R.participants)?R.participants:[],U=Array.isArray(R.documents)?R.documents:[],H=R.summary||{},X=Array.isArray(R.tatAlerts)?R.tatAlerts:[];X.length>0;const J=(H==null?void 0:H.currentLevel)||V.currentLevel||1,$=M.map(q=>{const ue=q.levelNumber||0,Pe=(q.status||"").toString().toUpperCase(),ve=q.levelId||q.level_id;let Ne=f(q.status);ue>J&&Pe!=="APPROVED"&&Pe!=="REJECTED"?Ne="waiting":ue===J&&Pe==="PENDING"&&(Ne="pending");const Ue=X.filter(nt=>nt.levelId===ve);return{step:ue,levelId:ve,role:q.levelName||q.approverName||"Approver",status:Ne,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:Ue,skipReason:q.skipReason||void 0,isSkipped:Pe==="SKIPPED"||q.isSkipped||!1}}),B=L.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:b(q.userName||q.user_name,q.userEmail||q.user_email)})),K=q=>{var Pe,ve;if(!q)return;const ue=L.find(Ne=>Ne.userId===q||Ne.user_id===q);return ue!=null&&ue.userName||ue!=null&&ue.user_name?ue.userName||ue.user_name:V.initiatorId===q?((Pe=V.initiator)==null?void 0:Pe.displayName)||((ve=V.initiator)==null?void 0:ve.email):q},se=U.map(q=>{const ue=Number(q.fileSize||q.file_size||0),Pe=(ue/(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:ue,uploadedBy:K(q.uploadedBy||q.uploaded_by),uploadedAt:q.uploadedAt||q.uploaded_at}}),Y=Array.isArray(R.activities)?R.activities.filter(q=>(q.type||"").toLowerCase()!=="sla_warning"):[];let ee=null;if(V.isPaused||!1)try{ee=await eu(V.requestId)}catch{}let Se=null,Je=null,Ve=null,Ee=null,Oe=[],ie=null;if(Yn(V)){try{const q=await be.get(`/dealer-claims/${V.requestId}/credit-note-wfm`),ue=q.data??q;ie=Array.isArray(ue==null?void 0:ue.data)?ue.data:Array.isArray(ue)?ue:[]}catch(q){console.warn("[useRequestDetails] Error fetching credit note WFM data:",q)}try{const q=await be.get(`/dealer-claims/${V.requestId}`),ue=((S=q.data)==null?void 0:S.data)||q.data;if(ue){Se=ue.claimDetails||ue.claim_details,Je=ue.proposalDetails||ue.proposal_details,Ve=ue.completionDetails||ue.completion_details,Ee=ue.internalOrder||ue.internal_order||null,Oe=ue.internalOrders||ue.internal_orders||[];const Pe=ue.budgetTracking||ue.budget_tracking||null,ve=ue.invoice||null,Ne=ue.creditNote||ue.credit_note||null,Ue=ue.completionExpenses||ue.completion_expenses||null;Se&&(Se.budgetTracking=Pe,Se.invoice=ve,Se.creditNote=Ne,Se.completionExpenses=Ue,Se.creditNoteWfmData=ie)}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:(C=q==null?void 0:q.response)==null?void 0:C.status,statusText:(I=q==null?void 0:q.response)==null?void 0:I.statusText,responseData:(D=q==null?void 0:q.response)==null?void 0:D.data,requestId:V.requestId})}}const ge={...V,id:V.requestNumber||V.requestId,requestId:V.requestId,requestNumber:V.requestNumber,title:V.title,description:V.description,status:f(V.status),priority:(V.priority||"").toString().toLowerCase(),workflowType:V.workflowType||(V.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:$,approvals:M,participants:L,documents:se,spectators:B,summary:H,sla:(H==null?void 0:H.sla)||V.sla||null,initiator:{name:((T=V.initiator)==null?void 0:T.displayName)||((N=V.initiator)==null?void 0:N.email),role:((_=V.initiator)==null?void 0:_.designation)||void 0,department:((A=V.initiator)==null?void 0:A.department)||void 0,email:((z=V.initiator)==null?void 0:z.email)||void 0,phone:((F=V.initiator)==null?void 0:F.phone)||void 0,avatar:b((O=V.initiator)==null?void 0:O.displayName,(P=V.initiator)==null?void 0:P.email)},createdAt:V.createdAt,updatedAt:V.updatedAt,totalSteps:V.totalLevels||1,currentStepRaw:(H==null?void 0:H.currentLevel)||V.currentLevel||1,currentStep:Math.min(Math.max(1,(H==null?void 0:H.currentLevel)||V.currentLevel||1),V.totalLevels||1),auditTrail:Y,conclusionRemark:V.conclusionRemark||null,closureDate:V.closureDate||null,pauseInfo:ee||null,claimDetails:Se||null,proposalDetails:Je||null,completionDetails:Ve||null,internalOrder:Ee||null,internalOrders:Oe||[],budgetTracking:(Se==null?void 0:Se.budgetTracking)||null,invoice:(Se==null?void 0:Se.invoice)||(Se==null?void 0:Se.invoice)||null,creditNote:(Se==null?void 0:Se.creditNote)||null,creditNoteWfmData:ie||(Se==null?void 0:Se.creditNoteWfmData)||null,completionExpenses:(Se==null?void 0:Se.completionExpenses)||null,templateType:V.templateType||V.template_type,form16Submission:R.form16Submission||null};n(ge);const we=(k=a==null?void 0:a.email)==null?void 0:k.toLowerCase(),Te=M.find(q=>{const ue=(q.status||"").toString().toUpperCase(),Pe=(q.approverEmail||"").toLowerCase(),ve=q.levelNumber||0;return(ue==="PENDING"||ue==="IN_PROGRESS"||ue==="PAUSED")&&Pe===we&&ve===J});x(Te||null);const de=a==null?void 0:a.userId;if(de){const q=L.some(ue=>(ue.participantType||ue.participant_type||"").toUpperCase()==="SPECTATOR"&&(ue.userId||ue.user_id)===de);g(q)}else g(!1)}catch(R){console.error("[useRequestDetails] Error refreshing details:",R),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);h.useEffect(()=>{if(!t){d(!1);return}let S=!0;return d(!0),m(null),(async()=>{var C,I,D,T,N,_,A,z,F,O,P,k,R,V;try{const M=await Hs.getWorkflowDetails(t);if(!S||!M){S&&d(!1);return}const L=M.workflow||{},U=Array.isArray(M.approvals)?M.approvals:[],H=Array.isArray(M.participants)?M.participants:[],X=Array.isArray(M.documents)?M.documents:[],J=M.summary||{},$=Array.isArray(M.tatAlerts)?M.tatAlerts:[],B=(L.priority||"").toString().toLowerCase(),K=(J==null?void 0:J.currentLevel)||L.currentLevel||1,se=U.map(ve=>{const Ne=ve.levelNumber||0,Ue=(ve.status||"").toString().toUpperCase(),nt=ve.levelId||ve.level_id;let ot=f(ve.status);Ue==="PAUSED"?ot="paused":Ne>K&&Ue!=="APPROVED"&&Ue!=="REJECTED"?ot="waiting":Ne===K&&(Ue==="PENDING"||Ue==="IN_PROGRESS")&&(ot=Ue==="IN_PROGRESS"?"in-review":"pending");const Tt=$.filter(Mt=>Mt.levelId===nt);return{step:Ne,levelId:nt,role:ve.levelName||ve.approverName||"Approver",status:ot,approver:ve.approverName||ve.approverEmail,approverId:ve.approverId||ve.approver_id,approverEmail:ve.approverEmail,tatHours:Number(ve.tatHours||0),elapsedHours:Number(ve.elapsedHours||0),remainingHours:Number(ve.remainingHours||0),tatPercentageUsed:Number(ve.tatPercentageUsed||0),actualHours:ve.elapsedHours!==void 0&&ve.elapsedHours!==null?Number(ve.elapsedHours):void 0,comment:ve.comments||void 0,timestamp:ve.actionDate||void 0,levelStartTime:ve.levelStartTime||ve.tatStartTime,tatAlerts:Tt}}),Y=H.filter(ve=>(ve.participantType||"").toUpperCase()==="SPECTATOR").map(ve=>({name:ve.userName||ve.userEmail,role:"Spectator",avatar:b(ve.userName,ve.userEmail)})),ee=ve=>{var Ue,nt;if(!ve)return;const Ne=H.find(ot=>ot.userId===ve);return Ne!=null&&Ne.userName?Ne.userName:L.initiatorId===ve?((Ue=L.initiator)==null?void 0:Ue.displayName)||((nt=L.initiator)==null?void 0:nt.email):ve},me=X.map(ve=>{const Ne=Number(ve.fileSize||0),Ue=(Ne/(1024*1024)).toFixed(2)+" MB";return{documentId:ve.documentId||ve.document_id,name:ve.originalFileName||ve.fileName,fileType:ve.fileType||ve.file_type||"",size:Ue,sizeBytes:Ne,uploadedBy:ee(ve.uploadedBy),uploadedAt:ve.uploadedAt}}),Se=Array.isArray(M.activities)?M.activities.filter(ve=>(ve.type||"").toLowerCase()!=="sla_warning"):[];let Je=null;if(L.isPaused||!1)try{Je=await eu(L.requestId)}catch{}let Ee=null,Oe=null,ie=null,ge=null,we=[],Te=null;if(Yn(L)){try{const ve=await be.get(`/dealer-claims/${L.requestId}/credit-note-wfm`),Ne=ve.data??ve;Te=Array.isArray(Ne==null?void 0:Ne.data)?Ne.data:Array.isArray(Ne)?Ne:[]}catch(ve){console.warn("[useRequestDetails] Error fetching credit note WFM data:",ve)}try{const ve=await be.get(`/dealer-claims/${L.requestId}`),Ne=((C=ve.data)==null?void 0:C.data)||ve.data;if(Ne){Ee=Ne.claimDetails||Ne.claim_details,Oe=Ne.proposalDetails||Ne.proposal_details,ie=Ne.completionDetails||Ne.completion_details,ge=Ne.internalOrder||Ne.internal_order||null,we=Ne.internalOrders||Ne.internal_orders||[];const Ue=Ne.budgetTracking||Ne.budget_tracking||null,nt=Ne.invoice||null,ot=Ne.creditNote||Ne.credit_note||null,Tt=Ne.completionExpenses||Ne.completion_expenses||null;Ee&&(Ee.budgetTracking=Ue,Ee.invoice=nt,Ee.creditNote=ot,Ee.completionExpenses=Tt,Ee.creditNoteWfmData=Te)}}catch(ve){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(ve==null?void 0:ve.message)||ve,status:(I=ve==null?void 0:ve.response)==null?void 0:I.status,requestId:L.requestId})}}const de={id:L.requestNumber||L.requestId,requestId:L.requestId,title:L.title,description:L.description,priority:B,status:f(L.status),workflowType:L.workflowType||(L.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:J,initiator:{name:((D=L.initiator)==null?void 0:D.displayName)||((T=L.initiator)==null?void 0:T.email),role:((N=L.initiator)==null?void 0:N.designation)||void 0,department:((_=L.initiator)==null?void 0:_.department)||void 0,email:((A=L.initiator)==null?void 0:A.email)||void 0,phone:((z=L.initiator)==null?void 0:z.phone)||void 0,avatar:b((F=L.initiator)==null?void 0:F.displayName,(O=L.initiator)==null?void 0:O.email)},createdAt:L.createdAt,updatedAt:L.updatedAt,totalSteps:L.totalLevels||1,currentStepRaw:(J==null?void 0:J.currentLevel)||L.currentLevel||1,currentStep:Math.min(Math.max(1,(J==null?void 0:J.currentLevel)||L.currentLevel||1),L.totalLevels||1),approvalFlow:se,approvals:U,documents:me,spectators:Y,auditTrail:Se,conclusionRemark:L.conclusionRemark||null,closureDate:L.closureDate||null,pauseInfo:Je||null,claimDetails:Ee||null,proposalDetails:Oe||null,completionDetails:ie||null,internalOrder:ge||null,internalOrders:we||[],budgetTracking:(Ee==null?void 0:Ee.budgetTracking)||null,invoice:(Ee==null?void 0:Ee.invoice)||null,creditNote:(Ee==null?void 0:Ee.creditNote)||null,creditNoteWfmData:Te||(Ee==null?void 0:Ee.creditNoteWfmData)||null,completionExpenses:(Ee==null?void 0:Ee.completionExpenses)||null,templateType:L.templateType||L.template_type,form16Submission:M.form16Submission||null};n(de);const q=(P=a==null?void 0:a.email)==null?void 0:P.toLowerCase(),ue=U.find(ve=>{const Ne=(ve.status||"").toString().toUpperCase(),Ue=(ve.approverEmail||"").toLowerCase(),nt=ve.levelNumber||0;return(Ne==="PENDING"||Ne==="IN_PROGRESS"||Ne==="PAUSED")&&Ue===q&&nt===K});x(ue||null);const Pe=a==null?void 0:a.userId;if(Pe){const ve=H.some(Ne=>(Ne.participantType||"").toUpperCase()==="SPECTATOR"&&Ne.userId===Pe);g(ve)}else g(!1)}catch(M){if(console.error("[useRequestDetails] Error loading request details:",M),S){if(((k=M==null?void 0:M.response)==null?void 0:k.status)===403){const L=((V=(R=M==null?void 0:M.response)==null?void 0:R.data)==null?void 0:V.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:L})}n(null)}}finally{S&&d(!1)}})(),()=>{S=!1}},[t,a]);const y=h.useMemo(()=>{if(r)return r;const S=s.find(C=>C.id===t||C.requestNumber===t||C.request_number===t);return S||null},[t,s,r]),v=h.useMemo(()=>{var I,D,T;if(!y||!a)return!1;const S=(I=a==null?void 0:a.email)==null?void 0:I.toLowerCase(),C=(T=(D=y.initiator)==null?void 0:D.email)==null?void 0:T.toLowerCase();return S===C},[y,a]),w=h.useMemo(()=>{var C;if(!y)return[];const S=[];return(C=y.initiator)!=null&&C.email&&S.push({email:y.initiator.email.toLowerCase(),participantType:"INITIATOR",name:y.initiator.name}),y.approvalFlow&&Array.isArray(y.approvalFlow)&&y.approvalFlow.forEach(I=>{I.approverEmail&&S.push({email:I.approverEmail.toLowerCase(),participantType:"APPROVER",name:I.approver})}),y.spectators&&Array.isArray(y.spectators)&&y.spectators.forEach(I=>{I.email&&S.push({email:I.email.toLowerCase(),participantType:"SPECTATOR",name:I.name})}),y.participants&&Array.isArray(y.participants)&&y.participants.forEach(I=>{const D=(I.userEmail||I.email||"").toLowerCase(),T=(I.participantType||I.participant_type||"").toUpperCase(),N=I.userName||I.user_name||I.name;D&&T&&!S.find(_=>_.email===D)&&S.push({email:D,participantType:T,name:N})}),S},[y]);return h.useEffect(()=>{if(!t||!r)return;const S=an();if(!S)return;const C=I=>{((I==null?void 0:I.requestId)===r.requestId||(I==null?void 0:I.requestNumber)===t)&&j()};return S.on("request:updated",C),()=>{S.off("request:updated",C)}},[t,r,j]),{request:y,apiRequest:r,loading:o,refreshing:i,refreshDetails:j,currentApprovalLevel:p,isSpectator:u,isInitiator:v,existingParticipants:w,accessDenied:c}}function a0(t,s,a,r){const[n,i]=h.useState([]),[l,o]=h.useState(0),[d,c]=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 b;try{const f=await Hs.getWorkflowDetails(t);(b=f==null?void 0:f.workflow)!=null&&b.requestId&&m&&(p=f.workflow.requestId)}catch(f){console.error("[useRequestSocket] Failed to resolve UUID:",f)}if(!m)return;const x=an();if(!x){console.error("[useRequestSocket] Socket not available");return}const u=r==null?void 0:r.userId,g=()=>{bo(x,p,u)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),Jh(x,p))}})(),()=>{m=!1}},[t,r]),h.useEffect(()=>{!t||!s||(async()=>{try{const m=await tn(t),p=s.auditTrail||[],x=[...m,...p];x.sort((u,g)=>{const b=new Date(u.createdAt||u.created_at||u.timestamp||0).getTime(),f=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return b-f}),i(x)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),h.useEffect(()=>{if(!t)return;const m=an();if(!m)return;const p=u=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await tn(t),b=(s==null?void 0:s.auditTrail)||[],f=[...g,...b].sort((j,y)=>{const v=new Date(j.createdAt||j.created_at||j.timestamp||0).getTime(),w=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime();return v-w});i(f)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},x=u=>{const g=u.type==="breach"?"⏰":u.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const b=await Hs.getWorkflowDetails(t);b&&(Array.isArray(b.tatAlerts)&&b.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:u.message,icon:"/favicon.ico",tag:`tat-${u.requestId}-${u.type}`,requireInteraction:!1}))}catch(b){console.error("[useRequestSocket] Failed to refresh after TAT alert:",b)}})()};return m.on("noteHandler",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:d,setWorkNoteAttachments:c}}async function Pn(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 be.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 kT=["MALWARE_DETECTED","FILE_VALIDATION_FAILED","CONTENT_THREAT_DETECTED","SCAN_UNAVAILABLE","SCAN_ERROR"],RT={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 Jc(t){var l,o,d,c;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(!kT.includes(a))return!1;const r=RT[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(", ")}`:(d=s.details.errors)!=null&&d.length?i=s.details.errors[0]||"":(c=s.details.threats)!=null&&c.length&&(i=s.details.threats.map(m=>m.description).join(", "))),G.error(r,{description:i||n,duration:8e3,style:{background:"#fef2f2",border:"1px solid #fca5a5",color:"#991b1b"}}),!0}function r0(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"]}),[d,c]=h.useState({show:!1,errors:[]});h.useEffect(()=>{(async()=>{try{const g=await ma("DOCUMENT_POLICY"),b={};g.forEach(v=>{b[v.configKey]=v.configValue});const f=parseInt(b.MAX_FILE_SIZE_MB||"10"),y=(b.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(v=>v.trim().toLowerCase());o({maxFileSizeMB:f,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 b=u.name.toLowerCase(),f=b.substring(b.lastIndexOf(".")+1);return l.allowedFileTypes.includes(f)?{valid:!0}:{valid:!1,reason:`File type "${f}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},p=async u=>{var y,v;const g=u.target.files;if(!g||g.length===0)return;const b=Array.from(g),f=[],j=[];if(b.forEach(w=>{const S=m(w);S.valid?j.push(w):f.push({fileName:w.name,reason:S.reason||"Unknown validation error"})}),f.length>0&&c({show:!0,errors:f}),j.length===0){u.target&&(u.target.value="");return}r(!0);try{const w=j[0],S=t==null?void 0:t.requestId;if(!S){G.error("Request ID not found");return}w&&await Pn(w,S,"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:d,setDocumentError:c}}const DT="modulepreload",FT=function(t){return"/"+t},kx={},Ql=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(d=>{if(d=FT(d),d in kx)return;kx[d]=!0;const c=d.endsWith(".css"),m=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${m}`))return;const p=document.createElement("link");if(p.rel=c?"stylesheet":DT,c||(p.as="script"),p.crossOrigin="",p.href=d,o&&p.setAttribute("nonce",o),document.head.appendChild(p),c)return new Promise((x,u)=>{p.addEventListener("load",x),p.addEventListener("error",()=>u(new Error(`Unable to preload CSS for ${d}`)))})}))}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 n0(t,s,a,r,n,i,l){const[o,d]=h.useState(""),[c,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(!1),[b,f]=h.useState(0),[j,y]=h.useState(!1),[v,w]=h.useState(!1),[S,C]=h.useState(0),I=async()=>{var A;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||_){d(N||_),g(!!_);return}try{const{getConclusion:z}=await Ql(async()=>{const{getConclusion:O}=await import("./conclusionApi-CKkdyXjv.js");return{getConclusion:O}},__vite__mapDeps([0,1,2,3,4,5,6,7])),F=await z(t.requestId||s);F&&(F.aiGeneratedRemark||F.finalRemark)&&(d(F.finalRemark||F.aiGeneratedRemark||""),g(!!F.aiGeneratedRemark))}catch(z){((A=z==null?void 0:z.response)==null?void 0:A.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",z)}},D=async()=>{if(!v)try{m(!0),y(!1);const{generateConclusion:N}=await Ql(async()=>{const{generateConclusion:F}=await import("./conclusionApi-CKkdyXjv.js");return{generateConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7])),_=await N(t.requestId||s),A=b+1;if(f(A),!(_!=null&&_.aiGeneratedRemark)||_.aiGeneratedRemark.toLowerCase().includes("unable to generate")||_.aiGeneratedRemark.toLowerCase().includes("sorry")){const F=S+1;C(F),F>=2?(w(!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),d((_==null?void 0:_.aiGeneratedRemark)||""),g(!1);return}d(_.aiGeneratedRemark),g(!0),C(0),A>=2&&(w(!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 _=S+1;C(_),g(!1),_>=2?(w(!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)}},T=async()=>{var _,A;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:z}=await Ql(async()=>{const{finalizeConclusion:F}=await import("./conclusionApi-CKkdyXjv.js");return{finalizeConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await z(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(z){i==null||i({success:!1,title:"Error",message:((A=(_=z.response)==null?void 0:_.data)==null?void 0:A.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 A=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),z=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);A||z?(d(A||z),g(!!z)):I()},[t==null?void 0:t.status,t==null?void 0:t.conclusionRemark,t==null?void 0:t.aiGeneratedConclusion,a,o]),{conclusionRemark:o,setConclusionRemark:d,conclusionLoading:c,conclusionSubmitting:p,aiGenerated:u,handleGenerateConclusion:D,handleFinalizeConclusion:T,generationAttempts:b,generationFailed:j,maxAttemptsReached:v}}function i0(t,s,a){const[r,n]=h.useState(!1),[i,l]=h.useState(!1),[o,d]=h.useState(!1),[c,m]=h.useState(!1),[p,x]=h.useState(!1),[u,g]=h.useState(!1),[b,f]=h.useState(null),[j,y]=h.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:d,showAddSpectatorModal:c,setShowAddSpectatorModal:m,showSkipApproverModal:p,setShowSkipApproverModal:x,showActionStatusModal:u,setShowActionStatusModal:g,skipApproverData:b,setSkipApproverData:f,actionStatus:j,setActionStatus:y,handleApproveConfirm:async D=>{var N,_;const T=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!T){alert("Approval level not found");return}await Dn(t,T,D||""),await new Promise(A=>setTimeout(A,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 T=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!T){alert("Approval level not found");return}await Cr(t,T,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,T,N)=>{var _,A;try{await xp(t,D,T,N),await a(),d(!1),y==null||y({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${T}h TAT`}),g==null||g(!0)}catch(z){throw y==null||y({success:!1,title:"Failed to Add Approver",message:((A=(_=z==null?void 0:z.response)==null?void 0:_.data)==null?void 0:A.error)||"Failed to add approver. Please try again."}),g==null||g(!0),z}},handleSkipApprover:async D=>{var T,N;if(b)try{await Iw(t,b.levelId,D),await a(),x(!1),f(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=(T=_==null?void 0:_.response)==null?void 0:T.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),_}},handleAddSpectator:async D=>{var T,N;try{await hp(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=(T=_==null?void 0:_.response)==null?void 0:T.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),_}}}}function PT({requestId:t,request:s,onRefresh:a}){const[r,n]=h.useState(null),[i,l]=h.useState(!0),[o,d]=h.useState(null),m=!!(s==null?void 0:s.form16Submission),p=!!r&&r.status!=="withdrawn";h.useEffect(()=>{if(!t){l(!1);return}let g=!1;return(async()=>{try{const b=await Qh(t);g||n(b?{id:typeof b.id=="number"?b.id:Number(b.id),status:b.status||""}:null)}catch{g||n(null)}finally{g||l(!1)}})(),()=>{g=!0}},[t]);const x=async()=>{if(!(!t||!window.confirm("Cancel this Form 16 submission? The request will be marked as rejected."))){d("cancel");try{await ky(t),G.success("Submission cancelled"),a==null||a()}catch(g){G.error(g instanceof Error?g.message:"Failed to cancel submission")}finally{d(null)}}},u=async()=>{if(!(!t||!window.confirm("Mark this submission as resubmission needed? The dealer will need to resubmit Form 16."))){d("resubmit");try{await Ry(t),G.success("Marked as resubmission needed"),a==null||a()}catch(g){G.error(g instanceof Error?g.message:"Failed to update")}finally{d(null)}}};return i||!m||p?null:e.jsxs(Z,{className:"border-blue-200 bg-blue-50/30","data-testid":"form16-quick-actions-card",children:[e.jsxs(oe,{className:"pb-2",children:[e.jsxs(ce,{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 or mark resubmission needed."})]}),e.jsxs(te,{className:"space-y-2",children:[e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start border-red-300 text-red-700 hover:bg-red-50",onClick:x,disabled:!!o,children:[o==="cancel"?e.jsx(Ke,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(jt,{className:"w-3 h-3 mr-1"}),"Cancel submission"]}),e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start border-amber-300 text-amber-700 hover:bg-amber-50",onClick:u,disabled:!!o,children:[o==="resubmit"?e.jsx(Ke,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(hh,{className:"w-3 h-3 mr-1"}),"Resubmission needed"]})]})]})}const IT=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 _r({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(De,{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&&IT(t.fileType)&&s&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>s({fileName:t.name,fileType:t.fileType,documentId:t.documentId,fileSize:t.sizeBytes}),title:"Preview file","data-testid":`${n}-preview-btn`,children:e.jsx(Nt,{className:"w-4 h-4"})}),a&&e.jsx(E,{variant:"ghost",size:"sm",onClick:async()=>{if(!t.documentId){alert("Document ID not available");return}try{await a(t.documentId)}catch{alert("Failed to download document")}},title:"Download file","data-testid":`${n}-download-btn`,children:e.jsx(At,{className:"w-4 h-4"})})]})]})}function ET({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l,isSpectator:o=!1}){var c,m,p,x;const d=((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:[d&&((m=(c=t==null?void 0:t.form16Submission)==null?void 0:c.previousDocuments)==null?void 0:m.length)>0&&e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-sm sm:text-base text-amber-800",children:[e.jsx(De,{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 (",(p=t==null?void 0:t.form16Submission)==null?void 0:p.financialYear," ",(x=t==null?void 0:t.form16Submission)==null?void 0:x.quarter,")"]})]}),e.jsx(te,{children:e.jsx("div",{className:"space-y-4",children:(()=>{const u=new Map;for(const g of t.form16Submission.previousDocuments){const b=g.requestId||g.request_id,f=g.requestNumber||b;u.has(f)||u.set(f,[]),u.get(f).push(g)}return Array.from(u.entries()).map(([g,b])=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600",children:["Request ",g]}),e.jsx("div",{className:"space-y-2 pl-2 border-l-2 border-amber-200",children:b.map((f,j)=>{const y=f.documentId??f.document_id,v=f.originalFileName??f.original_file_name??f.fileName??f.file_name??"Document",w=Number(f.fileSize??f.file_size??0),S=w>0?(w/(1024*1024)).toFixed(2)+" MB":"—";return e.jsx(_r,{document:{documentId:y,name:v,fileType:f.fileType??f.file_type??"",size:S,sizeBytes:w,uploadedBy:f.uploadedBy??f.uploaded_by,uploadedAt:f.uploadedAt??f.uploaded_at},onPreview:C=>i(C),onDownload:l,testId:"form16-previous-document"},y||j)})})]},g))})()})})]}),e.jsxs(Z,{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(ce,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(De,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),d?"Current submission":"Request Documents"]}),e.jsx(ye,{className:"text-xs sm:text-sm mt-1",children:d?"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(E,{size:"sm",onClick:n,disabled:a||t.status==="closed"||o,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(te,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((u,g)=>e.jsx(_r,{document:u,onPreview:b=>i(b),onDownload:l,testId:"request-document"},g))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-documents",children:"No documents uploaded yet"})})]}),!d&&e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Vs,{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(te,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((u,g)=>e.jsx(_r,{document:{documentId:u.attachmentId||"",name:u.name,fileType:u.type||"",size:u.size?`${(u.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:u.size,uploadedBy:u.uploadedBy,uploadedAt:u.uploadedAt},onPreview:b=>i(b),onDownload:async b=>{const{downloadWorkNoteAttachment:f}=require("@/services/workflowApi");await f(b)},testId:"worknote-attachment"},u.attachmentId||g))}):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 _T=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"}}},Rx=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:ts,iconColor:"text-gray-600"};case"in-review":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"in-review",icon:Et,iconColor:"text-blue-600"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:$e,iconColor:"text-green-600"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected",icon:Ct,iconColor:"text-red-600"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-300",label:"closed",icon:$e,iconColor:"text-gray-600"};case"skipped":return{color:"bg-orange-100 text-orange-800 border-orange-200",label:"skipped",icon:Bt,iconColor:"text-orange-600"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t,icon:ts,iconColor:"text-gray-600"}}},MT=t=>{switch(t){case"approval":case"approved":return e.jsx($e,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(Ct,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(Vs,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(Et,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(qi,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(De,{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(Qi,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(ts,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(Bt,{className:"w-5 h-5 text-gray-600"})}};function LT(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||"",b=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:b}),u.creditNoteNumber){const f=u.creditNoteIssueDate?new Date(u.creditNoteIssueDate).toISOString():b;a.push({type:"status_change",action:"Credit note issued",details:`Credit note ${u.creditNoteNumber} issued for previous submission (${g}).`,timestamp:f})}}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||""||"",d=(s.displayStatus||"").toLowerCase(),c=!!(s.ocrExtractedData&&typeof s.ocrExtractedData=="object"&&Object.keys(s.ocrExtractedData).length>0),m=!!s.creditNoteNumber,p=d==="balance mismatch"||l==="failed"&&!m||l==="failed"&&/mismatch|26as|value/i.test(o),x=d==="duplicate"||l==="duplicate";if(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:c?"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"||m?"26AS matching completed.":"26AS matching was performed.",timestamp:i}),m){const u=s.creditNoteIssueDate?new Date(s.creditNoteIssueDate).toISOString():i;a.push({type:"status_change",action:"Credit note issued",details:`Credit note ${s.creditNoteNumber} issued for this submission.`,timestamp:u})}return a.sort((u,g)=>new Date(u.timestamp).getTime()-new Date(g.timestamp).getTime())}function OT({request:t}){const s=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",a=s?LT(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,d=l.timestamp?new Date(l.timestamp).getTime():0;return o-d}):r;return e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Bt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx(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(te,{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:MT(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(Bt,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No activity recorded yet"}),e.jsx("p",{className:"text-xs text-gray-400 mt-2",children:"Actions and updates will appear here"})]})})})]})}function l0({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(ut,{className:"sm:max-w-md",children:[e.jsx(gt,{children:e.jsxs(xt,{className:"flex items-center gap-2",children:[a?e.jsx($e,{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($e,{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(Ct,{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(It,{children:e.jsx(E,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function o0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=h.useState(""),[l,o]=h.useState(!1),[d,c]=h.useState([]),[m,p]=h.useState(!1),[x,u]=h.useState(null),g=h.useRef(null),b=h.useRef(null),[f,j]=h.useState({open:!1,type:"error",email:"",message:""}),[y,v]=h.useState({open:!1,violations:[]}),[w,S]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});h.useEffect(()=>{t&&(async()=>{var _;try{const A=await ma("WORKFLOW_SHARING"),z=await ma("TAT_SETTINGS"),F=[...A,...z],O={};F.forEach(P=>{O[P.configKey]=P.configValue}),S({maxApprovalLevels:parseInt(O.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(O.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((_=O.ALLOW_ADD_SPECTATOR)==null?void 0:_.toLowerCase())==="true",maxSpectators:parseInt(O.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(A){console.error("Failed to load system policy:",A)}})()},[t]);const C=async()=>{var k,R;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 A=r.find(V=>(V.email||"").toLowerCase()===N);if(A){const V=((k=A.participantType)==null?void 0:k.toUpperCase())||"PARTICIPANT",M=A.name||N;if(V==="INITIATOR"){j({open:!0,type:"error",email:N,message:`${M} is the request initiator and cannot be added as a spectator.`});return}else if(V==="APPROVER"){j({open:!0,type:"error",email:N,message:`${M} is already an approver on this request and cannot be added as a spectator.`});return}else if(V==="SPECTATOR"){j({open:!0,type:"error",email:N,message:`${M} is already a spectator on this request.`});return}else{j({open:!0,type:"error",email:N,message:`${M} is already a participant on this request.`});return}}const z=[];w.allowSpectators||z.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const O=r.filter(V=>(V.participantType||"").toUpperCase()==="SPECTATOR").length;O>=w.maxSpectators&&z.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:O,maxValue:w.maxSpectators});const P=r.length+1;if(P>w.maxParticipants&&z.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:P,maxValue:w.maxParticipants}),z.length>0){v({open:!0,violations:z});return}if(!x||x.email.toLowerCase()!==N)try{const M=((R=(await ya(N,1)).data)==null?void 0:R.data)||[];if(M.length===0){j({open:!0,type:"not-found",email:N,message:""});return}const L=M[0];await ba({userId:L.userId,email:L.email,displayName:L.displayName,firstName:L.firstName,lastName:L.lastName,department:L.department,phone:L.phone,mobilePhone:L.mobilePhone,designation:L.designation,jobTitle:L.jobTitle,manager:L.manager,employeeId:L.employeeId,employeeNumber:L.employeeNumber,secondEmail:L.secondEmail,location:L.location})}catch(V){console.error("Failed to validate spectator:",V),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(V){console.error("Failed to add spectator:",V)}finally{o(!1)}},I=()=>{l||(i(""),u(null),c([]),p(!1),s())};h.useEffect(()=>{d.length>0&&b.current&&b.current.scrollTo({top:b.current.scrollHeight,behavior:"smooth"})},[d.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){c([]),p(!1);return}p(!0),g.current=setTimeout(async()=>{var _;try{const A=N.slice(1),F=((_=(await ya(A,10)).data)==null?void 0:_.data)||[];c(F)}catch(A){console.error("Search failed:",A),c([])}finally{p(!1)}},300)},T=async N=>{try{await ba({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),c([]),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(pt,{open:t,onOpenChange:I,children:[e.jsxs(ut,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:I,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(gt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center",children:e.jsx(Nt,{className:"w-5 h-5 text-purple-600"})}),e.jsx(xt,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:b,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a spectator to this request. They will receive notifications but cannot approve or reject."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(el,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(ke,{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||d.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..."}):d.length>0?e.jsx("ul",{className:"divide-y",children:d.map(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>T(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(os,{className:"h-8 w-8",children:e.jsx(cs,{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(E,{type:"button",variant:"outline",onClick:I,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:C,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(Nt,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(pt,{open:f.open,onOpenChange:N=>j(_=>({..._,open:N})),children:e.jsxs(ut,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(xt,{className:"flex items-center gap-2",children:f.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(_t,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[f.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:f.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Zi,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),f.type==="error"&&e.jsxs(e.Fragment,{children:[f.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:f.email}),"."]}),f.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:f.message})})]})]})})]}),e.jsx(It,{children:e.jsx(E,{onClick:()=>j(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(ni,{open:y.open,onClose:()=>v({open:!1,violations:[]}),violations:y.violations,policyDetails:{maxApprovalLevels:w.maxApprovalLevels,maxParticipants:w.maxParticipants,allowSpectators:w.allowSpectators,maxSpectators:w.maxSpectators}})]})}function c0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,d]=h.useState(""),[c,m]=h.useState(24),[p,x]=h.useState(null),[u,g]=h.useState(!1),[b,f]=h.useState([]),[j,y]=h.useState(!1),[v,w]=h.useState(null),S=h.useRef(null),C=h.useRef(null),[I,D]=h.useState({open:!1,type:"error",email:"",message:""}),T=n.filter(R=>R&&(R.status==="approved"||R.status==="rejected"||R.status==="skipped")),N=Math.max(1,T.length+1),_=Math.max(1,n.length+1),A=_>=N?Array.from({length:_-N+1},(R,V)=>N+V):[N];h.useEffect(()=>{A.length>0&&p===null&&x(A[0]||null)},[A.length,p]);const z=async()=>{var H,X;const R=o.trim().toLowerCase();if(!R){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(R)){D({open:!0,type:"error",email:R,message:"Please enter a valid email address"});return}if(!c||c<=0){D({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(c>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(J=>J.levelNumber),0):0,L=p>M?p:M+1;if(i&&L>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${p} would result in ${L} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:L,maxValue:i}]):D({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${M} level(s).`});return}const U=r.find(J=>(J.email||"").toLowerCase()===R);if(U){const J=((H=U.participantType)==null?void 0:H.toUpperCase())||"PARTICIPANT",$=U.name||R;if(J==="INITIATOR"){D({open:!0,type:"error",email:R,message:`${$} is the request initiator and cannot be added as an approver.`});return}else if(J==="APPROVER"){D({open:!0,type:"error",email:R,message:`${$} is already an approver on this request.`});return}else if(J==="SPECTATOR"){D({open:!0,type:"error",email:R,message:`${$} 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:R,message:`${$} is already a participant on this request.`});return}}if(!v||v.email.toLowerCase()!==R)try{const $=((X=(await ya(R,1)).data)==null?void 0:X.data)||[];if($.length===0){D({open:!0,type:"not-found",email:R,message:""});return}const B=$[0];await ba({userId:B.userId,email:B.email,displayName:B.displayName,firstName:B.firstName,lastName:B.lastName,department:B.department,phone:B.phone,mobilePhone:B.mobilePhone,designation:B.designation,jobTitle:B.jobTitle,manager:B.manager,employeeId:B.employeeId,employeeNumber:B.employeeNumber,secondEmail:B.secondEmail,location:B.location})}catch(J){console.error("Failed to validate approver:",J),D({open:!0,type:"error",email:R,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(R,c,p),d(""),m(24),x(null),w(null),s()}catch(J){console.error("Failed to add approver:",J)}finally{g(!1)}},F=()=>{u||(d(""),m(24),x(null),w(null),f([]),y(!1),s())},O=R=>{const V=R.toLowerCase();return V==="approved"?e.jsx($e,{className:"w-4 h-4 text-green-600"}):V==="rejected"?e.jsx(Ct,{className:"w-4 h-4 text-red-600"}):V==="skipped"?e.jsx(Ze,{className:"w-4 h-4 text-orange-600"}):V==="in-review"||V==="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(()=>{b.length>0&&C.current&&C.current.scrollTo({top:C.current.scrollHeight,behavior:"smooth"})},[b.length]),h.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const P=R=>{if(d(R),v&&v.email.toLowerCase()!==R.toLowerCase()&&w(null),S.current&&clearTimeout(S.current),!R||!R.startsWith("@")||R.length<2){f([]),y(!1);return}y(!0),S.current=setTimeout(async()=>{var V;try{const M=R.slice(1),U=((V=(await ya(M,10)).data)==null?void 0:V.data)||[];f(U)}catch(M){console.error("Search failed:",M),f([])}finally{y(!1)}},300)},k=async R=>{try{await ba({userId:R.userId,email:R.email,displayName:R.displayName,firstName:R.firstName,lastName:R.lastName,department:R.department,phone:R.phone,mobilePhone:R.mobilePhone,designation:R.designation,jobTitle:R.jobTitle,manager:R.manager,employeeId:R.employeeId,employeeNumber:R.employeeNumber,secondEmail:R.secondEmail,location:R.location}),d(R.email),w(R),f([]),y(!1)}catch(V){console.error("Failed to ensure user exists:",V),D({open:!0,type:"error",email:R.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(pt,{open:t,onOpenChange:F,children:[e.jsxs(ut,{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(gt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Zt,{className:"w-5 h-5 text-blue-600"})}),e.jsx(xt,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:C,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(R=>R.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ae,{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(R=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${R.status==="approved"?"bg-green-100 border border-green-200":R.status==="rejected"?"bg-red-100 border border-red-200":R.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:R.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:R.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[R.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[O(R.status),e.jsx(re,{variant:"outline",className:`text-xs ${R.status==="approved"?"bg-green-50 text-green-700 border-green-300":R.status==="rejected"?"bg-red-50 text-red-700 border-red-300":R.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:R.status})]})]},R.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(ae,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(He,{value:(p==null?void 0:p.toString())||"",onValueChange:R=>x(Number(R)),disabled:u,children:[e.jsx(Ge,{className:"h-11 border-gray-300",children:e.jsx(We,{placeholder:"Select level"})}),e.jsx(Ye,{children:A.map(R=>e.jsx(Q,{value:R.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 ",R]}),R<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",R,")"]})]})},R))})]}),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(ae,{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(ke,{type:"number",min:"1",max:"720",value:c,onChange:R=>m(Number(R.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(el,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(ke,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:R=>P(R.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(j||b.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:j?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):b.length>0?e.jsx("ul",{className:"divide-y",children:b.map(R=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>k(R),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(os,{className:"h-8 w-8",children:e.jsx(cs,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(R.displayName||R.email).split(" ").map(V=>V[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:R.displayName||[R.firstName,R.lastName].filter(Boolean).join(" ")||R.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:R.email}),R.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:R.designation})]})]})},R.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:F,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:z,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!o.trim()||!p||!c,children:[e.jsx(Zt,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${p||"?"}`]})]})]}),e.jsx(pt,{open:I.open,onOpenChange:R=>D(V=>({...V,open:R})),children:e.jsxs(ut,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(xt,{className:"flex items-center gap-2",children:I.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:[I.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:I.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(Zi,{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."]})})]}),I.type==="error"&&e.jsxs(e.Fragment,{children:[I.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:I.email}),"."]}),I.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:I.message})})]})]})})]}),e.jsx(It,{children:e.jsx(E,{onClick:()=>D(R=>({...R,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const $T=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"}},UT=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},BT=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 Pa(s)},VT=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",Dx=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(De,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(gh,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(De,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(De,{className:`${s} text-blue-600`}):a.includes("image")||a.includes("png")||a.includes("jpg")||a.includes("jpeg")||a.includes("gif")||a.includes("webp")?e.jsx(bi,{className:`${s} text-purple-600`}):e.jsx(Qi,{className:`${s} text-gray-600`})};function d0({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:d=[],onAddApprover:c,maxApprovalLevels:m,onPolicyViolation:p}){const x=Oa(),u=t||x.requestId||"",[g,b]=h.useState(""),[f,j]=h.useState(""),[y,v]=h.useState(!1),[w,S]=h.useState([]),[C,I]=h.useState(!1),[D,T]=h.useState([]),[N,_]=h.useState(null),[A,z]=h.useState(null),[F,O]=h.useState(!1),[P,k]=h.useState(!1),[R,V]=h.useState(!1),[M,L]=h.useState({success:!0,title:"",message:""}),U=h.useRef(null),H=h.useRef(null),X=h.useRef(null),J=h.useRef(!1),[$,B]=h.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[K,se]=h.useState({open:!1,errors:[]}),Y=h.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[ee,me]=h.useState([]),Se=ee.filter(ne=>ne.status==="online"),Je=w.filter(ne=>ne.content.toLowerCase().includes(f.toLowerCase())||ne.user.name.toLowerCase().includes(f.toLowerCase())),Ve=h.useMemo(()=>o!==void 0?o:!N||ee.length===0?!1:ee.some(ne=>{const Ie=ne.userId||ne.user_id,le=(ne.role||"").toString().toUpperCase(),Xe=(ne.participantType||ne.participant_type||"").toString().toUpperCase();return Ie===N&&(le==="SPECTATOR"||Xe==="SPECTATOR")}),[o,N,ee]);h.useEffect(()=>{},[ee]),h.useEffect(()=>{!u||!N||s||(async()=>{try{const ne=await tn(u),Ie=Array.isArray(ne)?ne.map(le=>{const Xe=le.userId||le.user_id;return{id:le.noteId||le.id||String(Math.random()),user:{name:le.userName||"User",avatar:(le.userName||"U").slice(0,2).toUpperCase(),role:le.userRole||"Participant"},content:le.message||"",timestamp:le.createdAt||new Date().toISOString(),isCurrentUser:Xe===N,attachments:Array.isArray(le.attachments)?le.attachments.map(ze=>({attachmentId:ze.attachmentId||ze.attachment_id,name:ze.fileName||ze.file_name||ze.name,fileName:ze.fileName||ze.file_name||ze.name,url:ze.storageUrl||ze.storage_url||ze.url||"#",type:ze.fileType||ze.file_type||ze.type||"file",fileType:ze.fileType||ze.file_type||ze.type||"file",fileSize:ze.fileSize||ze.file_size})):void 0}}):[];S(Ie)}catch(ne){console.error("[WorkNoteChat] Failed to load messages:",ne)}})()},[u,N,s]);const Ee=h.useMemo(()=>{const ne=[];return w.forEach(Ie=>{Ie.attachments&&Ie.attachments.length>0&&Ie.attachments.forEach(le=>{ne.push({attachmentId:le.attachmentId||le.attachment_id,name:le.fileName||le.file_name||le.name||"Untitled",fileName:le.fileName||le.file_name||le.name||"Untitled",size:le.fileSize||le.file_size,type:le.fileType||le.file_type||le.type||"file",uploadedBy:Ie.user.name,uploadedAt:Ie.timestamp,url:le.storageUrl||le.storage_url||le.url||"#"})})}),ne},[w]);h.useEffect(()=>{i&&Ee.length>=0&&i(Ee)},[Ee,i]);const Oe=h.useMemo(()=>ee.map(ne=>({email:(ne.email||"").toLowerCase(),participantType:ne.role==="Initiator"?"INITIATOR":ne.role==="Approver"?"APPROVER":ne.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:ne.name})),[ee]),ie=ne=>{if(!ne)return"Participant";switch(ne.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return ne.charAt(0).toUpperCase()+ne.slice(1).toLowerCase()}},ge=()=>{var ne;(ne=U.current)==null||ne.scrollIntoView({behavior:"smooth"})};h.useEffect(()=>{ge()},[w]);const we=ne=>{switch(ne.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return ne.charAt(0).toUpperCase()+ne.slice(1).toLowerCase()}};h.useEffect(()=>{J.current||u&&(async()=>{try{const ne=await Ps(u),Ie=Array.isArray(ne==null?void 0:ne.participants)?ne.participants:[];if(Ie.length===0)return;const le=Ie.map(Qe=>{const rt=Qe.participantType||Qe.participant_type||"participant",qe=Qe.userId||Qe.user_id||"";return{name:Qe.userName||Qe.user_name||Qe.user_email||Qe.userEmail||"User",avatar:(Qe.userName||Qe.user_name||Qe.user_email||"U").toString().split(" ").map(ct=>ct[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:we(rt.toString()),status:"offline",email:Qe.userEmail||Qe.user_email||"",permissions:["read","write","mention"],userId:qe}});J.current=!0,me(le);let Xe=0;const ze=3,tt=()=>{X.current&&X.current.connected?(X.current.emit("request:online-users",{requestId:u}),Xe++,Xe()=>{u&&(J.current=!1)},[u]),h.useEffect(()=>{const ne=localStorage.getItem("userData");if(ne)try{const Ie=JSON.parse(ne),le=(Ie==null?void 0:Ie.id)||(Ie==null?void 0:Ie.userId)||(Ie==null?void 0:Ie.user_id)||null;_(le)}catch(Ie){console.error("[WorkNoteChat] Failed to parse userData:",Ie)}},[]),h.useEffect(()=>{(async()=>{try{const Ie=await ma("DOCUMENT_POLICY"),le={};Ie.forEach(Qe=>{le[Qe.configKey]=Qe.configValue});const Xe=parseInt(le.MAX_FILE_SIZE_MB||"10"),tt=(le.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Qe=>Qe.trim().toLowerCase());B({maxFileSizeMB:Xe,allowedFileTypes:tt})}catch(Ie){console.error("Failed to load document policy:",Ie)}})()},[]),h.useEffect(()=>{if(!N)return;let ne=u;return(async()=>{var Ie;try{const le=await Ps(u);(Ie=le==null?void 0:le.workflow)!=null&&Ie.requestId&&(ne=le.workflow.requestId)}catch{}try{const le=an();r?me(yt=>yt.map(Ft=>Ft.userId===N?{...Ft,status:"online"}:Ft)):(bo(le,ne,N),me(yt=>yt.map(Ft=>Ft.userId===N?{...Ft,status:"online"}:Ft)));const Xe=yt=>{const mt=(yt==null?void 0:yt.note)||yt;if(!mt)return;const Ft=mt.noteId||mt.id;S(Ss=>{if(Ss.some(Lt=>Lt.id===Ft))return Ss;const ss=mt.userName||mt.user_name||"User",$a=mt.userRole||mt.user_role,Ua=ie($a),ur=mt.userId||mt.user_id,va={id:Ft||String(Date.now()),user:{name:ss,avatar:ss.split(" ").map(Lt=>Lt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ua},content:mt.message||"",timestamp:mt.createdAt||new Date().toISOString(),isCurrentUser:ur===N,attachments:Array.isArray(mt.attachments)?mt.attachments.map(Lt=>({attachmentId:Lt.attachmentId||Lt.attachment_id,name:Lt.fileName||Lt.file_name||Lt.name,fileName:Lt.fileName||Lt.file_name||Lt.name,url:Lt.storageUrl||Lt.storage_url||Lt.url||"#",type:Lt.fileType||Lt.file_type||Lt.type||"file",fileType:Lt.fileType||Lt.file_type||Lt.type||"file",fileSize:Lt.fileSize||Lt.file_size})):void 0};return[...Ss,va]})},ze=yt=>{me(mt=>mt.length===0||!mt.find(ss=>ss.userId===yt.userId)?mt:mt.map(ss=>ss.userId===yt.userId?{...ss,status:"online"}:ss))},tt=yt=>{yt.userId!==N&&me(mt=>mt.length===0||!mt.find(ss=>ss.userId===yt.userId)?mt:mt.map(ss=>ss.userId===yt.userId?{...ss,status:"offline"}:ss))},Qe=yt=>{me(mt=>mt.length===0?mt:mt.map(Ss=>{const ss=Ss.userId||"";if(ss===N)return{...Ss,status:"online"};const Ua=yt.userIds.includes(ss);return{...Ss,status:Ua?"online":"offline"}}))},rt=()=>{me(yt=>yt.map(Ft=>Ft.userId===N?{...Ft,status:"online"}:Ft)),r||bo(le,ne,N),J.current&&(le.emit("request:online-users",{requestId:ne}),setTimeout(()=>le.emit("request:online-users",{requestId:ne}),300),setTimeout(()=>le.emit("request:online-users",{requestId:ne}),800))},qe=yt=>{console.error("[WorkNoteChat] ❌ Socket error:",yt)},ct=yt=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",yt),me(mt=>mt.map(Ft=>Ft.userId===N?Ft:{...Ft,status:"offline"}))},$s=yt=>{yt.includes("presence")||yt.includes("worknote")||yt.includes("request")};le.on("connect",rt),le.on("disconnect",ct),le.on("error",qe),le.on("worknote:new",Xe),le.on("presence:join",ze),le.on("presence:leave",tt),le.on("presence:online",Qe),le.onAny($s),X.current=le,le.connected&&J.current&&(le.emit("request:online-users",{requestId:ne}),setTimeout(()=>{le.emit("request:online-users",{requestId:ne})},300),setTimeout(()=>{le.emit("request:online-users",{requestId:ne})},800),setTimeout(()=>{le.emit("request:online-users",{requestId:ne})},1500));const ns=()=>{le.off("connect",rt),le.off("disconnect",ct),le.off("error",qe),le.off("worknote:new",Xe),le.off("presence:join",ze),le.off("presence:leave",tt),le.off("presence:online",Qe),le.offAny($s),r||Jh(le,ne),X.current=null};window.__wn_cleanup=ns}catch{}})(),()=>{var Ie;try{(Ie=window.__wn_cleanup)==null||Ie.call(window)}catch{}}},[u,N,r]);const Te=async()=>{if(g.trim()||D.length>0){const ne=ot(g),Ie=ne.map(ze=>{const tt=ee.find(Qe=>Qe.name.toLowerCase().includes(ze.toLowerCase()));return tt==null?void 0:tt.userId}).filter(Boolean),le=D.map(ze=>({name:ze.name,url:URL.createObjectURL(ze),type:ze.type.split("/")[1]||"file"})),Xe={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:ne,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:le.length>0?le:void 0,isCurrentUser:!0};if(a)try{await a(g,D)}catch{}else try{await up(u,{message:g,mentions:Ie},D);const ze=await tn(u),tt=Array.isArray(ze)?ze.map(Qe=>{const rt=Qe.userId||Qe.user_id;return{id:Qe.noteId||Qe.id||String(Math.random()),user:{name:Qe.userName||"User",avatar:(Qe.userName||"U").slice(0,2).toUpperCase(),role:Qe.userRole||"Participant"},content:Qe.message||"",timestamp:Qe.createdAt||new Date().toISOString(),isCurrentUser:rt===N,attachments:Array.isArray(Qe.attachments)?Qe.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}}):[];S(tt)}catch{S(ze=>[...ze,Xe])}b(""),T([])}};h.useEffect(()=>{if(s&&Array.isArray(s))try{const Ie=s.filter(le=>(le.type||"").toLowerCase()!=="sla_warning").map(le=>{var ze;if(le.type||le.activityType||le.isSystem)return{id:le.id||`activity-${le.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:le.details||le.action||le.content||"",timestamp:le.timestamp||le.createdAt||le.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const tt=le.userName||le.user_name||((ze=le.user)==null?void 0:ze.name)||"User",Qe=le.userRole||le.user_role,rt=ie(Qe),qe=le.userId||le.user_id;return{id:le.noteId||le.note_id||le.id||String(Math.random()),user:{name:tt,avatar:tt.split(" ").map(ct=>ct[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:rt},content:le.message||le.content||"",timestamp:le.createdAt||le.created_at||le.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(le.attachments)?le.attachments.map(ct=>({attachmentId:ct.attachmentId||ct.attachment_id,name:ct.fileName||ct.file_name||ct.name,fileName:ct.fileName||ct.file_name||ct.name,url:ct.storageUrl||ct.storage_url||ct.url||"#",type:ct.fileType||ct.file_type||ct.type||"file",fileType:ct.fileType||ct.file_type||ct.type||"file",fileSize:ct.fileSize||ct.file_size})):void 0,isCurrentUser:qe===N}}}).sort((le,Xe)=>new Date(le.timestamp).getTime()-new Date(Xe.timestamp).getTime());S(Ie)}catch(ne){console.error("[WorkNoteChat] Error mapping messages:",ne)}else(async()=>{try{const ne=await tn(u),Ie=Array.isArray(ne)?ne.map(le=>{const Xe=le.userName||le.user_name||"User",ze=le.userRole||le.user_role,tt=ie(ze),Qe=le.userId||le.user_id;return{id:le.noteId||le.note_id||le.id||String(Math.random()),user:{name:Xe,avatar:Xe.split(" ").map(rt=>rt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:tt},content:le.message||"",timestamp:le.createdAt||le.created_at||new Date().toISOString(),attachments:Array.isArray(le.attachments)?le.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:Qe===N}}):[];S(Ie)}catch(ne){console.error("[WorkNoteChat] Error loading work notes:",ne)}})()},[s,u,ee]);const de=ne=>{const Ie=$.maxFileSizeMB*1024*1024;if(ne.size>Ie)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${$.maxFileSizeMB}MB. Current size: ${(ne.size/(1024*1024)).toFixed(2)}MB`};const le=ne.name.toLowerCase(),Xe=le.substring(le.lastIndexOf(".")+1);return $.allowedFileTypes.includes(Xe)?{valid:!0}:{valid:!1,reason:`File type "${Xe}" is not allowed. Allowed types: ${$.allowedFileTypes.join(", ")}`}},q=ne=>{if(!ne.target.files||ne.target.files.length===0)return;const Ie=Array.from(ne.target.files),le=[],Xe=[];Ie.forEach(ze=>{const tt=de(ze);tt.valid?Xe.push(ze):le.push({fileName:ze.name,reason:tt.reason||"Unknown validation error"})}),le.length>0&&se({open:!0,errors:le}),Xe.length>0&&(T(ze=>[...ze,...Xe]),Xe.length{T(Ie=>Ie.filter((le,Xe)=>Xe!==ne)),H.current&&(H.current.value="")},Pe=ne=>{b(Ie=>Ie+ne),v(!1)},ve=()=>{var ne;(ne=H.current)==null||ne.click()},Ne=async ne=>{var Ie,le;try{await hp(u,ne);const Xe=await Ps(u),ze=Array.isArray(Xe==null?void 0:Xe.participants)?Xe.participants:[];if(ze.length){const tt=ze.map(Qe=>{const rt=Qe.participantType||Qe.participant_type||"participant",qe=Qe.userId||Qe.user_id||"",ct=Qe.userName||Qe.user_name||Qe.userEmail||Qe.user_email||"User",$s=Qe.userEmail||Qe.user_email||"",ns=ct.split(" ").map(yt=>yt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:ct,avatar:ns,role:we(rt),status:"offline",email:$s,lastSeen:void 0,permissions:["read"],userId:qe}});me(tt),X.current&&X.current.connected&&X.current.emit("request:online-users",{requestId:u})}O(!1),L({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),V(!0)}catch(Xe){throw console.error("Failed to add spectator:",Xe),L({success:!1,title:"Failed to Add Spectator",message:((le=(Ie=Xe==null?void 0:Xe.response)==null?void 0:Ie.data)==null?void 0:le.error)||"Failed to add spectator. Please try again."}),V(!0),Xe}},Ue=async(ne,Ie,le)=>{var Xe,ze;if(c)await c(ne,Ie,le),k(!1);else try{await xp(u,ne,Ie,le);const tt=await Ps(u),Qe=Array.isArray(tt==null?void 0:tt.participants)?tt.participants:[];if(Qe.length){const rt=Qe.map(qe=>{const ct=qe.participantType||qe.participant_type||"participant",$s=qe.userId||qe.user_id||"",ns=qe.userName||qe.user_name||qe.userEmail||qe.user_email||"User",yt=qe.userEmail||qe.user_email||"",mt=ns.split(" ").map(Ft=>Ft[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:ns,avatar:mt,role:we(ct),status:"offline",email:yt,lastSeen:void 0,permissions:["read"],userId:$s}});me(rt),X.current&&X.current.connected&&X.current.emit("request:online-users",{requestId:u})}k(!1),L({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${le} with ${Ie}h TAT`}),V(!0)}catch(tt){throw console.error("Failed to add approver:",tt),L({success:!1,title:"Failed to Add Approver",message:((ze=(Xe=tt==null?void 0:tt.response)==null?void 0:Xe.data)==null?void 0:ze.error)||"Failed to add approver. Please try again."}),V(!0),tt}},nt=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],ot=ne=>{const Ie=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,le=[];let Xe;for(;(Xe=Ie.exec(ne))!==null;)if(Xe[1]){const ze=Xe.index+Xe[0].length,tt=ne.slice(ze),Qe=ne[ze];(tt.startsWith("@")||!Qe||/\s|[.,!?;:]|@/.test(Qe))&&le.push(Xe[1].trim())}return le},Tt=ne=>{ne.key==="Enter"&&!ne.shiftKey&&(ne.preventDefault(),Te())},Mt=(ne,Ie)=>{S(le=>le.map(Xe=>{if(Xe.id===ne){const ze=Xe.reactions||[],tt=ze.find(Qe=>Qe.emoji===Ie);if(tt)if(tt.users.includes("You")){if(tt.users=tt.users.filter(Qe=>Qe!=="You"),tt.users.length===0)return{...Xe,reactions:ze.filter(Qe=>Qe.emoji!==Ie)}}else tt.users.push("You");else ze.push({emoji:Ie,users:["You"]});return{...Xe,reactions:ze}}return Xe}))};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(Vs,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"text-lg sm:text-2xl font-bold text-gray-900",children:"Work Notes"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("p",{className:"text-gray-600 text-sm sm:text-base truncate",children:Y.title}),e.jsx(re,{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:[Se.slice(0,3).map((ne,Ie)=>e.jsx(os,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(cs,{className:"bg-blue-500 text-white text-xs font-semibold",children:ne.avatar})},Ie)),Se.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:["+",Se.length-3]})]})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>I(!C),className:"lg:hidden",children:e.jsx(Zt,{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(ys,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(ke,{placeholder:"Search messages...",value:f,onChange:ne=>j(ne.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:[Je.map(ne=>{const Ie=ne.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${ne.isSystem?"justify-center":Ie?"justify-end":""}`,children:[!ne.isSystem&&!Ie&&e.jsx(os,{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(cs,{className:`text-white font-semibold text-xs sm:text-sm ${ne.user.role==="Initiator"?"bg-green-600":ne.user.role==="Current User"?"bg-blue-500":ne.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:ne.user.avatar})}),e.jsx("div",{className:`${Ie?"max-w-[70%]":"flex-1"} min-w-0 ${ne.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:ne.isSystem?e.jsxs("div",{className:"inline-flex items-center gap-2 sm:gap-3 px-3 sm:px-4 py-1.5 sm:py-2 bg-gray-100 rounded-full",children:[e.jsx(Bt,{className:"w-3 h-3 sm:w-4 sm:h-4 text-gray-500 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm text-gray-700",children:ne.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:gs(ne.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${Ie?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[ne.user.name," ",Ie&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(re,{variant:"outline",className:"text-xs flex-shrink-0",children:ne.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(ne.timestamp)]}),ne.isHighPriority&&e.jsxs(re,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(Db,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${Ie?"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:BT(ne.content)}}),ne.attachments&&ne.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:ne.attachments.map((le,Xe)=>{const ze=le.fileSize||le.file_size,tt=le.fileName||le.file_name||le.name,Qe=le.fileType||le.file_type||le.type||"",rt=le.attachmentId||le.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(Dx,{type:Qe})}),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}),ze&&e.jsx("p",{className:"text-xs text-gray-500",children:VT(ze)})]}),rt&&(()=>{const qe=(Qe||"").toLowerCase();return qe.includes("image")||qe.includes("pdf")||qe.includes("jpg")||qe.includes("jpeg")||qe.includes("png")||qe.includes("gif")})()&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-purple-100 hover:text-purple-600",onClick:qe=>{qe.preventDefault(),qe.stopPropagation();const ct=Lw(rt);z({fileName:tt,fileType:Qe,fileUrl:ct,fileSize:ze,attachmentId:rt})},title:"Preview file",children:e.jsx(Nt,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-blue-100 hover:text-blue-600",onClick:async qe=>{if(qe.preventDefault(),qe.stopPropagation(),!rt){G.error("Cannot download: Attachment ID missing");return}try{await tu(rt)}catch{G.error("Failed to download file")}},title:"Download file",children:e.jsx(At,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Xe)})})}),ne.reactions&&ne.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:[ne.reactions.map((le,Xe)=>e.jsxs("button",{onClick:()=>Mt(ne.id,le.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${le.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:le.emoji}),e.jsx("span",{className:"text-xs font-medium",children:le.users.length})]},Xe)),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>v(!y),children:e.jsx(bs,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!ne.isSystem&&Ie&&e.jsx(os,{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(cs,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:ne.user.avatar})})]},ne.id)}),e.jsx("div",{ref:U})]})}),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:H,onChange:q,className:"hidden",multiple:!0,accept:$.allowedFileTypes.map(ne=>`.${ne}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((ne,Ie)=>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(Dx,{type:ne.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:ne.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(ne.size/1024).toFixed(1)," KB"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>ue(Ie),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"})})]},Ie))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const ne=g.lastIndexOf("@"),Ie=ne>=0;if(!Ie)return null;const le=g.slice(ne+1),Xe=le.trim(),ze=le.endsWith(" "),tt=Xe.length>0,Qe=Xe.includes(" ")&&!ze,rt=ze&&tt;if(!(Ie&&le.length<=20&&!Qe&&!rt))return null;const ct=Xe.toLowerCase(),$s=ee.filter(ns=>ns.userId===N?!1:ct?ns.name.toLowerCase().includes(ct):!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:$s.length>0?$s.map((ns,yt)=>e.jsxs("button",{type:"button",onClick:mt=>{mt.preventDefault(),mt.stopPropagation();const Ft=g.lastIndexOf("@"),Ss=g.slice(0,Ft);b(Ss+"@"+ns.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(os,{className:"h-10 w-10",children:e.jsx(cs,{className:`text-white text-sm font-semibold ${ns.role==="Initiator"?"bg-green-600":ns.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:ns.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:ns.name}),e.jsx("p",{className:"text-xs text-gray-600",children:ns.role})]})]},yt)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:ct?`No participants found matching "${ct}"`:"No other participants available"})})]})})(),e.jsx(Os,{placeholder:Ve?"Spectators cannot send messages":"Type your message... Use @username to mention someone",value:g,onChange:ne=>b(ne.target.value),onKeyPress:Tt,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,disabled:Ve}),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(E,{variant:"ghost",size:"sm",onClick:()=>v(!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:nt.map((ne,Ie)=>e.jsx("button",{onClick:()=>Pe(ne),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:ne,children:ne},Ie))})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-shrink-0",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:ve,disabled:Ve,title:Ve?"Spectators cannot attach files":"Attach file",children:e.jsx(Qi,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>v(!y),disabled:Ve,title:Ve?"Spectators cannot add emojis":"Add emoji",children:e.jsx(Fb,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>b(ne=>ne+"@"),disabled:Ve,title:Ve?"Spectators cannot mention users":"Mention someone",children:e.jsx(el,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto flex-shrink-0",children:[e.jsxs("span",{className:"text-xs text-gray-500 hidden md:inline whitespace-nowrap",children:[g.length,"/2000"]}),e.jsxs(E,{onClick:Te,disabled:!g.trim()&&D.length===0||Ve,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",title:Ve?"Spectators cannot send messages":"Send",children:[e.jsx(ph,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),C&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>I(!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 ${C?"fixed right-0 top-0 bottom-0 z-50 shadow-xl":"hidden lg:flex"} - `,children:[e.jsxs("div",{className:"p-4 sm:p-6 border-b border-gray-200 flex-1 flex flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:[e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900",children:"Participants"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>I(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(jt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:ee.map((ne,Ie)=>{const le=ne.userId===N;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(os,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(cs,{className:`text-white font-semibold text-sm ${ne.role==="Initiator"?"bg-green-600":le?"bg-blue-500":"bg-slate-600"}`,children:ne.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${$T(ne.status)}`})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium text-gray-900 truncate text-sm sm:text-base",children:[ne.name," ",le&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-xs text-gray-500",children:ne.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:UT(ne.status)})]}),ne.lastSeen&&ne.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:ne.lastSeen})]})]},Ie)})})]}),!Ve&&e.jsxs("div",{className:"p-4 sm:p-6 flex-shrink-0",children:[e.jsx("h4",{className:"font-semibold text-gray-900 mb-3 text-sm sm:text-base",children:"Quick Actions"}),e.jsxs("div",{className:"space-y-2",children:[l&&e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>k(!0),children:[e.jsx(qi,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>O(!0),children:[e.jsx(Nt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),A&&e.jsx(Or,{fileName:A.fileName,fileType:A.fileType,fileUrl:A.fileUrl,fileSize:A.fileSize,attachmentId:A.attachmentId,onDownload:tu,open:!!A,onClose:()=>z(null)}),!Ve&&e.jsx(o0,{open:F,onClose:()=>O(!1),onConfirm:Ne,requestIdDisplay:u,requestTitle:Y.title,existingParticipants:Oe}),!Ve&&l&&e.jsx(c0,{open:P,onClose:()=>k(!1),onConfirm:Ue,requestIdDisplay:u,requestTitle:Y.title,existingParticipants:Oe,currentLevels:d,maxApprovalLevels:m,onPolicyViolation:p}),e.jsx(pt,{open:K.open,onOpenChange:ne=>se(Ie=>({...Ie,open:ne})),children:e.jsxs(ut,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(xt,{className:"flex items-center gap-2",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:K.errors.map((ne,Ie)=>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:ne.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:ne.reason})]},Ie))}),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: ",$.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",$.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(It,{children:e.jsx(E,{onClick:()=>se({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(l0,{open:R,onClose:()=>V(!1),success:M.success,title:M.title,message:M.message})]})}function zT({requestId:t,requestTitle:s,mergedMessages:a,setWorkNoteAttachments:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:d,onPolicyViolation:c}){return e.jsx("div",{className:"h-[calc(100vh-300px)] min-h-[600px]",children:e.jsx(d0,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:d,onPolicyViolation:c})})}function HT({summary:t,loading:s,onShare:a,isInitiator:r}){const n=o=>{const d=o.toLowerCase();return d==="approved"?e.jsx($e,{className:"h-4 w-4 text-green-600"}):d==="rejected"?e.jsx(Ct,{className:"h-4 w-4 text-red-600"}):d==="pending"||d==="in progress"?e.jsx(st,{className:"h-4 w-4 text-orange-600"}):e.jsx(De,{className:"h-4 w-4 text-gray-600"})},i=o=>{const d=o.toLowerCase();return d==="approved"?"bg-green-100 text-green-700 border-green-300":d==="rejected"?"bg-red-100 text-red-700 border-red-300":d==="pending"||d==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},l=(o,d)=>o&&o.trim()&&o.trim().toUpperCase()!=="N/A"?o:d&&d.trim()&&d.trim().toUpperCase()!=="N/A"?d:"N/A";return s?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ke,{className:"h-12 w-12 animate-spin text-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading summary..."})]})}):t?e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200",children:[e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:t.title}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Request #",t.requestNumber]})]}),r&&a?e.jsxs(E,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(ln,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(re,{className:i(t.workflow.status),children:[n(t.workflow.status),e.jsx("span",{className:"ml-1 capitalize",children:t.workflow.status})]})]}),t.description&&e.jsx("div",{className:"mb-4",children:e.jsx(Is,{content:t.description,className:"text-gray-700"})})]}),e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Initiator"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.status})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:et(new Date(t.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),t.approvers&&t.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),t.approvers.map((o,d)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsx("h4",{className:"text-md font-semibold text-gray-800 mb-3",children:o.levelName||`Approver ${o.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:o.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:l(o.designation,o.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1",children:[n(o.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o.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(o.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),o.remarks?e.jsx(Is,{content:o.remarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]},d))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),t.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(re,{variant:"outline",className:"text-xs",children:"AI Generated"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),t.closingRemarks?e.jsx(Is,{content:t.closingRemarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]})]})]})}):e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(De,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-bold text-gray-900 mb-2",children:"Summary Not Available"}),e.jsx("p",{className:"text-gray-600",children:"Summary has not been generated for this request yet."})]})})}function WT({sla:t,requestStatus:s,isPaused:a=!1,testId:r="sla-progress"}){if(!(t&&(t.percentageUsed!==void 0||t.elapsedHours!==void 0))||s==="approved"||s==="rejected"||s==="closed")return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${r}-status-only`,children:[s==="closed"?e.jsx(rr,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx($e,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(Ct,{className:"h-4 w-4 text-red-600"}):e.jsx(st,{className:"h-4 w-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-medium text-gray-700",children:s==="closed"?"Request Closed":s==="approved"?"Request Approved":s==="rejected"?"Request Rejected":"SLA Not Available"})]});const i=t.percentageUsed!==void 0?t.percentageUsed:0,l=t.status||"on_track",d=a?{badge:"bg-gray-500 text-white",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-500"}:i>=100?{badge:"bg-red-600 text-white animate-pulse",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:i>=75?{badge:"bg-orange-500 text-white",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:i>=50?{badge:"bg-amber-500 text-white",progress:"bg-amber-500",text:"text-amber-600",icon:"text-blue-600"}:{badge:"bg-green-600 text-white",progress:"bg-green-600",text:"text-gray-700",icon:"text-blue-600"},c=l==="on_track"||l==="normal"?"normal":l;return e.jsxs("div",{"data-testid":r,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[a?e.jsx(rr,{className:`h-4 w-4 ${d.icon}`}):e.jsx(st,{className:`h-4 w-4 ${d.icon}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:a?"SLA Progress (Paused)":"SLA Progress"})]}),e.jsxs(re,{className:`text-xs ${d.badge}`,"data-testid":`${r}-badge`,children:[i,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(qs,{value:i,className:"h-3 mb-2",indicatorClassName:d.progress,"data-testid":`${r}-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsxs("span",{className:"text-gray-600","data-testid":`${r}-elapsed`,children:[Xt(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${c==="breached"||c==="critical"?d.text:"text-gray-700"}`,"data-testid":`${r}-remaining`,children:[Xt(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${r}-deadline`,children:["Due: ",ka(t.deadline,!0)," • ",i,"% elapsed"]}),c==="critical"&&e.jsxs("p",{className:"text-xs text-orange-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-critical`,children:[e.jsx(ts,{className:"h-3.5 w-3.5"}),"Approaching Deadline"]}),c==="breached"&&e.jsxs("p",{className:"text-xs text-red-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-breached`,children:[e.jsx(Ei,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function GT({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var g,b;const d=_T((t==null?void 0:t.priority)||"standard"),c=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",m=(g=t==null?void 0:t.form16Submission)==null?void 0:g.displayStatus,p=m&&/balance mismatch|failed/i.test(String(m)),x=m&&String(m).toLowerCase()==="duplicate",u=c&&m?{color:p?"bg-red-100 !text-red-800 border-red-200":m==="Completed"?"bg-green-100 !text-green-800 border-green-200":x?"bg-amber-100 !text-amber-800 border-amber-200":"bg-gray-100 !text-gray-700 border-gray-200",icon:Rx((t==null?void 0:t.status)||"pending").icon,label:m}:Rx((t==null?void 0:t.status)||"pending");return e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-300 mb-4 sm:mb-6","data-testid":"request-detail-header",children:[e.jsxs("div",{className:"p-3 sm:p-4 md:p-6 border-b border-gray-300",children:[e.jsxs("div",{className:"flex items-start sm:items-center justify-between gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:a,className:"rounded-lg flex-shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"back-button",children:e.jsx(ws,{className:"h-4 w-4 sm:h-5 sm:h-5"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(De,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 min-w-0 flex-1",children:[e.jsx("h1",{className:"text-sm sm:text-base md:text-lg font-bold text-gray-900 truncate","data-testid":"request-id",children:t.id||"N/A"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2",children:[e.jsx(re,{className:`${d.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"priority-badge",children:d.label}),e.jsx(re,{className:`${u.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:u.label}),(()=>{const f=(t==null?void 0:t.workflowType)||(t==null?void 0:t.workflow_type),j=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",y=(j==null?void 0:j.toString().toUpperCase())||"",v=y==="FORM_16",w=f==="CLAIM_MANAGEMENT"||j==="claim-management",S=f==="DEALER_CLAIM"||y==="DEALER CLAIM"||y==="DEALER_CLAIM";let C="Non-Templatized",I="bg-purple-100 !text-purple-600 border-purple-200";return v?(C="Form 16",I="bg-emerald-100 !text-emerald-700 border-emerald-200"):S?(C="Dealer Claim",I="bg-blue-100 !text-blue-700 border-blue-200"):w?(C="Claim Management",I="bg-blue-100 !text-blue-700 border-blue-200"):y==="TEMPLATE"&&(C="Template"),e.jsx(re,{className:`${I} rounded-full px-2 sm:px-3 text-xs shrink-0`,variant:"outline","data-testid":"template-type-badge",children:C})})()]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&i&&((b=t==null?void 0:t.status)==null?void 0:b.toLowerCase())==="closed"&&e.jsxs(E,{variant:"default",size:"sm",className:"gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9",onClick:n,"data-testid":"share-summary-button",children:[e.jsx(ln,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Share Summary"})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9",onClick:r,disabled:s,"data-testid":"refresh-button",children:[e.jsx(Et,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:s?"Refreshing...":"Refresh"})]})]})]}),e.jsx("div",{className:"mt-3 ml-0 sm:ml-14",children:e.jsx("h2",{className:"text-base sm:text-lg md:text-xl font-semibold text-gray-900 line-clamp-2","data-testid":"request-title",children:t.title})})]}),l!==void 0&&e.jsx("div",{className:`px-3 sm:px-4 md:px-6 py-3 sm:py-4 border-b border-gray-200 ${o?"bg-gradient-to-r from-gray-100 to-gray-200":"bg-gradient-to-r from-blue-50 to-indigo-50"}`,"data-testid":"sla-section",children:e.jsx(WT,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function Zc(t){return(await be.get(`/summaries/${t}`)).data.data}async function YT(t,s){return(await be.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function KT(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await be.get("/summaries/shared",{params:{page:s,limit:a}});return{data:((n=r.data.data)==null?void 0:n.data)||r.data.data||[],pagination:((i=r.data.data)==null?void 0:i.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function m0(t){await be.patch(`/summaries/shared/${t}/view`)}async function u0(t){var s;try{return(await be.get(`/summaries/request/${t}`)).data.data}catch(a){return((s=a==null?void 0:a.response)==null?void 0:s.status)===404,null}}async function QT(t){return(await be.get(`/summaries/${t}/recipients`)).data.data||[]}function XT({activityInfo:t,className:s,createdAt:a,updatedAt:r}){if(!t)return console.warn("[ActivityInformationCard] activityInfo is missing"),e.jsx(Z,{className:s,children:e.jsx(te,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Activity information not available"})})});const n=l=>{const o=typeof l=="string"?parseFloat(l):l;return isNaN(o)?"N/A":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`},i=l=>{if(!l)return"N/A";try{return et(new Date(l),"MMM d, yyyy")}catch{return l}};return e.jsxs(Z,{className:s,children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx(ht,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsxs(te,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.activityName})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Type"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.activityType})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Location"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(Xo,{className:"w-4 h-4 text-gray-400"}),t.location]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Requested Date"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:i(t.requestedDate)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Estimated Budget"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(Ga,{className:"w-4 h-4 text-green-600"}),t.estimatedBudget!==void 0&&t.estimatedBudget!==null?n(t.estimatedBudget):"TBD"]})]}),t.closedExpenses!==void 0&&t.closedExpenses!==null&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Closed Expenses"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-blue-600"}),n(t.closedExpensesBreakdown&&t.closedExpensesBreakdown.length>0?t.closedExpensesBreakdown.reduce((l,o)=>l+(o.totalAmt||Number(o.amount)+Number(o.gstAmt||0)),0):t.closedExpenses)]})]}),t.period&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Period"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1",children:[i(t.period.startDate)," - ",i(t.period.endDate)]})]})]}),t.closedExpensesBreakdown&&t.closedExpensesBreakdown.length>0&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Closed Expenses Breakdown"}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full text-xs sm:text-sm",children:[e.jsx("thead",{className:"bg-blue-100/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left font-semibold text-blue-900",children:"Description"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-24",children:"Base"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-24",children:"GST"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-28",children:"Total"})]})}),e.jsxs("tbody",{className:"divide-y divide-blue-200/50",children:[t.closedExpensesBreakdown.map((l,o)=>e.jsxs("tr",{className:"hover:bg-blue-100/30",children:[e.jsxs("td",{className:"px-3 py-2 text-gray-700",children:[l.description,l.gstRate?e.jsxs("span",{className:"text-[10px] text-gray-400 block",children:[l.gstRate,"% GST"]}):null]}),e.jsx("td",{className:"px-3 py-2 text-right text-gray-900",children:n(l.amount)}),e.jsx("td",{className:"px-3 py-2 text-right text-gray-900",children:n(l.gstAmt||0)}),e.jsx("td",{className:"px-3 py-2 text-right font-medium text-gray-900",children:n(l.totalAmt||Number(l.amount)+Number(l.gstAmt||0))})]},o)),e.jsxs("tr",{className:"bg-blue-100/50 font-bold",children:[e.jsx("td",{colSpan:3,className:"px-3 py-2 text-blue-900",children:"Final Claim Amount"}),e.jsx("td",{className:"px-3 py-2 text-right text-blue-700",children:n(t.closedExpensesBreakdown.reduce((l,o)=>l+(o.totalAmt||Number(o.amount)+Number(o.gstAmt||0)),0))})]})]})]})})]}),t.description&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Description"}),e.jsx("div",{className:"mt-2 bg-gray-50 p-3 rounded-lg border border-gray-200",children:e.jsx(Is,{content:t.description||"",className:"text-sm"})})]}),(a||r)&&e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t border-gray-300",children:[a&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Created"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:gs(a)})]}),r&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Last Updated"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:gs(r)})]})]})]})]})}function JT({dealerInfo:t,className:s}){return t?!t.dealerCode&&!t.dealerName?(console.warn("[DealerInformationCard] Dealer info missing essential fields:",t),e.jsx(Z,{className:s,children:e.jsx(te,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information incomplete"})})})):e.jsxs(Z,{className:s,children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx(tl,{className:"w-5 h-5 text-purple-600"}),"Dealer Information"]})}),e.jsxs(te,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Code"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.dealerCode})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.dealerName})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Contact Information"}),e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx(ja,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{children:t.email})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx(Kn,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{children:t.phone})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-gray-700",children:[e.jsx(Xo,{className:"w-4 h-4 text-gray-400 mt-0.5"}),e.jsx("span",{children:t.address})]})]})]})]})]}):(console.warn("[DealerInformationCard] dealerInfo is missing"),e.jsx(Z,{className:s,children:e.jsx(te,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information not available"})})}))}function ZT({ioDetails:t,dmsDetails:s,claimAmount:a,estimatedBudgetBreakdown:r,closedExpensesBreakdown:n,visibility:i,onEditClaimAmount:l,className:o}){const d=x=>x==null||Number.isNaN(x)?"₹0.00":`₹${x.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,c=x=>{if(!x)return"";try{return et(new Date(x),"MMM d, yyyy, h:mm a")}catch{return x||""}},m=x=>!x||x.length===0?0:x.reduce((u,g)=>u+(g.totalAmt??g.amount+(g.gstAmt??0)),0);return i.showIODetails&&t||i.showDMSDetails&&s||(s==null?void 0:s.creditNoteWfmData)&&s.creditNoteWfmData.length>0||i.showClaimAmount&&a&&a.amount!==void 0&&a.amount!==null||r&&r.length>0||n&&n.length>0?e.jsxs(Z,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${o}`,children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"text-base flex items-center gap-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-blue-600"}),"Process Details"]}),e.jsx(ye,{children:"Workflow reference numbers"})]}),e.jsxs(te,{className:"space-y-3",children:[i.showIODetails&&t&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-blue-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-blue-600"}),e.jsx(ae,{className:"text-xs font-semibold text-blue-900 uppercase tracking-wide",children:"IO Number"})]}),e.jsx("p",{className:"font-bold text-gray-900 mb-2",children:t.ioNumber}),t.remarks&&e.jsxs("div",{className:"pt-2 border-t border-blue-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Remark:"}),e.jsx("p",{className:"text-xs text-gray-900",children:t.remarks})]}),(t.availableBalance!==void 0||t.blockedAmount!==void 0)&&e.jsxs("div",{className:"pt-2 border-t border-blue-100 mt-2 space-y-1",children:[t.availableBalance!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Available Balance:"}),e.jsx("span",{className:"font-medium text-gray-900",children:d(t.availableBalance)})]}),t.blockedAmount!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Blocked Amount:"}),e.jsx("span",{className:"font-medium text-blue-700",children:d(t.blockedAmount)})]}),t.remainingBalance!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Remaining Balance:"}),e.jsx("span",{className:"font-medium text-green-700",children:d(t.remainingBalance)})]})]}),e.jsxs("div",{className:"pt-2 border-t border-blue-100 mt-2",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["By ",t.blockedByName]}),e.jsx("p",{className:"text-xs text-gray-500",children:c(t.blockedAt)})]})]}),i.showDMSDetails&&s&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-purple-600"}),e.jsx(ae,{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"E-Invoice Details"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-2",children:s.ackNo&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Ack No"}),e.jsx("p",{className:"font-bold text-sm text-purple-700",children:s.ackNo})]})}),s.irn&&e.jsxs("div",{className:"mb-2 p-2 bg-purple-50 rounded border border-purple-100",children:[e.jsx("p",{className:"text-[10px] text-purple-600 uppercase font-semibold",children:"IRN"}),e.jsx("p",{className:"text-[10px] font-mono break-all text-gray-700 leading-tight",children:s.irn})]}),s.signedInvoiceUrl&&e.jsxs(E,{variant:"outline",size:"sm",className:"w-full h-8 text-xs gap-2 mb-2 border-purple-200 text-purple-700 hover:bg-purple-50",onClick:()=>window.open(s.signedInvoiceUrl,"_blank"),children:[e.jsx(Pt,{className:"w-3.5 h-3.5"}),"View E-Invoice"]}),s.remarks&&e.jsxs("div",{className:"pt-2 border-t border-purple-100",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase mb-1",children:"Remarks"}),e.jsx("p",{className:"text-xs text-gray-900",children:s.remarks})]}),e.jsxs("div",{className:"pt-2 border-t border-purple-100 mt-2",children:[e.jsxs("p",{className:"text-[10px] text-gray-500",children:["By ",s.createdByName]}),e.jsx("p",{className:"text-[10px] text-gray-500",children:c(s.createdAt)})]})]}),(s==null?void 0:s.creditNoteWfmData)&&s.creditNoteWfmData.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-pink-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-pink-600"}),e.jsx(ae,{className:"text-xs font-semibold text-pink-900 uppercase tracking-wide",children:"Credit Note Validation"})]}),e.jsx("div",{className:"space-y-2",children:s.creditNoteWfmData.map((x,u)=>e.jsxs("div",{className:"bg-pink-50 p-2 rounded border border-pink-100 text-[10px]",children:[e.jsxs("div",{className:"flex justify-between mb-1 text-pink-900",children:[e.jsxs("span",{className:"font-semibold break-words flex-1 pr-2",children:["Credit Note No: ",x.DOC_NO||"N/A"]}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-sm text-white font-medium self-start whitespace-nowrap ${x.MSG_TYP==="E"?"bg-red-500":"bg-green-500"}`,children:x.MSG_TYP==="E"?"Error":x.MSG_TYP==="S"?"Success":x.MSG_TYP||"Unknown"})]}),e.jsxs("div",{className:"text-gray-500 mb-0.5",children:["Txn: ",x.TRNS_UNIQ_NO||"N/A"]}),e.jsx("div",{className:"text-gray-700 break-words font-medium",children:x.MESSAGE||"No Message"})]},u))})]}),i.showClaimAmount&&a&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"w-4 h-4 text-green-600"}),e.jsx(ae,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),i.canEditClaimAmount&&l&&e.jsxs(E,{variant:"outline",size:"sm",onClick:l,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(_i,{className:"w-3 h-3 mr-1 text-green-700"}),"Edit"]})]}),e.jsx("p",{className:"text-2xl font-bold text-green-700",children:d(a.amount)}),a.lastUpdatedBy&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-green-100",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["Last updated by ",a.lastUpdatedBy]}),a.lastUpdatedAt&&e.jsx("p",{className:"text-xs text-gray-500",children:c(a.lastUpdatedAt)})]})]}),r&&r.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-amber-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-amber-600"}),e.jsx(ae,{className:"text-xs font-semibold text-amber-900 uppercase tracking-wide",children:"Estimated Budget Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[r.map((x,u)=>e.jsxs("div",{className:"flex justify-between items-center text-[10px] sm:text-xs",children:[e.jsx("div",{className:"text-gray-700 truncate mr-2",title:x.description,children:x.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:d(x.totalAmt??x.amount+(x.gstAmt??0))})]},u)),e.jsxs("div",{className:"pt-2 border-t border-amber-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-amber-700",children:d(m(r))})]})]})]}),n&&n.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-indigo-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-indigo-600"}),e.jsx(ae,{className:"text-xs font-semibold text-indigo-900 uppercase tracking-wide",children:"Closed Expenses Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[n.map((x,u)=>e.jsxs("div",{className:"flex justify-between items-center text-[10px] sm:text-xs",children:[e.jsx("div",{className:"text-gray-700 truncate mr-2",title:x.description,children:x.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:d(x.totalAmt??x.amount+(x.gstAmt??0))})]},u)),e.jsxs("div",{className:"pt-2 border-t border-indigo-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-indigo-700",children:d(m(n))})]})]})]})]})]}):null}function qT({proposalDetails:t,className:s}){const r=(()=>{const o=t.totalEstimatedBudget??t.estimatedBudgetTotal;return o??(t.costBreakup&&t.costBreakup.length>0?t.costBreakup.reduce((c,m)=>{const p=m.amount||0,x=m.gstAmt||0,u=m.totalAmt||Number(p)+Number(x);return c+(Number.isNaN(u)?0:u)},0):0)})(),n=o=>o==null||Number.isNaN(o)?"₹0.00":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,i=o=>{if(!o)return"";try{return et(new Date(o),"MMM d, yyyy, h:mm a")}catch{return o||""}},l=o=>{if(!o)return"-";try{return et(new Date(o),"MMM d, yyyy")}catch{return o||"-"}};return e.jsxs(Z,{className:s,children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx(Pt,{className:"w-5 h-5 text-green-600"}),"Proposal Details"]}),t.submittedOn&&e.jsxs(ye,{children:["Submitted on ",i(t.submittedOn)]})]}),e.jsxs(te,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Cost Breakup"}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-gray-50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-left text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Item Description"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Base Amount"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"GST"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Total"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-200",children:[(t.costBreakup||[]).map((o,d)=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsxs("td",{className:"px-4 py-3 text-sm text-gray-900",children:[e.jsx("div",{children:o.description}),o.gstRate?e.jsx("div",{className:"text-[10px] text-gray-400",children:o.cgstAmt?`CGST: ${o.gstRate/2}%, SGST: ${o.gstRate/2}%`:`IGST: ${o.gstRate}%`}):null]}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right",children:n(o.amount)}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right",children:n(o.gstAmt)}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right font-medium",children:n(o.totalAmt||Number(o.amount||0)+Number(o.gstAmt||0))})]},d)),e.jsxs("tr",{className:"bg-green-50 font-semibold",children:[e.jsx("td",{colSpan:3,className:"px-4 py-3 text-sm text-gray-900",children:"Estimated Budget (Total Inclusive of GST)"}),e.jsx("td",{className:"px-4 py-3 text-sm text-green-700 text-right",children:n(r)})]})]})]})})]}),e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Timeline for Closure"}),e.jsx("div",{className:"mt-2 bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ht,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{className:"text-sm font-medium text-gray-900",children:["Expected completion by: ",l(t.timelineForClosure)]})]})})]}),t.dealerComments&&e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Comments"}),e.jsx("p",{className:"text-sm text-gray-700 mt-2 bg-gray-50 p-3 rounded-lg whitespace-pre-line",children:t.dealerComments})]})]})]})}function e5({initiatorInfo:t,className:s}){const a=r=>r.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2);return e.jsxs(Z,{className:s,children:[e.jsx(oe,{children:e.jsx(ce,{className:"text-base",children:"Request Initiator"})}),e.jsx(te,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(os,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(cs,{className:"bg-gray-700 text-white font-semibold text-lg",children:a(t.name)})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:t.name}),t.role&&e.jsx("p",{className:"text-sm text-gray-600",children:t.role}),t.department&&e.jsx("p",{className:"text-sm text-gray-500",children:t.department}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[e.jsx(ja,{className:"w-4 h-4"}),e.jsx("span",{children:t.email})]}),t.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[e.jsx(Kn,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function x0(t,s){var a,r;try{if(!Yn(t))return null;const n=t.claimDetails||{},i=t.proposalDetails||{},l=t.completionDetails||{},o=t.internalOrder||t.internal_order||{},d=t.budgetTracking||t.budget_tracking||{},c=t.invoice||{},m=t.creditNote||t.credit_note||{},p=t.completionExpenses||t.completion_expenses||[],x=n.periodStartDate||n.period_start_date,u=n.periodEndDate||n.period_end_date,g=n.activityName||n.activity_name||"",b=n.activityType||n.activity_type||"",f=n.location||"",j=d.proposalEstimatedBudget??d.proposal_estimated_budget??d.initialEstimatedBudget??d.initial_estimated_budget??n.estimatedBudget??n.estimated_budget,y=(d==null?void 0:d.closedExpenses)??(d==null?void 0:d.closed_expenses)??(l==null?void 0:l.totalClosedExpenses)??(l==null?void 0:l.total_closed_expenses)??(n==null?void 0:n.closedExpenses)??(n==null?void 0:n.closed_expenses),v=y!=null?Number(y):void 0,w=Array.isArray(p)&&p.length>0?p.map(A=>({description:A.description||A.itemDescription||A.item_description||"",amount:Number(A.amount)||0,gstRate:A.gstRate??A.gst_rate,gstAmt:A.gstAmt??A.gst_amt,cgstAmt:A.cgstAmt??A.cgst_amt,sgstAmt:A.sgstAmt??A.sgst_amt,igstAmt:A.igstAmt??A.igst_amt,totalAmt:A.totalAmt??A.total_amt})):(l==null?void 0:l.closedExpenses)||(l==null?void 0:l.closed_expenses)||(l==null?void 0:l.closedExpensesBreakdown)||[],S={activityName:g,activityType:b,defaultGstRate:n.defaultGstRate||18,requestedDate:n.activityDate||n.activity_date||t.createdAt,location:f,period:x&&u?{startDate:x,endDate:u}:void 0,estimatedBudget:j,closedExpenses:v,closedExpensesBreakdown:w,description:t.description||""},C={dealerCode:(n==null?void 0:n.dealerCode)||(n==null?void 0:n.dealer_code)||(n==null?void 0:n.DealerCode)||"",dealerName:(n==null?void 0:n.dealerName)||(n==null?void 0:n.dealer_name)||(n==null?void 0:n.DealerName)||"",email:(n==null?void 0:n.dealerEmail)||(n==null?void 0:n.dealer_email)||(n==null?void 0:n.DealerEmail)||"",phone:(n==null?void 0:n.dealerPhone)||(n==null?void 0:n.dealer_phone)||(n==null?void 0:n.DealerPhone)||"",address:(n==null?void 0:n.dealerAddress)||(n==null?void 0:n.dealer_address)||(n==null?void 0:n.DealerAddress)||""};(!C.dealerCode||!C.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!n,dealerCode:C.dealerCode,dealerName:C.dealerName,rawClaimDetails:n,availableKeys:n?Object.keys(n):[]});const I=(i==null?void 0:i.expectedCompletionDate)||(i==null?void 0:i.expected_completion_date),D=i?{proposalDocumentUrl:i.proposalDocumentUrl||i.proposal_document_url,costBreakup:Array.isArray(i.costItems||i.cost_items)?(i.costItems||i.cost_items).map(A=>({description:A.description||A.itemDescription||A.item_description||"",amount:Number(A.amount)||0,gstRate:Number(A.gstRate??A.gst_rate??0),gstAmt:Number(A.gstAmt??A.gst_amt??0),cgstAmt:Number(A.cgstAmt??A.cgst_amt??0),sgstAmt:Number(A.sgstAmt??A.sgst_amt??0),igstAmt:Number(A.igstAmt??A.igst_amt??0),totalAmt:Number(A.totalAmt??A.total_amt??0)})):Array.isArray(i.costBreakup||i.cost_breakup)?(i.costBreakup||i.cost_breakup).map(A=>({description:A.description||A.itemDescription||A.item_description||"",amount:Number(A.amount)||0,gstRate:A.gstRate??A.gst_rate,gstAmt:A.gstAmt??A.gst_amt,cgstAmt:A.cgstAmt??A.cgst_amt,sgstAmt:A.sgstAmt??A.sgst_amt,igstAmt:A.igstAmt??A.igst_amt,totalAmt:A.totalAmt??A.total_amt})):[],totalEstimatedBudget:i.totalEstimatedBudget||i.total_estimated_budget||0,timelineMode:i.timelineMode||i.timeline_mode,expectedCompletionDate:I,expectedCompletionDays:i.expectedCompletionDays||i.expected_completion_days,timelineForClosure:I,dealerComments:i.dealerComments||i.dealer_comments,submittedOn:i.submittedAt||i.submitted_at||i.submittedOn}:void 0,T={ioNumber:o.ioNumber||o.io_number||n.ioNumber||n.io_number,ioRemark:o.ioRemark||o.io_remark||"",availableBalance:o.ioAvailableBalance||o.io_available_balance||n.ioAvailableBalance||n.io_available_balance,blockedAmount:o.ioBlockedAmount||o.io_blocked_amount||n.ioBlockedAmount||n.io_blocked_amount,remainingBalance:o.ioRemainingBalance||o.io_remaining_balance||n.ioRemainingBalance||n.io_remaining_balance,organizedBy:((a=o.organizer)==null?void 0:a.displayName)||((r=o.organizer)==null?void 0:r.name)||o.organizedBy||"",organizedAt:o.organizedAt||o.organized_at||""},N={eInvoiceNumber:c.invoiceNumber||c.invoice_number||n.eInvoiceNumber||n.e_invoice_number,eInvoiceDate:c.invoiceDate||c.invoice_date||n.eInvoiceDate||n.e_invoice_date,dmsNumber:c.dmsNumber||c.dms_number||n.dmsNumber||n.dms_number,creditNoteNumber:m.creditNoteNumber||m.credit_note_number||n.creditNoteNumber||n.credit_note_number,creditNoteDate:m.creditNoteDate||m.credit_note_date||n.creditNoteDate||n.credit_note_date,creditNoteAmount:m.creditNoteAmount?Number(m.creditNoteAmount):m.credit_note_amount?Number(m.credit_note_amount):m.creditNoteAmount?Number(m.creditNoteAmount):n.creditNoteAmount?Number(n.creditNoteAmount):n.credit_note_amount?Number(n.credit_note_amount):void 0,irn:c.irn||n.irn,ackNo:c.ackNo||n.ackNo,ackDate:c.ackDate||n.ackDate,signedInvoiceUrl:c.signedInvoiceUrl||n.signedInvoiceUrl,taxBreakdown:c.taxBreakdown||n.taxBreakdown,creditNoteWfmData:t.creditNoteWfmData||n.creditNoteWfmData||[]},_={estimated:S.estimatedBudget||0,closed:S.closedExpenses||0};return{activityInfo:S,dealerInfo:C,proposalDetails:D,ioDetails:Object.keys(T).some(A=>T[A])?T:void 0,dmsDetails:Object.keys(N).some(A=>N[A])?N:void 0,claimAmount:_}}catch(n){return console.error("[claimDataMapper] Error mapping claim data:",n),null}}function h0(t,s){var a,r;try{if(t.initiatorId===s||((a=t.initiator)==null?void 0:a.userId)===s||((r=t.requestedBy)==null?void 0:r.userId)===s)return"INITIATOR";if((t.participants||[]).find(c=>{var m;return(c.userId===s||((m=c.user)==null?void 0:m.userId)===s)&&(c.participantType==="DEALER"||c.type==="DEALER")}))return"DEALER";const l=t.approvalLevels||[];return l.find(c=>{var m;return c.levelNumber===3&&(c.approverId===s||((m=c.approver)==null?void 0:m.userId)===s)})?"DEPARTMENT_LEAD":l.find(c=>{var m;return(c.approverId===s||((m=c.approver)==null?void 0:m.userId)===s)&&c.status==="PENDING"})?"APPROVER":"SPECTATOR"}catch(n){return console.error("[claimDataMapper] Error determining user role:",n),"SPECTATOR"}}function p0(t){switch(t){case"INITIATOR":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!0,showDMSDetails:!0,showClaimAmount:!0,canEditClaimAmount:!1};case"DEALER":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!1,showDMSDetails:!1,showClaimAmount:!0,canEditClaimAmount:!1};case"DEPARTMENT_LEAD":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!0,showDMSDetails:!0,showClaimAmount:!0,canEditClaimAmount:!1};case"APPROVER":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!0,showDMSDetails:!0,showClaimAmount:!0,canEditClaimAmount:!1};case"SPECTATOR":default:return{showDealerInfo:!1,showProposalDetails:!1,showIODetails:!1,showDMSDetails:!1,showClaimAmount:!1,canEditClaimAmount:!1}}}function t5({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:l,onReject:o,onPause:d,onResume:c,onRetrigger:m,summaryId:p,refreshTrigger:x,pausedByUserId:u,currentUserId:g,apiRequest:b,onEditClaimAmount:f,hideApproveReject:j=!1}){var k,R,V,M,L;const{user:y}=ds(),[v,w]=h.useState([]),[S,C]=h.useState(!1),[I,D]=h.useState(!1),T=(t==null?void 0:t.status)==="closed",N=((k=t==null?void 0:t.pauseInfo)==null?void 0:k.isPaused)||!1,_=u||((V=(R=t==null?void 0:t.pauseInfo)==null?void 0:R.pausedBy)==null?void 0:V.userId),A=g||(y==null?void 0:y.userId)||"",z=!N&&!T&&(r||s),F=N&&c&&(r||s),O=N&&s&&_&&_!==A&&m;h.useEffect(()=>{if(!N||!r||!(t!=null&&t.requestId)){D(!1);return}(async()=>{var H;try{const $=(((H=(await nr.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:H.notifications)||[]).some(B=>B.requestId===t.requestId&&B.notificationType==="pause_retrigger_request");D($)}catch(X){console.error("Failed to check retrigger notifications:",X),D(!1)}})()},[N,r,t==null?void 0:t.requestId,x]),h.useEffect(()=>{(async()=>{if(!T||!p||!s){w([]);return}try{C(!0);const H=await QT(p);w(H)}catch(H){console.error("Failed to fetch shared recipients:",H),w([])}finally{C(!1)}})()},[T,p,s,x]);const P=h.useMemo(()=>{if(!b||!Yn(b))return null;const U=x0(b);if(!U)return null;const H=h0(b,A),X=p0(H);return{claimRequest:U,visibility:X}},[b,A]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(Z,{"data-testid":"quick-actions-card",children:[e.jsx(oe,{className:"pb-2",children:e.jsx(ce,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(te,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-gray-700 border-gray-300 hover:bg-gray-50 hover:text-gray-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:n,"data-testid":"add-approver-button",children:[e.jsx(qi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-gray-700 border-gray-300 hover:bg-gray-50 hover:text-gray-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:i,"data-testid":"add-spectator-button",children:[e.jsx(Nt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),z&&d&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:d,"data-testid":"pause-workflow-button",children:[e.jsx(lr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),F&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-green-700 border-green-300 hover:bg-green-50 hover:text-green-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:c,"data-testid":"resume-workflow-button",children:[e.jsx(Ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),O&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:m,"data-testid":"request-resume-button",children:[e.jsx(Ze,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Request Resume"]}),e.jsxs("div",{className:"pt-3 sm:pt-4 space-y-2",children:[r&&!N&&!j&&e.jsxs(e.Fragment,{children:[e.jsxs(E,{className:"w-full bg-green-600 hover:bg-green-700 text-white h-9 sm:h-10 text-xs sm:text-sm",onClick:l,"data-testid":"approve-request-button",children:[e.jsx($e,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Approve Request"]}),e.jsxs(E,{variant:"destructive",className:"w-full h-9 sm:h-10 text-xs sm:text-sm",onClick:o,"data-testid":"reject-request-button",children:[e.jsx(Ct,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Reject Request"]})]}),N&&e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children:_===A?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-orange-800 font-medium flex items-center justify-center gap-1.5",children:[I&&e.jsx(Ze,{className:"w-3.5 h-3.5"}),I?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:I?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&_!==A&&I?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-orange-800 font-medium flex items-center justify-center gap-1.5",children:[e.jsx(Ze,{className:"w-3.5 h-3.5"}),"Initiator has requested resume"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"Please review and resume if appropriate"})]}):r&&_!==A?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Workflow is paused"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"You can resume to continue approval"})]}):s&&_&&_!==A?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Approver has paused this workflow"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:O?'Click "Request Resume" to notify approver':"Resume request sent - Waiting for approver"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Workflow is paused"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"Actions are disabled until resumed"})]})})]})]})]}),e.jsxs(Z,{"data-testid":"spectators-card",children:[e.jsx(oe,{className:"pb-2",children:e.jsx(ce,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(te,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((U,H)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${H}`,children:[e.jsx(os,{className:"h-8 w-8",children:e.jsx(cs,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:U.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:U.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:U.role})]})]},H)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),T&&s&&e.jsxs(Z,{"data-testid":"shared-recipients-card",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs(ce,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(ln,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(te,{className:"space-y-3",children:S?e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Loading..."})}):v.length>0?v.map((U,H)=>{const X=(U.displayName||"NA").split(" ").map(J=>J[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${H}`,children:[e.jsx(os,{className:"h-8 w-8",children:e.jsx(cs,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:X})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:U.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:U.email}),U.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},U.userId||H)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),P&&e.jsx(ZT,{ioDetails:P.claimRequest.ioDetails,dmsDetails:P.claimRequest.dmsDetails,claimAmount:{amount:P.claimRequest.claimAmount.closed||P.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:(M=P.claimRequest.proposalDetails)==null?void 0:M.costBreakup,closedExpensesBreakdown:(L=P.claimRequest.activityInfo)==null?void 0:L.closedExpensesBreakdown,visibility:P.visibility,onEditClaimAmount:f})]})}function s5({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:l}){const[o,d]=h.useState(r),[c,m]=h.useState(!1),p=(o==null?void 0:o.length)||0,x=h.useMemo(()=>o.slice(0,500),[o]),u=async()=>{try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(pt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(ut,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-green-100 flex items-center justify-center",children:e.jsx($e,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(xt,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide your approval comments and remarks"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:l||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(re,{className:"bg-green-100 text-green-800 border-green-200",variant:"outline",children:"APPROVE"})]})]}),e.jsxs("div",{className:"space-y-2 mt-4",children:[e.jsx("label",{className:"text-sm font-semibold text-gray-800",children:"Comments & Remarks *"}),e.jsx(Os,{value:x,onChange:g=>d(g.target.value),rows:5,placeholder:"Enter your approval comments and any conditions or notes...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(p,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-green-50 border-green-200 text-green-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx($e,{className:"w-4 h-4"})}),e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-semibold",children:"Approval Confirmation"}),e.jsx("div",{children:"This request will be forwarded to the next approver or completed if this is the final step."})]})]}),e.jsxs(It,{className:"mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,disabled:c,children:"Cancel"}),e.jsxs(E,{onClick:u,disabled:c,className:"bg-green-600 hover:bg-green-700",children:[e.jsx($e,{className:"w-4 h-4 mr-2"}),c?"Approving...":"Approve Request"]})]})]})})}function a5({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:l}){const[o,d]=h.useState(r),[c,m]=h.useState(!1),p=(o==null?void 0:o.length)||0,x=h.useMemo(()=>o.slice(0,500),[o]),u=async()=>{if(!x.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(pt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(ut,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-red-100 flex items-center justify-center",children:e.jsx(Ct,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(xt,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide detailed reasons for rejection"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:l||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(re,{className:"bg-red-100 text-red-800 border-red-200",variant:"outline",children:"REJECT"})]})]}),e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("label",{className:"text-sm font-semibold text-gray-800",children:"Comments & Remarks *"}),e.jsx(Os,{value:x,onChange:g=>d(g.target.value),rows:5,placeholder:"Enter detailed reasons for rejection and any suggestions for improvement...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(p,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-red-50 border-red-200 text-red-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(Ze,{className:"w-4 h-4"})}),e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-semibold",children:"Rejection Guidelines"}),e.jsx("div",{children:"Please provide specific, actionable feedback to help the initiator improve their request."})]})]}),e.jsxs(It,{className:"mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,disabled:c,children:"Cancel"}),e.jsxs(E,{variant:"destructive",onClick:u,disabled:c,children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),c?"Rejecting...":"Reject Request"]})]})]})})}function r5({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:l}){const[o,d]=h.useState(""),[c,m]=h.useState(!1),p=async()=>{if(o.trim())try{m(!0),await a(o.trim()),d(""),s()}catch(u){console.error("Failed to skip approver:",u)}finally{m(!1)}},x=()=>{c||(d(""),s())};return e.jsx(pt,{open:t,onOpenChange:x,children:e.jsxs(ut,{className:"sm:max-w-md max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:x,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:c,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(gt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center",children:e.jsx(Ze,{className:"w-5 h-5 text-orange-600"})}),e.jsx(xt,{className:"text-xl font-bold text-gray-900",children:"Skip Approver"})]})}),e.jsxs("div",{className:"space-y-4 px-6 py-4 overflow-y-auto flex-1",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ze,{className:"w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-orange-900 mb-1",children:"Important Notice"}),e.jsx("p",{className:"text-sm text-orange-800",children:"You are about to skip the current approver. The request will be moved to the next approval level."})]})]})}),(i||l)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ae,{className:"text-sm font-semibold text-gray-700",children:"Request Details"}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3 space-y-1",children:[i&&e.jsxs("p",{className:"text-sm text-gray-900",children:[e.jsx("span",{className:"font-medium",children:"Request ID:"})," ",i]}),l&&e.jsxs("p",{className:"text-sm text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Title:"})," ",l]})]})]}),(r||n)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ae,{className:"text-sm font-semibold text-gray-700",children:"Approver Being Skipped"}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-1",children:[n&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Level:"})," ",n]}),r&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Approver:"})," ",r]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ae,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(Os,{id:"skip-reason",placeholder:"Please provide a detailed reason for skipping this approver (e.g., 'Approver is on leave until [date]', 'Approver unavailable - escalating to next level')",value:o,onChange:u=>d(u.target.value),className:"min-h-[100px] border-2 border-gray-300 focus:border-orange-500",disabled:c,autoFocus:!0}),e.jsx("p",{className:"text-xs text-gray-500",children:"This reason will be recorded in the activity log and all participants will be notified."})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:x,className:"flex-1 h-11 border-gray-300",disabled:c,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:p,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:c||!o.trim(),children:[e.jsx(Ze,{className:"w-4 h-4 mr-2"}),c?"Skipping...":"Skip Approver"]})]})]})})}function n5({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:l,documentError:o,request:d,skipApproverData:c,actionStatus:m,existingParticipants:p,currentLevels:x,maxApprovalLevels:u,onPolicyViolation:g,setShowApproveModal:b,setShowRejectModal:f,setShowAddApproverModal:j,setShowAddSpectatorModal:y,setShowSkipApproverModal:v,setShowActionStatusModal:w,setPreviewDocument:S,setDocumentError:C,setSkipApproverData:I,setActionStatus:D,handleApproveConfirm:T,handleRejectConfirm:N,handleAddApprover:_,handleAddSpectator:A,handleSkipApprover:z,downloadDocument:F,documentPolicy:O}){return e.jsxs(e.Fragment,{children:[e.jsx(s5,{open:t,onClose:()=>b(!1),onConfirm:T,requestIdDisplay:d.id,requestTitle:d.title}),e.jsx(a5,{open:s,onClose:()=>f(!1),onConfirm:N,requestIdDisplay:d.id,requestTitle:d.title}),e.jsx(c0,{open:a,onClose:()=>j(!1),onConfirm:_,requestIdDisplay:d.id,requestTitle:d.title,existingParticipants:p,currentLevels:x,maxApprovalLevels:u,onPolicyViolation:g}),e.jsx(o0,{open:r,onClose:()=>y(!1),onConfirm:A,requestIdDisplay:d.id,requestTitle:d.title,existingParticipants:p}),e.jsx(r5,{open:n,onClose:()=>{v(!1),I(null)},onConfirm:z,approverName:c==null?void 0:c.approverName,levelNumber:c==null?void 0:c.levelNumber,requestIdDisplay:d.id,requestTitle:d.title}),l&&e.jsx(Or,{fileName:l.fileName,fileType:l.fileType,fileUrl:hn(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:F,open:!!l,onClose:()=>S(null)}),m&&e.jsx(l0,{open:i,onClose:()=>{w(!1),D(null)},success:m.success,title:m.title,message:m.message}),e.jsx(pt,{open:o.show,onOpenChange:P=>C(k=>({...k,show:P})),children:e.jsxs(ut,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(xt,{className:"flex items-center gap-2",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:o.errors.map((P,k)=>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:P.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:P.reason})]},k))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",O.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",O.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(It,{children:e.jsx(E,{onClick:()=>C({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const g0={DocumentsTab:ET,ActivityTab:OT,WorkNotesTab:zT,SummaryTab:HT,RequestDetailHeader:GT,QuickActionsSidebar:t5,RequestDetailModals:n5};function qc({className:t,...s}){return e.jsx(zf,{"data-slot":"checkbox",className:Me("peer border bg-input-background dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(Hf,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(Wa,{className:"size-3.5"})})})}function f0({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,l]=h.useState(""),[o,d]=h.useState([]),[c,m]=h.useState(new Set),[p,x]=h.useState(!1),[u,g]=h.useState(!1);h.useEffect(()=>{if(!t){d([]);return}if(!i||!i.startsWith("@")||i.length<2){d([]),x(!1);return}const y=setTimeout(async()=>{var v;try{x(!0);const w=i.slice(1),S=await ya(w,10),C=((v=S==null?void 0:S.data)==null?void 0:v.data)||(S==null?void 0:S.data)||[];d(Array.isArray(C)?C:[])}catch(w){console.error("Failed to search users:",w),G.error("Failed to search users")}finally{x(!1)}},300);return()=>clearTimeout(y)},[i,t]);const b=y=>{m(v=>{const w=new Set(v);return w.has(y)?w.delete(y):w.add(y),w})},f=async()=>{var y,v;if(c.size===0){G.error("Please select at least one user to share with");return}try{g(!0),await YT(a,Array.from(c)),G.success(`Summary shared with ${c.size} user(s)`),m(new Set),l(""),d([]),n==null||n(),s()}catch(w){console.error("Failed to share summary:",w),G.error(((v=(y=w==null?void 0:w.response)==null?void 0:y.data)==null?void 0:v.message)||"Failed to share summary")}finally{g(!1)}},j=()=>{m(new Set),l(""),d([]),s()};return e.jsx(pt,{open:t,onOpenChange:j,children:e.jsxs(ut,{className:"sm:max-w-[500px]",children:[e.jsx(gt,{children:e.jsx(xt,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(ae,{className:"text-sm font-medium text-gray-700",children:"Request"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:r})]}),e.jsxs("div",{children:[e.jsx(ae,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(ys,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(ke,{id:"user-search",placeholder:"Type @ to search users...",value:i,onChange:y=>l(y.target.value),className:"pl-10"})]}),i&&!i.startsWith("@")&&e.jsx("p",{className:"text-xs text-gray-500 mt-1 ml-1",children:"Start with @ to search users (e.g., @john)"})]}),p&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ke,{className:"h-5 w-5 animate-spin text-blue-600"})}),!p&&o.length>0&&e.jsx("div",{className:"border rounded-lg max-h-[300px] overflow-y-auto",children:o.map(y=>{const v=c.has(y.userId);return e.jsxs("div",{className:"flex items-center gap-3 p-3 hover:bg-gray-50 border-b last:border-b-0 cursor-pointer",onClick:()=>b(y.userId),children:[e.jsx("div",{onClick:w=>w.stopPropagation(),onMouseDown:w=>w.stopPropagation(),className:"flex items-center",children:e.jsx(qc,{checked:v,onCheckedChange:()=>b(y.userId)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zt,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:y.displayName||y.email})]}),(y.designation||y.department)&&e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:y.designation||y.department}),e.jsx("p",{className:"text-xs text-gray-400 truncate",children:y.email})]})]},y.userId)})}),!p&&i&&i.startsWith("@")&&o.length===0&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No users found"}),!p&&i&&!i.startsWith("@")&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"Start typing with @ to search users"}),c.size>0&&e.jsxs("div",{className:"border rounded-lg p-3 bg-blue-50",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-700 mb-2",children:["Selected (",c.size,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(c).map(y=>{const v=o.find(w=>w.userId===y);return e.jsxs("div",{className:"flex items-center gap-1 bg-white px-2 py-1 rounded-full text-xs",children:[e.jsx("span",{children:(v==null?void 0:v.displayName)||(v==null?void 0:v.email)||y}),e.jsx("button",{onClick:()=>b(y),className:"ml-1 hover:text-red-600",children:e.jsx(jt,{className:"h-3 w-3"})})]},y)})})]})]}),e.jsxs(It,{children:[e.jsx(E,{variant:"outline",onClick:j,disabled:u,children:"Cancel"}),e.jsx(E,{onClick:f,disabled:u||c.size===0,children:u?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${c.size} user(s)`})]})]})})}function b0({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,l]=h.useState(""),[o,d]=h.useState(""),[c,m]=h.useState(!1),p=()=>as().add(1,"month").format("YYYY-MM-DD"),x=()=>as().add(1,"month").format("YYYY-MM-DD"),u=()=>as().add(1,"day").format("YYYY-MM-DD");h.useEffect(()=>{t&&!o&&d(p())},[t]);const g=async()=>{var v,w,S,C;if(!i.trim()){G.error("Please provide a reason for pausing");return}if(!o){G.error("Please select a resume date");return}const f=as(o),j=as().add(1,"month"),y=as().add(1,"day");if(f.isAfter(j)){G.error("Resume date cannot be more than 1 month from now");return}if(f.isBefore(y,"day")){G.error("Resume date must be at least 1 day from now");return}try{m(!0),await Ew(a,r,i.trim(),f.toDate()),G.success("Workflow paused successfully"),n&&await n(),l(""),d(p()),s()}catch(I){console.error("Failed to pause workflow:",I),G.error(((w=(v=I==null?void 0:I.response)==null?void 0:v.data)==null?void 0:w.error)||((C=(S=I==null?void 0:I.response)==null?void 0:S.data)==null?void 0:C.message)||"Failed to pause workflow")}finally{m(!1)}},b=()=>{c||(l(""),d(p()),s())};return e.jsx(pt,{open:t,onOpenChange:b,children:e.jsxs(ut,{className:"sm:max-w-[500px]",children:[e.jsx(gt,{children:e.jsxs(xt,{className:"flex items-center gap-2",children:[e.jsx(lr,{className:"w-5 h-5 text-orange-600"}),"Pause Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-orange-800",children:[e.jsx("strong",{children:"Note:"})," Pausing will temporarily halt TAT calculations and notifications. The workflow will automatically resume on the selected date."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ae,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Os,{id:"pause-reason",value:i,onChange:f=>l(f.target.value),placeholder:"Enter the reason for pausing this workflow...",className:"min-h-[100px] text-sm",disabled:c}),e.jsxs("p",{className:"text-xs text-gray-500",children:[i.length," / 1000 characters"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ae,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ke,{id:"resume-date",type:"date",value:o,onChange:f=>d(f.target.value),min:u(),max:x(),className:"text-sm",disabled:c}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum 1 month from today. The workflow will automatically resume on this date."})]})]}),e.jsxs(It,{children:[e.jsx(E,{variant:"outline",onClick:b,disabled:c,children:"Cancel"}),e.jsx(E,{onClick:g,disabled:c||!i.trim()||!o,className:"bg-orange-600 hover:bg-orange-700 text-white",children:c?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function j0({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=h.useState(""),[l,o]=h.useState(!1),d=async()=>{var m,p,x,u;try{o(!0),await _w(a,n.trim()||void 0),G.success("Workflow resumed successfully"),r&&await r(),i(""),s()}catch(g){console.error("Failed to resume workflow:",g),G.error(((p=(m=g==null?void 0:g.response)==null?void 0:m.data)==null?void 0:p.error)||((u=(x=g==null?void 0:g.response)==null?void 0:x.data)==null?void 0:u.message)||"Failed to resume workflow")}finally{o(!1)}},c=()=>{l||(i(""),s())};return e.jsx(pt,{open:t,onOpenChange:c,children:e.jsxs(ut,{className:"sm:max-w-[500px]",children:[e.jsx(gt,{children:e.jsxs(xt,{className:"flex items-center gap-2",children:[e.jsx(Ii,{className:"w-5 h-5 text-green-600"}),"Resume Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-green-50 border border-green-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-green-800",children:[e.jsx("strong",{children:"Note:"})," Resuming will restart TAT calculations and notifications. The workflow will continue from where it was paused."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ae,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(Os,{id:"resume-notes",value:n,onChange:m=>i(m.target.value),placeholder:"Add any notes about why you're resuming this workflow...",className:"min-h-[100px] text-sm",disabled:l}),e.jsxs("p",{className:"text-xs text-gray-500",children:[n.length," / 1000 characters"]})]})]}),e.jsxs(It,{children:[e.jsx(E,{variant:"outline",onClick:c,disabled:l,children:"Cancel"}),e.jsx(E,{onClick:d,disabled:l,className:"bg-green-600 hover:bg-green-700 text-white",children:l?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ii,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function y0({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,l]=h.useState(!1),o=async()=>{var d,c,m,p;try{l(!0),await Mw(a),G.success("Retrigger request sent to approver"),n&&await n(),s()}catch(x){console.error("Failed to retrigger pause:",x),G.error(((c=(d=x==null?void 0:x.response)==null?void 0:d.data)==null?void 0:c.error)||((p=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:p.message)||"Failed to send retrigger request")}finally{l(!1)}};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(ut,{className:"sm:max-w-[450px]",children:[e.jsx(gt,{children:e.jsxs(xt,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-orange-600"}),"Request Resume"]})}),e.jsxs("div",{className:"py-4",children:[e.jsxs("p",{className:"text-sm text-gray-700 mb-4",children:["You are requesting the approver",r?` (${r})`:""," to cancel the pause and resume work on this request."]}),e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-orange-800",children:"A notification will be sent to the approver who paused this workflow, requesting them to resume it."})})]}),e.jsxs(It,{children:[e.jsx(E,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(E,{onClick:o,disabled:i,className:"bg-orange-600 hover:bg-orange-700 text-white",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:i5,ActivityTab:l5,WorkNotesTab:o5,SummaryTab:c5,RequestDetailHeader:d5,QuickActionsSidebar:m5,RequestDetailModals:u5}=g0;let x5=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("Custom RequestDetail Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(ts,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(E,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(E,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function h5({requestId:t,onBack:s,dynamicRequests:a=[]}){var Br,Qa,hr,Xa,pr,gr,Ja,Da,Za;const n=Oa().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,d]=h.useState(l),[c,m]=h.useState(!1),[p,x]=h.useState(null),[u,g]=h.useState(null),[b,f]=h.useState(!1),[j,y]=h.useState(0),[v,w]=h.useState(!1),[S,C]=h.useState(!1),[I,D]=h.useState(!1),[T,N]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[_,A]=h.useState({open:!1,violations:[]}),{user:z}=ds(),{request:F,apiRequest:O,loading:P,refreshing:k,refreshDetails:R,currentApprovalLevel:V,isSpectator:M,isInitiator:L,existingParticipants:U,accessDenied:H}=Xc(n,a,z),{mergedMessages:X,unreadWorkNotes:J,workNoteAttachments:$,setWorkNoteAttachments:B}=a0(n,O,o,z),{uploadingDocument:K,triggerFileInput:se,previewDocument:Y,setPreviewDocument:ee,documentPolicy:me,documentError:Se,setDocumentError:Je}=r0(O,R),{showApproveModal:Ve,setShowApproveModal:Ee,showRejectModal:Oe,setShowRejectModal:ie,showAddApproverModal:ge,setShowAddApproverModal:we,showAddSpectatorModal:Te,setShowAddSpectatorModal:de,showSkipApproverModal:q,setShowSkipApproverModal:ue,showActionStatusModal:Pe,setShowActionStatusModal:ve,skipApproverData:Ne,setSkipApproverData:Ue,actionStatus:nt,setActionStatus:ot,handleApproveConfirm:Tt,handleRejectConfirm:Mt,handleAddApprover:ne,handleSkipApprover:Ie,handleAddSpectator:le}=i0(n,V,R),{conclusionRemark:Xe,setConclusionRemark:ze,conclusionLoading:tt,conclusionSubmitting:Qe,aiGenerated:rt,handleGenerateConclusion:qe,handleFinalizeConclusion:ct,generationAttempts:$s,generationFailed:ns,maxAttemptsReached:yt}=n0(F,n,L,R,s,ot,ve);h.useEffect(()=>{(async()=>{var As;try{const aa=await ma("SYSTEM_SETTINGS"),fr=await ma("WORKFLOW_SHARING"),br=[...aa,...fr],wa={};br.forEach(qa=>{wa[qa.configKey]=qa.configValue}),N({maxApprovalLevels:parseInt(wa.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(wa.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((As=wa.ALLOW_ADD_SPECTATOR)==null?void 0:As.toLowerCase())==="true",maxSpectators:parseInt(wa.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(aa){console.error("Failed to load system policy:",aa)}})()},[]),h.useEffect(()=>{const As=new URLSearchParams(window.location.search).get("tab");As&&d(As)},[n]);const mt=()=>{R()},Ft=()=>{w(!0)},Ss=()=>{C(!0)},ss=async()=>{await R()},$a=()=>{D(!0)},Ua=async()=>{await R()},ur=async()=>{await R()},va=async()=>{if(!(O!=null&&O.requestId)){G.error("Request ID not found");return}if(!p){G.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},Lt=((F==null?void 0:F.status)==="approved"||(F==null?void 0:F.status)==="rejected")&&L,Na=(F==null?void 0:F.status)==="closed"||(F==null?void 0:F.status)==="approved"&&!L||(F==null?void 0:F.status)==="rejected"&&!L,Ms=((F==null?void 0:F.templateType)||(F==null?void 0:F.template_type)||"").toString().toUpperCase()==="FORM_16";h.useEffect(()=>{Ms&&o==="worknotes"&&d("overview")},[Ms,o]),h.useEffect(()=>{(async()=>{if(!Na||!(O!=null&&O.requestId)){g(null),x(null);return}try{f(!0);const As=await u0(O.requestId);if(As!=null&&As.summaryId){x(As.summaryId);try{const aa=await Zc(As.summaryId);g(aa)}catch(aa){console.error("Failed to fetch summary details:",aa),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{f(!1)}})()},[Na,O==null?void 0:O.requestId]);const $r=((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}));if(P&&!F&&!O)return e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Et,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading custom request details..."})]})});if(H!=null&&H.denied)return 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(fh,{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:H.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(ws,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})});if(!F)return 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(De,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Custom Request Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The custom request you're looking for doesn't exist or may have been deleted."}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(ws,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})});const Ur=(z==null?void 0:z.role)==="MANAGEMENT"||(z==null?void 0:z.role)==="ADMIN",xr=((Br=at.getUserData())==null?void 0:Br.jobTitle)==="Dealer";return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"custom-request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[Ms&&e.jsx("p",{className:"text-sm text-emerald-700 font-medium mb-2","data-testid":"form16-details-heading",children:"Form 16 Details"}),e.jsx(d5,{request:F,refreshing:k,onBack:s||(()=>window.history.back()),onRefresh:mt,onShareSummary:va,isInitiator:L,slaData:((Qa=F==null?void 0:F.summary)==null?void 0:Qa.sla)||(F==null?void 0:F.sla)||null,isPaused:((hr=F==null?void 0:F.pauseInfo)==null?void 0:hr.isPaused)||!1}),e.jsxs(ii,{value:o,onValueChange:d,className:"w-full","data-testid":"custom-request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(li,{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($t,{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(bh,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:Ms?"Form 16":"Overview"})]}),Na&&u&&e.jsxs($t,{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(Jo,{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($t,{value:"workflow",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-workflow",children:[e.jsx(zs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),e.jsxs($t,{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(De,{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($t,{value:"activity",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 col-span-1 sm:col-span-1","data-testid":"tab-activity",children:[e.jsx(Bt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Activity"})]}),!Ms&&e.jsxs($t,{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(Vs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),J>0&&e.jsx(re,{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:J>9?"9+":J})]})]})}),e.jsxs("div",{className:o==="worknotes"&&!Ms?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:o==="worknotes"&&!Ms?"":"lg:col-span-2",children:[e.jsx(Ut,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:Ms?e.jsx(qw,{request:F}):e.jsx(Gw,{request:F,isInitiator:L,needsClosure:Lt,conclusionRemark:Xe,setConclusionRemark:ze,conclusionLoading:tt,conclusionSubmitting:Qe,aiGenerated:rt,handleGenerateConclusion:qe,handleFinalizeConclusion:ct,onPause:Ft,onResume:Ss,onRetrigger:$a,currentUserIsApprover:!!V,pausedByUserId:(pr=(Xa=F==null?void 0:F.pauseInfo)==null?void 0:Xa.pausedBy)==null?void 0:pr.userId,currentUserId:z==null?void 0:z.userId,generationAttempts:$s,generationFailed:ns,maxAttemptsReached:yt})}),Na&&e.jsx(Ut,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(c5,{summary:u,loading:b,onShare:va,isInitiator:L})}),e.jsx(Ut,{value:"workflow",className:"mt-0",children:Ms?e.jsx(t1,{request:F,requestId:(O==null?void 0:O.requestId)||n,isReUser:Ur,onRefresh:R}):e.jsx(Xw,{request:F,user:z,isInitiator:L,onSkipApprover:Yt=>{if(!Yt.levelId){alert("Level ID not available");return}Ue(Yt),ue(!0)},onRefresh:R})}),e.jsx(Ut,{value:"documents",className:"mt-0",children:e.jsx(i5,{request:F,workNoteAttachments:$,uploadingDocument:K,documentPolicy:me,triggerFileInput:se,setPreviewDocument:ee,downloadDocument:_s,isSpectator:M})}),e.jsx(Ut,{value:"activity",className:"mt-0",children:e.jsx(l5,{request:F})}),!Ms&&e.jsx(Ut,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(o5,{requestId:n,requestTitle:F.title,mergedMessages:X,setWorkNoteAttachments:B,isInitiator:L,isSpectator:M,currentLevels:$r,onAddApprover:ne,maxApprovalLevels:T.maxApprovalLevels,onPolicyViolation:Yt=>A({open:!0,violations:Yt})})})]}),!xr&&o!=="worknotes"&&e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[Ms&&Ur&&e.jsx(PT,{requestId:(O==null?void 0:O.requestId)||n,request:F,onRefresh:R}),e.jsx(m5,{request:F,isInitiator:L,isSpectator:M,currentApprovalLevel:V,onAddApprover:()=>we(!0),onAddSpectator:()=>de(!0),onApprove:()=>Ee(!0),onReject:()=>ie(!0),onPause:Ft,onResume:Ss,onRetrigger:$a,summaryId:p,refreshTrigger:j,pausedByUserId:(Ja=(gr=F==null?void 0:F.pauseInfo)==null?void 0:gr.pausedBy)==null?void 0:Ja.userId,currentUserId:z==null?void 0:z.userId,apiRequest:O,hideApproveReject:xr})]})]})]})]})}),c&&p&&e.jsx(f0,{isOpen:c,onClose:()=>m(!1),summaryId:p,requestTitle:(F==null?void 0:F.title)||"N/A",onSuccess:()=>{R(),y(Yt=>Yt+1)}}),v&&(O==null?void 0:O.requestId)&&e.jsx(b0,{isOpen:v,onClose:()=>w(!1),requestId:O.requestId,levelId:(V==null?void 0:V.levelId)||null,onSuccess:Ua}),S&&(O==null?void 0:O.requestId)&&e.jsx(j0,{isOpen:S,onClose:()=>C(!1),requestId:O.requestId,onSuccess:ss}),I&&(O==null?void 0:O.requestId)&&e.jsx(y0,{isOpen:I,onClose:()=>D(!1),requestId:O.requestId,approverName:(Za=(Da=F==null?void 0:F.pauseInfo)==null?void 0:Da.pausedBy)==null?void 0:Za.name,onSuccess:ur}),e.jsx(u5,{showApproveModal:Ve,showRejectModal:Oe,showAddApproverModal:ge,showAddSpectatorModal:Te,showSkipApproverModal:q,showActionStatusModal:Pe,previewDocument:Y,documentError:Se,request:F,skipApproverData:Ne,actionStatus:nt,existingParticipants:U,currentLevels:$r,maxApprovalLevels:T.maxApprovalLevels,onPolicyViolation:Yt=>A({open:!0,violations:Yt}),setShowApproveModal:Ee,setShowRejectModal:ie,setShowAddApproverModal:we,setShowAddSpectatorModal:de,setShowSkipApproverModal:ue,setShowActionStatusModal:ve,setPreviewDocument:ee,setDocumentError:Je,setSkipApproverData:Ue,setActionStatus:ot,handleApproveConfirm:Tt,handleRejectConfirm:Mt,handleAddApprover:ne,handleAddSpectator:le,handleSkipApprover:Ie,downloadDocument:_s,documentPolicy:me}),e.jsx(ni,{open:_.open,onClose:()=>A({open:!1,violations:[]}),violations:_.violations,policyDetails:{maxApprovalLevels:T.maxApprovalLevels,maxParticipants:T.maxParticipants,allowSpectators:T.allowSpectators,maxSpectators:T.maxSpectators}})]})}function p5(t){return e.jsx(x5,{children:e.jsx(h5,{...t})})}const g5=[{value:"Q1",label:"Q1 (April - June)"},{value:"Q2",label:"Q2 (July - September)"},{value:"Q3",label:"Q3 (October - December)"},{value:"Q4",label:"Q4 (January - March)"}];function f5(){const t=new Date().getFullYear(),s=[];for(let a=0;a<4;a++){const r=t-a,n=(r+1).toString().slice(-2);s.push(`${r}-${n}`)}return s}function b5({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,form16FinancialYear:n="",form16Quarter:i="",sortBy:l,sortOrder:o,onSearchChange:d,onStatusFilterChange:c,onPriorityFilterChange:m,onTemplateTypeFilterChange:p,onForm16FinancialYearChange:x,onForm16QuarterChange:u,onSortByChange:g,onSortOrderChange:b,onClearFilters:f,activeFiltersCount:j}){const y=f5(),v=r==="FORM_16";return e.jsxs(Z,{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(Ma,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ye,{className:"text-xs sm:text-sm",children:j>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[j," filter",j>1?"s":""," active"]})})]})]}),j>0&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:f,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(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(te,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ys,{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(ke,{placeholder:"Search requests, IDs...",value:t,onChange:w=>d(w.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(He,{value:a,onValueChange:m,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:"All Priorities"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Priorities"}),e.jsx(Q,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ra,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(Q,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(He,{value:s,onValueChange:c,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:"All Statuses"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Statuses"}),e.jsx(Q,{value:"pending",children:"Pending (In Approval)"}),e.jsx(Q,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs(He,{value:r,onValueChange: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",children:e.jsx(We,{placeholder:"Request type"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Templates"}),e.jsx(Q,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Q,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(Q,{value:"FORM_16",children:"Form 16"})]})]}),v&&x&&e.jsxs(He,{value:n||void 0,onValueChange:x,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:"Financial Year"})}),e.jsx(Ye,{children:y.map(w=>e.jsx(Q,{value:w,children:w},w))})]}),v&&u&&e.jsxs(He,{value:i||void 0,onValueChange:u,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:"Quarter"})}),e.jsx(Ye,{children:g5.map(w=>e.jsx(Q,{value:w.value,children:w.label},w.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:l,onValueChange:w=>g(w),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(Q,{value:"due",children:"Due Date"}),e.jsx(Q,{value:"created",children:"Date Created"}),e.jsx(Q,{value:"priority",children:"Priority"}),e.jsx(Q,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>b(o==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:o==="asc"?e.jsx(sl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(al,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}const j5=[{value:"Q1",label:"Q1 (April - June)"},{value:"Q2",label:"Q2 (July - September)"},{value:"Q3",label:"Q3 (October - December)"},{value:"Q4",label:"Q4 (January - March)"}];function y5(){const t=new Date().getFullYear(),s=[];for(let a=0;a<4;a++){const r=t-a,n=(r+1).toString().slice(-2);s.push(`${r}-${n}`)}return s}function v5({searchTerm:t,priorityFilter:s,statusFilter:a,templateTypeFilter:r,form16FinancialYear:n="",form16Quarter:i="",sortBy:l,sortOrder:o,activeFiltersCount:d,onSearchChange:c,onPriorityChange:m,onStatusChange:p,onTemplateTypeChange:x,onForm16FinancialYearChange:u,onForm16QuarterChange:g,onSortByChange:b,onSortOrderChange:f,onClearFilters:j}){const y=y5(),v=r==="FORM_16";return e.jsxs(Z,{className:"shadow-lg border-0","data-testid":"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(Ma,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(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(E,{variant:"ghost",size:"sm",onClick:j,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3","data-testid":"closed-requests-clear-filters",children:[e.jsx(jt,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(te,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ys,{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(ke,{placeholder:"Search requests, IDs...",value:t,onChange:w=>c(w.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white transition-colors","data-testid":"closed-requests-search"})]}),e.jsxs(He,{value:s,onValueChange:m,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","data-testid":"closed-requests-priority-filter",children:e.jsx(We,{placeholder:"All Priorities"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Priorities"}),e.jsx(Q,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ra,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(Q,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(He,{value:a,onValueChange: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","data-testid":"closed-requests-status-filter",children:e.jsx(We,{placeholder:"Closure Type"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Closures"}),e.jsx(Q,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($e,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(Q,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs(He,{value:r,onValueChange:x,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","data-testid":"closed-requests-template-type-filter",children:e.jsx(We,{placeholder:"Request type"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Templates"}),e.jsx(Q,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Q,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(Q,{value:"FORM_16",children:"Form 16"})]})]}),v&&u&&e.jsxs(He,{value:n||void 0,onValueChange:u,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",children:e.jsx(We,{placeholder:"Financial Year"})}),e.jsx(Ye,{children:y.map(w=>e.jsx(Q,{value:w,children:w},w))})]}),v&&g&&e.jsxs(He,{value:i||void 0,onValueChange:g,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",children:e.jsx(We,{placeholder:"Quarter"})}),e.jsx(Ye,{children:j5.map(w=>e.jsx(Q,{value:w.value,children:w.label},w.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:l,onValueChange:w=>b(w),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","data-testid":"closed-requests-sort-by",children:e.jsx(We,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"due",children:"Due Date"}),e.jsx(Q,{value:"created",children:"Date Created"}),e.jsx(Q,{value:"priority",children:"Priority"})]})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:f,className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11","data-testid":"closed-requests-sort-order",children:o==="asc"?e.jsx(sl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(al,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function N5({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,departmentFilter:n,slaComplianceFilter:i,initiatorFilter:l,approverFilter:o,approverFilterType:d,dateRange:c,customStartDate:m,customEndDate:p,showCustomDatePicker:x,departments:u,loadingDepartments:g,initiatorSearch:b,approverSearch:f,showForm16Filter:j=!1,form16FinancialYear:y="all",form16Quarter:v="all",onForm16FinancialYearChange:w,onForm16QuarterChange:S,onSearchChange:C,onStatusChange:I,onPriorityChange:D,onTemplateTypeChange:T,onDepartmentChange:N,onSlaComplianceChange:_,onInitiatorChange:A,onApproverChange:z,onApproverTypeChange:F,onDateRangeChange:O,onCustomStartDateChange:P,onCustomEndDateChange:k,onShowCustomDatePickerChange:R,onApplyCustomDate:V,onClearFilters:M,hasActiveFilters:L}){return e.jsx(Z,{className:"border-gray-200 shadow-md","data-testid":"user-all-requests-filters",children:e.jsx(te,{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(Ma,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),L&&e.jsx(re,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),L&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:M,className:"gap-2",children:[e.jsx(Et,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Jt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(ys,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(ke,{placeholder:"Search requests...",value:t,onChange:U=>C(U.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(He,{value:s,onValueChange:I,children:[e.jsx(Ge,{className:"h-10","data-testid":"status-filter",children:e.jsx(We,{placeholder:"All Status"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Status"}),e.jsx(Q,{value:"pending",children:"Pending"}),e.jsx(Q,{value:"paused",children:"Paused"}),e.jsx(Q,{value:"approved",children:"Approved"}),e.jsx(Q,{value:"rejected",children:"Rejected"}),e.jsx(Q,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:a,onValueChange:D,children:[e.jsx(Ge,{className:"h-10","data-testid":"priority-filter",children:e.jsx(We,{placeholder:"All Priority"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Priority"}),e.jsx(Q,{value:"express",children:"Express"}),e.jsx(Q,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:r,onValueChange:T,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(Q,{value:"all",children:"All Templates"}),e.jsx(Q,{value:"CUSTOM",children:"Custom"}),e.jsx(Q,{value:"DEALER CLAIM",children:"Dealer Claim"}),j&&e.jsx(Q,{value:"FORM_16",children:"Form 16"})]})]}),j&&r==="FORM_16"&&e.jsxs(e.Fragment,{children:[e.jsxs(He,{value:y,onValueChange:w??(()=>{}),children:[e.jsx(Ge,{className:"h-10","data-testid":"form16-financial-year-filter",children:e.jsx(We,{placeholder:"Financial Year"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Years"}),e.jsx(Q,{value:"2024-25",children:"2024-25"}),e.jsx(Q,{value:"2023-24",children:"2023-24"}),e.jsx(Q,{value:"2022-23",children:"2022-23"})]})]}),e.jsxs(He,{value:v,onValueChange:S??(()=>{}),children:[e.jsx(Ge,{className:"h-10","data-testid":"form16-quarter-filter",children:e.jsx(We,{placeholder:"Quarter"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Quarters"}),e.jsx(Q,{value:"Q1",children:"Q1"}),e.jsx(Q,{value:"Q2",children:"Q2"}),e.jsx(Q,{value:"Q3",children:"Q3"}),e.jsx(Q,{value:"Q4",children:"Q4"})]})]})]}),e.jsxs(He,{value:n,onValueChange:N,disabled:g||u.length===0,children:[e.jsx(Ge,{className:"h-10","data-testid":"department-filter",children:e.jsx(We,{placeholder:g?"Loading...":"All Departments"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Departments"}),u.map(U=>e.jsx(Q,{value:U,children:U},U))]})]}),e.jsxs(He,{value:i,onValueChange:_,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(Q,{value:"all",children:"All SLA Status"}),e.jsx(Q,{value:"compliant",children:"Compliant"}),e.jsx(Q,{value:"on-track",children:"On Track"}),e.jsx(Q,{value:"approaching",children:"Approaching"}),e.jsx(Q,{value:"critical",children:"Critical"}),e.jsx(Q,{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(ae,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:b.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:b.selectedUser.displayName||b.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:b.handleClear,children:e.jsx(jt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{placeholder:"Search initiator...",value:b.searchQuery,onChange:U=>b.handleSearch(U.target.value),onFocus:()=>{b.searchResults.length>0&&b.setShowResults(!0)},onBlur:()=>setTimeout(()=>b.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),b.showResults&&b.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:b.searchResults.map(U=>e.jsx("button",{type:"button",onClick:()=>b.handleSelect(U),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:U.displayName||U.email}),U.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:U.email})]})},U.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ae,{className:"text-sm font-medium text-gray-700",children:"Approver"}),o!=="all"&&F&&e.jsxs(He,{value:d,onValueChange:U=>F(U),children:[e.jsx(Ge,{className:"h-7 w-32 text-xs",children:e.jsx(We,{})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"current",children:"Current Only"}),e.jsx(Q,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:f.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:f.selectedUser.displayName||f.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:f.handleClear,children:e.jsx(jt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{placeholder:"Search approver...",value:f.searchQuery,onChange:U=>f.handleSearch(U.target.value),onFocus:()=>{f.searchResults.length>0&&f.setShowResults(!0)},onBlur:()=>setTimeout(()=>f.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),f.showResults&&f.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:f.searchResults.map(U=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(U),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:U.displayName||U.email}),U.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:U.email})]})},U.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(ht,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:c,onValueChange:U=>O(U),children:[e.jsx(Ge,{className:"w-[160px] h-10",children:e.jsx(We,{placeholder:"Date Range"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Time"}),e.jsx(Q,{value:"today",children:"Today"}),e.jsx(Q,{value:"week",children:"This Week"}),e.jsx(Q,{value:"month",children:"This Month"}),e.jsx(Q,{value:"last7days",children:"Last 7 Days"}),e.jsx(Q,{value:"last30days",children:"Last 30 Days"}),e.jsx(Q,{value:"custom",children:"Custom Range"})]})]}),c==="custom"&&e.jsxs(oa,{open:x,onOpenChange:R,children:[e.jsx(ca,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ht,{className:"w-4 h-4"}),m&&p?`${et(m,"MMM d, yyyy")} - ${et(p,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(da,{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(ae,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Xs,{value:m||null,onChange:U=>{const H=U?new Date(U):void 0;H?(P==null||P(H),p&&H>p&&(k==null||k(H))):P==null||P(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ae,{htmlFor:"end-date",children:"End Date"}),e.jsx(Xs,{value:p||null,onChange:U=>{const H=U?new Date(U):void 0;H?(k==null||k(H),m&&H{R==null||R(!1),P==null||P(void 0),k==null||k(void 0),O("month")},children:"Cancel"})]})]})})]})]})]})})})}function w5({request:t,apiRequest:s,currentUserId:a,isInitiator:r,onEditClaimAmount:n,className:i="",needsClosure:l=!1,conclusionRemark:o="",setConclusionRemark:d,conclusionLoading:c=!1,conclusionSubmitting:m=!1,aiGenerated:p=!1,handleGenerateConclusion:x,handleFinalizeConclusion:u,generationAttempts:g=0,generationFailed:b=!1,maxAttemptsReached:f=!1}){var S,C,I,D,T,N,_,A,z;if(!Yn(s))return e.jsx("div",{className:"text-center py-8 text-gray-500",children:e.jsx("p",{children:"This is not a claim management request."})});const j=x0(s);if(!j)return console.warn("[ClaimManagementOverviewTab] Failed to map claim data:",{apiRequest:s,hasClaimDetails:!!(s!=null&&s.claimDetails),hasProposalDetails:!!(s!=null&&s.proposalDetails),hasCompletionDetails:!!(s!=null&&s.completionDetails)}),e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx("p",{children:"Unable to load claim management data."}),e.jsx("p",{className:"text-xs mt-2",children:"Please ensure the request has been properly initialized."})]});const y=h0(s,a),v=p0(y),w={name:((S=s.initiator)==null?void 0:S.name)||((C=s.initiator)==null?void 0:C.displayName)||((I=s.initiator)==null?void 0:I.email)||"Unknown",role:((D=s.initiator)==null?void 0:D.role)||((T=s.initiator)==null?void 0:T.designation)||"Initiator",department:((N=s.initiator)==null?void 0:N.department)||s.department||"",email:((_=s.initiator)==null?void 0:_.email)||"N/A",phone:((A=s.initiator)==null?void 0:A.phone)||((z=s.initiator)==null?void 0:z.mobile)};return e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx(XT,{activityInfo:j.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(JT,{dealerInfo:j.dealerInfo}),v.showProposalDetails&&j.proposalDetails&&e.jsx(qT,{proposalDetails:j.proposalDetails}),e.jsx(e5,{initiatorInfo:w}),(s==null?void 0:s.status)==="closed"&&(s==null?void 0:s.conclusionRemark)&&e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx($e,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(ye,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(te,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Is,{content:s.conclusionRemark||"",className:"text-sm"})}),s.closureDate&&e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs text-gray-500 border-t border-gray-200 pt-3",children:[e.jsxs("span",{children:["Request closed on ",gs(s.closureDate)]}),e.jsxs("span",{children:["By ",w.name]})]})]})]}),l&&e.jsxs(Z,{"data-testid":"conclusion-remark-card",children:[e.jsx(oe,{className:`bg-gradient-to-r border-b ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"from-red-50 to-rose-50 border-red-200":"from-green-50 to-emerald-50 border-green-200"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(ce,{className:`flex items-center gap-2 text-base sm:text-lg ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx($e,{className:`w-5 h-5 ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(ye,{className:"mt-1 text-xs sm:text-sm",children:((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"This request was rejected. Please review the AI-generated closure remark and finalize it to close this request.":"All approvals are complete. Please review and finalize the conclusion to close this request."})]}),x&&e.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:x,disabled:c||f,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx(Et,{className:`w-3.5 h-3.5 ${c?"animate-spin":""}`}),p?"Regenerate":"Generate with AI"]}),p&&!f&&!b&&e.jsxs("span",{className:"text-[10px] text-gray-500 font-medium px-1",children:[2-g," attempts remaining"]})]})]})}),e.jsx(te,{className:"pt-4",children:c?e.jsx("div",{className:"flex items-center justify-center py-8","data-testid":"conclusion-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ke,{className:"w-8 h-8 text-blue-600 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Preparing conclusion remark..."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Conclusion Remark"}),p&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),d&&e.jsx(ei,{value:o,onChange:F=>d(F),placeholder:"Enter a professional conclusion remark summarizing the request outcome, key decisions, and approvals...",className:"text-sm",minHeight:"160px","data-testid":"conclusion-remark-textarea"}),e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"This will be the final summary for this request"}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":"character-count",children:[o?o.replace(/<[^>]*>/g,"").length:0," / 2000 characters"]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-blue-900 mb-1.5",children:"Finalizing this request will:"}),e.jsxs("ul",{className:"text-xs sm:text-sm text-blue-800 space-y-0.5 pl-4",children:[e.jsx("li",{className:"list-disc",children:'Change request status to "CLOSED"'}),e.jsx("li",{className:"list-disc",children:"Notify all participants of closure"}),e.jsx("li",{className:"list-disc",children:"Move request to Closed Requests"}),e.jsx("li",{className:"list-disc",children:"Save conclusion remark permanently"})]})]}),u&&e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(E,{onClick:u,disabled:m||!o.trim(),className:"bg-green-600 hover:bg-green-700 text-white","data-testid":"finalize-close-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function C5({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n="Request",requestDescription:i="",requestId:l,levelName:o="Approval Level",approverName:d="Approver"}){const[c,m]=h.useState(""),[p,x]=h.useState(!1),[u,g]=h.useState(null),b=async()=>{if(!c.trim()){G.error("Please provide approval comments");return}try{x(!0),g("approve"),await a(c),j(),s()}catch(v){console.error("Failed to approve request:",v),G.error("Failed to approve request. Please try again.")}finally{x(!1),g(null)}},f=async()=>{if(!c.trim()){G.error("Please provide rejection reason");return}try{x(!0),g("reject"),await r(c),j(),s()}catch(v){console.error("Failed to reject request:",v),G.error("Failed to reject request. Please try again.")}finally{x(!1),g(null)}},j=()=>{m(""),g(null)},y=()=>{p||(j(),s())};return t?e.jsx(pt,{open:t,onOpenChange:y,children:e.jsxs(ut,{className:"dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl",children:[e.jsxs(gt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(xt,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx($e,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),"Review Request"]}),e.jsxs(_t,{className:"text-xs lg:text-sm",children:[o,": Review request details and make a decision"]}),e.jsx("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:"Request ID:"})," ",l||"N/A"]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Approver:"})," ",d]})]})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden py-3 lg:py-4 px-6",children:e.jsxs("div",{className:"space-y-4",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(De,{className:"w-4 h-4 text-blue-600"}),"Request Title"]})}),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-medium text-gray-900",children:n})})]}),i&&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(Vs,{className:"w-4 h-4 text-blue-600"}),"Request Description"]})}),e.jsx("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50 max-h-[200px] overflow-y-auto",children:e.jsx(Is,{content:i,className:"text-xs lg:text-sm text-gray-700"})})]}),e.jsxs("div",{className:"space-y-2 border-t pt-3 lg:pt-3",children:[e.jsx("h3",{className:"font-semibold text-sm lg:text-base",children:"Your Decision & Comments"}),e.jsx(Os,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:c,onChange:v=>m(v.target.value),className:"min-h-[80px] lg:min-h-[90px] text-xs lg:text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[c.length," characters"]})]}),!c.trim()&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-2 flex items-start gap-2",children:[e.jsx(Ct,{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(It,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end px-6 pb-6 pt-3 lg:pt-4 flex-shrink-0 border-t bg-gray-50",children:[e.jsx(E,{variant:"outline",onClick:y,disabled:p,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{onClick:f,disabled:!c.trim()||p,variant:"destructive",className:"bg-red-600 hover:bg-red-700",children:p&&u==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),"Reject"]})}),e.jsx(E,{onClick:b,disabled:!c.trim()||p,className:"bg-green-600 hover:bg-green-700 text-white",children:p&&u==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"w-4 h-4 mr-2"}),"Approve"]})})]})]})]})}):null}function S5({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:l,requestNumber:o,requestId:d,dueDate:c,taxationType:m}){const[p,x]=h.useState(!1),[u,g]=h.useState(!1),b=m==="Non GST"||m==="Non-GST",f=(n==null?void 0:n.creditNoteNumber)&&(n==null?void 0:n.creditNoteNumber)!=="",j=(n==null?void 0:n.creditNoteNumber)||"",y=n!=null&&n.creditNoteDate?gs(n.creditNoteDate,{includeTime:!1,format:"short"}):"",v=(n==null?void 0:n.creditNoteAmount)||0,w=(n==null?void 0:n.status)||"PENDING",S=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",C=(i==null?void 0:i.dealerCode)||"RE-JP-009",I=l||"Activity",D=o||"RE-REQ-2024-CM-101",T=c?gs(c,{includeTime:!1,format:"short"}):"Jan 4, 2026",N=async()=>{if(a)try{x(!0),await a(),G.success("Credit note downloaded successfully")}catch(z){console.error("Failed to download credit note:",z),G.error("Failed to download credit note. Please try again.")}finally{x(!1)}else G.info("Credit note will be automatically saved to Documents tab")},_=async()=>{if(r)try{g(!0),await r(),G.success("Credit note sent to dealer successfully"),s()}catch(z){console.error("Failed to send credit note to dealer:",z),G.error("Failed to send credit note. Please try again.")}finally{g(!1)}else G.info("Email notification will be sent to dealer with credit note attachment")},A=z=>`₹${z.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(ut,{className:"sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(gt,{children:[e.jsxs(xt,{className:"font-semibold flex items-center gap-2 text-2xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note from SAP"]}),m&&e.jsx(re,{className:`ml-2 border-none shadow-sm ${b?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:b?"Non-GST Claim":"GST Claim"})]}),e.jsx(_t,{className:"text-base",children:"Review and send credit note to dealer"})]}),e.jsxs("div",{className:"space-y-5 py-4",children:[f?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-200 rounded-lg p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-green-900 text-xl mb-1",children:"Royal Enfield"}),e.jsx("p",{className:"text-sm text-green-700",children:"Credit Note Document"})]}),e.jsxs(re,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx($e,{className:"w-4 h-4 mr-2"}),w==="APPROVED"?"Approved":w==="ISSUED"?"Issued":w==="SENT"?"Sent":"Pending"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100",children:[e.jsxs(ae,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Pb,{className:"w-3 h-3"}),"Credit Note Number"]}),e.jsx("p",{className:"font-bold text-gray-900 mt-1 text-lg",children:j})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100",children:[e.jsxs(ae,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(ht,{className:"w-3 h-3"}),"Issue Date"]}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:y})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-5",children:[e.jsxs(ae,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-3",children:[e.jsx(Ga,{className:"w-4 h-4"}),"Credit Note Amount"]}),e.jsx("p",{className:"text-4xl font-bold text-blue-700",children:A(v)})]})]}):e.jsx("div",{className:"bg-gray-50 border-2 border-gray-300 rounded-lg p-8 text-center",children:e.jsxs("div",{className:"flex flex-col items-center justify-center space-y-4",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-200 rounded-full flex items-center justify-center",children:e.jsx(Pt,{className:"w-8 h-8 text-gray-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-700 mb-2",children:"No Credit Note Available"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Credit note has not been generated yet. Please wait for the credit note to be generated from DMS."})]})]})}),e.jsxs("div",{className:"bg-purple-50 border-2 border-purple-200 rounded-lg p-5",children:[e.jsxs("h3",{className:"font-semibold text-purple-900 mb-4 flex items-center gap-2",children:[e.jsx(tl,{className:"w-5 h-5"}),"Dealer Information"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(ae,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:S})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(ae,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:C})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(ae,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Activity"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:I})]})]})]}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:[e.jsxs("h3",{className:"font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4"}),"Reference Details"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx(ae,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Request ID"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:D})]}),e.jsxs("div",{children:[e.jsx(ae,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Due Date"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:T})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(De,{className:"w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-blue-800",children:[e.jsx("p",{className:"font-semibold mb-2",children:"Available Actions"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-xs",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Download:"})," Credit note will be automatically saved to Documents tab"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Send to Dealer:"})," Email notification will be sent to dealer with credit note attachment"]}),e.jsx("li",{children:"All actions will be recorded in activity trail for audit purposes"})]})]})]})]}),e.jsxs(It,{className:"flex-col-reverse gap-2 sm:flex-row flex items-center justify-between sm:justify-between",children:[e.jsx(E,{variant:"outline",onClick:s,disabled:p||u,className:"border-2",children:"Close"}),e.jsx("div",{className:"flex gap-2",children:f&&e.jsxs(e.Fragment,{children:[e.jsxs(E,{variant:"outline",onClick:N,disabled:p||u,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),p?"Downloading...":"Download"]}),e.jsxs(E,{onClick:_,disabled:p||u,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(ph,{className:"w-4 h-4 mr-2"}),u?"Sending...":"Send to Dealer"]})]})})]})]})})}const Jr=(t,s)=>{if(!t)return{isValid:!0,message:""};const a=t.trim();if(!/^\d+$/.test(a))return{isValid:!1,message:"Code must contain only digits"};if(s){if(!a.startsWith("99"))return{isValid:!1,message:"SAC (Service) code must start with 99"};if(a.length!==6)return{isValid:!1,message:"SAC code must be exactly 6 digits"}}else{if(![4,6,8].includes(a.length))return{isValid:!1,message:"HSN code must be 4, 6, or 8 digits"};if(a.startsWith("99"))return{isValid:!1,message:"HSN code should not start with 99 (use SAC type for services)"}}return{isValid:!0,message:""}},A5={"01":"Jammu and Kashmir","02":"Himachal Pradesh","03":"Punjab","04":"Chandigarh","05":"Uttarakhand","06":"Haryana","07":"Delhi","08":"Rajasthan","09":"Uttar Pradesh",10:"Bihar",11:"Sikkim",12:"Arunachal Pradesh",13:"Nagaland",14:"Manipur",15:"Mizoram",16:"Tripura",17:"Meghalaya",18:"Assam",19:"West Bengal",20:"Jharkhand",21:"Odisha",22:"Chhattisgarh",23:"Madhya Pradesh",24:"Gujarat",25:"Daman and Diu",26:"Dadra and Nagar Haveli",27:"Maharashtra",29:"Karnataka",30:"Goa",31:"Lakshadweep Islands",32:"Kerala",33:"Tamil Nadu",34:"Pondicherry",35:"Andaman and Nicobar",36:"Telangana",37:"Andhra Pradesh",38:"Ladakh",97:"Others"},T5="33",k5=new Set(["04","25","26","31","35","38"]),v0=t=>{if(!t||t.length<2)return null;const s=t.substring(0,2);return A5[s]?s:null},R5=t=>t?k5.has(t):!1,D5=t=>t?t!==T5:!1,N0=t=>{if(!t)return{isIGST:!1,isCGST:!0,isSGST:!0,isUTGST:!1};if(D5(t))return{isIGST:!0,isCGST:!1,isSGST:!1,isUTGST:!1};const a=R5(t);return{isIGST:!1,isCGST:!0,isSGST:!a,isUTGST:a}};function F5({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",dealerGSTIN:n,activityName:i="Activity",requestId:l,defaultGstRate:o=18,documentPolicy:d,taxationType:c}){var we,Te;const[m,p]=h.useState(""),[x,u]=h.useState(""),g=h.useMemo(()=>{const de=v0(n);return N0(de)},[n]),b=h.useMemo(()=>c==="Non GST"||c==="Non-GST",[c]),[f,j]=h.useState([]),[y,v]=h.useState([]),[w,S]=h.useState([]),[C,I]=h.useState([]),[D,T]=h.useState(null),[N,_]=h.useState(""),[A,z]=h.useState(!1),[F,O]=h.useState(null),P=h.useRef(null),k=h.useRef(null),R=h.useRef(null),V=h.useRef(null),M=de=>{const q=de.type.toLowerCase(),ue=de.name.toLowerCase();return q.includes("image")||q.includes("pdf")||ue.endsWith(".pdf")||ue.endsWith(".jpg")||ue.endsWith(".jpeg")||ue.endsWith(".png")||ue.endsWith(".gif")||ue.endsWith(".webp")};h.useEffect(()=>()=>{F!=null&&F.url&&URL.revokeObjectURL(F.url)},[F]),h.useEffect(()=>{f.length===0&&j([{id:"1",description:"",amount:0,gstRate:o||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},[o]);const L=de=>{if(!M(de)){G.error("Preview is only available for images and PDF files");return}F!=null&&F.url&&URL.revokeObjectURL(F.url);const q=URL.createObjectURL(de);O({file:de,url:q})},U=de=>{const q=URL.createObjectURL(de),ue=document.createElement("a");ue.href=q,ue.download=de.name,document.body.appendChild(ue),ue.click(),document.body.removeChild(ue),URL.revokeObjectURL(q)},H=h.useMemo(()=>f.reduce((de,q)=>de+(q.totalAmt||q.amount||0),0),[f]),X=(de,q,ue=1)=>{const Pe=de*ue,ve=Pe*(q.cgstRate||0)/100,Ne=Pe*(q.sgstRate||0)/100,Ue=Pe*(q.utgstRate||0)/100,nt=Pe*(q.igstRate||0)/100,ot=ve+Ne+Ue+nt,Tt=Pe+ot;return{cgstRate:q.cgstRate,cgstAmt:ve,sgstRate:q.sgstRate,sgstAmt:Ne,utgstRate:q.utgstRate,utgstAmt:Ue,igstRate:q.igstRate,igstAmt:nt,gstAmt:ot,gstRate:(q.cgstRate||0)+(q.sgstRate||0)+(q.utgstRate||0)+(q.igstRate||0),totalAmt:Tt}},J=h.useMemo(()=>{const de=m!=="",q=y.length>0,ue=w.length>0,Pe=N.trim().length>0,ve=f.length>0&&f.every(Ue=>Ue.description.trim()!==""&&Ue.amount>=0),Ne=b?!1:f.some(Ue=>{const{isValid:nt}=Jr(Ue.hsnCode,Ue.isService);return!nt});return de&&q&&ue&&Pe&&ve&&!Ne},[m,y,w,N,b,f]),$=new Date().toISOString().split("T")[0],B=()=>{j([...f,{id:Date.now().toString(),description:"",amount:0,gstRate:o||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},K=(de,q,ue)=>{j(f.map(Pe=>{if(Pe.id===de){let ve={...Pe,[q]:ue};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate","quantity"].includes(q)){const Ne=parseFloat(ue);if(!isNaN(Ne)&&Ne<0)return G.error("Value cannot be negative"),Pe;const Ue=q==="amount"?parseFloat(ue)||0:Pe.amount,nt=q==="quantity"?parseInt(ue)||1:Pe.quantity;let ot=Pe.cgstRate,Tt=Pe.sgstRate,Mt=Pe.utgstRate,ne=Pe.igstRate;if(q==="cgstRate"){if(!g.isCGST)return Pe;ot=parseFloat(ue)||0,g.isUTGST?(Mt=ot,Tt=0):(Tt=ot,Mt=0),ne=0}else if(q==="sgstRate"){if(!g.isSGST)return Pe;Tt=parseFloat(ue)||0,ot=Tt,Mt=0,ne=0}else if(q==="utgstRate"){if(!g.isUTGST)return Pe;Mt=parseFloat(ue)||0,ot=Mt,Tt=0,ne=0}else if(q==="igstRate"){if(!g.isIGST)return Pe;ne=parseFloat(ue)||0,ot=0,Tt=0,Mt=0}else if(q==="gstRate"){const le=parseFloat(ue)||0;g.isIGST?(ne=le,ot=0,Tt=0,Mt=0):(ot=le/2,g.isUTGST?(Mt=le/2,Tt=0):(Tt=le/2,Mt=0),ne=0)}const Ie=X(Ue,{cgstRate:ot,sgstRate:Tt,igstRate:ne,utgstRate:Mt},nt);return{...ve,amount:Ue,quantity:nt,...Ie}}return ve}return Pe}))},se=de=>{j(f.filter(q=>q.id!==de))},Y=de=>{const q=Array.from(de.target.files||[]);if(q.length>0){const ue=[],Pe=d.maxFileSizeMB*1024*1024,ve=[".pdf",".doc",".docx",".zip",".rar"];q.forEach(Ne=>{var ot,Tt;const Ue="."+((ot=Ne.name.split(".").pop())==null?void 0:ot.toLowerCase()),nt=((Tt=Ne.name.split(".").pop())==null?void 0:Tt.toLowerCase())||"";if(Ne.size>Pe){G.error(`"${Ne.name}" exceeds ${d.maxFileSizeMB}MB limit and was not added.`);return}if(!ve.includes(Ue)){G.error(`"${Ne.name}" is not a supported document type (PDF, DOC, ZIP).`);return}if(!d.allowedFileTypes.includes(nt)){G.error(`"${Ne.name}" has an unallowed file type according to system policy.`);return}ue.push(Ne)}),ue.length>0&&v([...y,...ue]),P.current&&(P.current.value="")}},ee=de=>{v(y.filter((q,ue)=>ue!==de))},me=de=>{const q=Array.from(de.target.files||[]);if(q.length>0){const ue=[],Pe=d.maxFileSizeMB*1024*1024;q.forEach(ve=>{var Ue;const Ne=((Ue=ve.name.split(".").pop())==null?void 0:Ue.toLowerCase())||"";if(ve.size>Pe){G.error(`Photo "${ve.name}" exceeds ${d.maxFileSizeMB}MB limit.`);return}if(!ve.type.startsWith("image/")){G.error(`"${ve.name}" is not an image file.`);return}if(!d.allowedFileTypes.includes(Ne)){G.error(`"${ve.name}" has an unsupported image format.`);return}ue.push(ve)}),ue.length>0&&S([...w,...ue]),k.current&&(k.current.value="")}},Se=de=>{S(w.filter((q,ue)=>ue!==de))},Je=de=>{const q=Array.from(de.target.files||[]);if(q.length>0){const ue=[],Pe=d.maxFileSizeMB*1024*1024,ve=[".pdf",".jpg",".jpeg",".png"];q.forEach(Ne=>{var ot,Tt;const Ue="."+((ot=Ne.name.split(".").pop())==null?void 0:ot.toLowerCase()),nt=((Tt=Ne.name.split(".").pop())==null?void 0:Tt.toLowerCase())||"";if(Ne.size>Pe){G.error(`Invoice "${Ne.name}" exceeds ${d.maxFileSizeMB}MB limit.`);return}if(!ve.includes(Ue)){G.error(`"${Ne.name}" is not a supported type (PDF, JPG, PNG).`);return}if(!d.allowedFileTypes.includes(nt)){G.error(`"${Ne.name}" format is not allowed by system policy.`);return}ue.push(Ne)}),ue.length>0&&I([...C,...ue]),R.current&&(R.current.value="")}},Ve=de=>{I(C.filter((q,ue)=>ue!==de))},Ee=de=>{var ue,Pe,ve;const q=(ue=de.target.files)==null?void 0:ue[0];if(q){const Ne=d.maxFileSizeMB*1024*1024,Ue=[".pdf",".xlsx",".xls",".csv"],nt="."+((Pe=q.name.split(".").pop())==null?void 0:Pe.toLowerCase()),ot=((ve=q.name.split(".").pop())==null?void 0:ve.toLowerCase())||"";if(q.size>Ne){G.error(`Attendance file exceeds ${d.maxFileSizeMB}MB limit.`),V.current&&(V.current.value="");return}if(!Ue.includes(nt)){G.error("Please upload PDF, Excel, or CSV files only"),V.current&&(V.current.value="");return}if(!d.allowedFileTypes.includes(ot)){G.error(`"${q.name}" format is not allowed by system policy.`),V.current&&(V.current.value="");return}T(q)}},Oe=async()=>{if(!J){G.error("Please fill all required fields");return}if(f.some(Pe=>Pe.amount<0||Pe.quantity<1)){G.error("Please ensure all amounts are non-negative and quantity is at least 1");return}const q=f.filter(Pe=>Pe.description.trim()!==""&&Pe.amount>0);if(!b&&q.some(Pe=>Pe.description.trim()!==""&&Pe.amount>0&&(Pe.gstRate===0||!Pe.gstRate))&&!window.confirm(`One or more expenses have 0% GST. Are you sure you want to proceed? + `,children:[e.jsxs("div",{className:"p-4 sm:p-6 border-b border-gray-200 flex-1 flex flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 flex-shrink-0",children:[e.jsx("h3",{className:"text-base sm:text-lg font-semibold text-gray-900",children:"Participants"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>I(!1),className:"lg:hidden h-8 w-8 p-0",children:e.jsx(jt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 overflow-y-auto flex-1 pr-2",children:ee.map((ne,Ie)=>{const le=ne.userId===N;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(os,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(cs,{className:`text-white font-semibold text-sm ${ne.role==="Initiator"?"bg-green-600":le?"bg-blue-500":"bg-slate-600"}`,children:ne.avatar})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white ${$T(ne.status)}`})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium text-gray-900 truncate text-sm sm:text-base",children:[ne.name," ",le&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-xs text-gray-500",children:ne.role}),e.jsx("span",{className:"text-xs text-gray-400",children:"•"}),e.jsx("p",{className:"text-xs text-gray-500",children:UT(ne.status)})]}),ne.lastSeen&&ne.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:ne.lastSeen})]})]},Ie)})})]}),!Ve&&e.jsxs("div",{className:"p-4 sm:p-6 flex-shrink-0",children:[e.jsx("h4",{className:"font-semibold text-gray-900 mb-3 text-sm sm:text-base",children:"Quick Actions"}),e.jsxs("div",{className:"space-y-2",children:[l&&e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>k(!0),children:[e.jsx(qi,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(E,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>O(!0),children:[e.jsx(Nt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),A&&e.jsx(Or,{fileName:A.fileName,fileType:A.fileType,fileUrl:A.fileUrl,fileSize:A.fileSize,attachmentId:A.attachmentId,onDownload:tu,open:!!A,onClose:()=>z(null)}),!Ve&&e.jsx(o0,{open:F,onClose:()=>O(!1),onConfirm:Ne,requestIdDisplay:u,requestTitle:Y.title,existingParticipants:Oe}),!Ve&&l&&e.jsx(c0,{open:P,onClose:()=>k(!1),onConfirm:Ue,requestIdDisplay:u,requestTitle:Y.title,existingParticipants:Oe,currentLevels:d,maxApprovalLevels:m,onPolicyViolation:p}),e.jsx(pt,{open:K.open,onOpenChange:ne=>se(Ie=>({...Ie,open:ne})),children:e.jsxs(ut,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(xt,{className:"flex items-center gap-2",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:K.errors.map((ne,Ie)=>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:ne.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:ne.reason})]},Ie))}),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: ",$.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",$.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(It,{children:e.jsx(E,{onClick:()=>se({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(l0,{open:R,onClose:()=>V(!1),success:M.success,title:M.title,message:M.message})]})}function zT({requestId:t,requestTitle:s,mergedMessages:a,setWorkNoteAttachments:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:d,onPolicyViolation:c}){return e.jsx("div",{className:"h-[calc(100vh-300px)] min-h-[600px]",children:e.jsx(d0,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:d,onPolicyViolation:c})})}function HT({summary:t,loading:s,onShare:a,isInitiator:r}){const n=o=>{const d=o.toLowerCase();return d==="approved"?e.jsx($e,{className:"h-4 w-4 text-green-600"}):d==="rejected"?e.jsx(Ct,{className:"h-4 w-4 text-red-600"}):d==="pending"||d==="in progress"?e.jsx(st,{className:"h-4 w-4 text-orange-600"}):e.jsx(De,{className:"h-4 w-4 text-gray-600"})},i=o=>{const d=o.toLowerCase();return d==="approved"?"bg-green-100 text-green-700 border-green-300":d==="rejected"?"bg-red-100 text-red-700 border-red-300":d==="pending"||d==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},l=(o,d)=>o&&o.trim()&&o.trim().toUpperCase()!=="N/A"?o:d&&d.trim()&&d.trim().toUpperCase()!=="N/A"?d:"N/A";return s?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ke,{className:"h-12 w-12 animate-spin text-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading summary..."})]})}):t?e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200",children:[e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:t.title}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Request #",t.requestNumber]})]}),r&&a?e.jsxs(E,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(ln,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(re,{className:i(t.workflow.status),children:[n(t.workflow.status),e.jsx("span",{className:"ml-1 capitalize",children:t.workflow.status})]})]}),t.description&&e.jsx("div",{className:"mb-4",children:e.jsx(Is,{content:t.description,className:"text-gray-700"})})]}),e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Initiator"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.status})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Time Stamp"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:et(new Date(t.initiator.timestamp),"MMM dd, yy, HH:mm")})]})]})]}),t.approvers&&t.approvers.length>0&&e.jsxs("div",{className:"p-6 border-b border-gray-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Workflow"}),t.approvers.map((o,d)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsx("h4",{className:"text-md font-semibold text-gray-800 mb-3",children:o.levelName||`Approver ${o.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:o.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:l(o.designation,o.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-1",children:[n(o.status),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:o.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(o.timestamp),"MMM dd, yy, HH:mm")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),o.remarks?e.jsx(Is,{content:o.remarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]},d))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l(t.initiator.designation,t.initiator.department)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Status"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Concluded"})]}),t.isAiGenerated&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Source"}),e.jsx(re,{variant:"outline",className:"text-xs",children:"AI Generated"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),t.closingRemarks?e.jsx(Is,{content:t.closingRemarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]})]})]})}):e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(De,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-bold text-gray-900 mb-2",children:"Summary Not Available"}),e.jsx("p",{className:"text-gray-600",children:"Summary has not been generated for this request yet."})]})})}function WT({sla:t,requestStatus:s,isPaused:a=!1,testId:r="sla-progress"}){if(!(t&&(t.percentageUsed!==void 0||t.elapsedHours!==void 0))||s==="approved"||s==="rejected"||s==="closed")return e.jsxs("div",{className:"flex items-center gap-2","data-testid":`${r}-status-only`,children:[s==="closed"?e.jsx(rr,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx($e,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(Ct,{className:"h-4 w-4 text-red-600"}):e.jsx(st,{className:"h-4 w-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-medium text-gray-700",children:s==="closed"?"Request Closed":s==="approved"?"Request Approved":s==="rejected"?"Request Rejected":"SLA Not Available"})]});const i=t.percentageUsed!==void 0?t.percentageUsed:0,l=t.status||"on_track",d=a?{badge:"bg-gray-500 text-white",progress:"bg-gray-500",text:"text-gray-600",icon:"text-gray-500"}:i>=100?{badge:"bg-red-600 text-white animate-pulse",progress:"bg-red-600",text:"text-red-600",icon:"text-blue-600"}:i>=75?{badge:"bg-orange-500 text-white",progress:"bg-orange-500",text:"text-orange-600",icon:"text-blue-600"}:i>=50?{badge:"bg-amber-500 text-white",progress:"bg-amber-500",text:"text-amber-600",icon:"text-blue-600"}:{badge:"bg-green-600 text-white",progress:"bg-green-600",text:"text-gray-700",icon:"text-blue-600"},c=l==="on_track"||l==="normal"?"normal":l;return e.jsxs("div",{"data-testid":r,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[a?e.jsx(rr,{className:`h-4 w-4 ${d.icon}`}):e.jsx(st,{className:`h-4 w-4 ${d.icon}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:a?"SLA Progress (Paused)":"SLA Progress"})]}),e.jsxs(re,{className:`text-xs ${d.badge}`,"data-testid":`${r}-badge`,children:[i,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(qs,{value:i,className:"h-3 mb-2",indicatorClassName:d.progress,"data-testid":`${r}-bar`}),e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsxs("span",{className:"text-gray-600","data-testid":`${r}-elapsed`,children:[Xt(t.elapsedHours||0)," elapsed"]}),e.jsxs("span",{className:`font-semibold ${c==="breached"||c==="critical"?d.text:"text-gray-700"}`,"data-testid":`${r}-remaining`,children:[Xt(t.remainingHours||0)," remaining"]})]}),t.deadline&&e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${r}-deadline`,children:["Due: ",ka(t.deadline,!0)," • ",i,"% elapsed"]}),c==="critical"&&e.jsxs("p",{className:"text-xs text-orange-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-critical`,children:[e.jsx(ts,{className:"h-3.5 w-3.5"}),"Approaching Deadline"]}),c==="breached"&&e.jsxs("p",{className:"text-xs text-red-600 font-semibold mt-1 flex items-center gap-1.5","data-testid":`${r}-warning-breached`,children:[e.jsx(Ei,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function GT({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var g,b;const d=_T((t==null?void 0:t.priority)||"standard"),c=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",m=(g=t==null?void 0:t.form16Submission)==null?void 0:g.displayStatus,p=m&&/balance mismatch|failed/i.test(String(m)),x=m&&String(m).toLowerCase()==="duplicate",u=c&&m?{color:p?"bg-red-100 !text-red-800 border-red-200":m==="Completed"?"bg-green-100 !text-green-800 border-green-200":x?"bg-amber-100 !text-amber-800 border-amber-200":"bg-gray-100 !text-gray-700 border-gray-200",icon:Rx((t==null?void 0:t.status)||"pending").icon,label:m}:Rx((t==null?void 0:t.status)||"pending");return e.jsxs("div",{className:"bg-white rounded-lg shadow-sm border border-gray-300 mb-4 sm:mb-6","data-testid":"request-detail-header",children:[e.jsxs("div",{className:"p-3 sm:p-4 md:p-6 border-b border-gray-300",children:[e.jsxs("div",{className:"flex items-start sm:items-center justify-between gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:a,className:"rounded-lg flex-shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"back-button",children:e.jsx(ws,{className:"h-4 w-4 sm:h-5 sm:h-5"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0",children:e.jsx(De,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2 min-w-0 flex-1",children:[e.jsx("h1",{className:"text-sm sm:text-base md:text-lg font-bold text-gray-900 truncate","data-testid":"request-id",children:t.id||"N/A"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2",children:[e.jsx(re,{className:`${d.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"priority-badge",children:d.label}),e.jsx(re,{className:`${u.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:u.label}),(()=>{const f=(t==null?void 0:t.workflowType)||(t==null?void 0:t.workflow_type),j=(t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"",y=(j==null?void 0:j.toString().toUpperCase())||"",v=y==="FORM_16",w=f==="CLAIM_MANAGEMENT"||j==="claim-management",S=f==="DEALER_CLAIM"||y==="DEALER CLAIM"||y==="DEALER_CLAIM";let C="Non-Templatized",I="bg-purple-100 !text-purple-600 border-purple-200";return v?(C="Form 16",I="bg-emerald-100 !text-emerald-700 border-emerald-200"):S?(C="Dealer Claim",I="bg-blue-100 !text-blue-700 border-blue-200"):w?(C="Claim Management",I="bg-blue-100 !text-blue-700 border-blue-200"):y==="TEMPLATE"&&(C="Template"),e.jsx(re,{className:`${I} rounded-full px-2 sm:px-3 text-xs shrink-0`,variant:"outline","data-testid":"template-type-badge",children:C})})()]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&i&&((b=t==null?void 0:t.status)==null?void 0:b.toLowerCase())==="closed"&&e.jsxs(E,{variant:"default",size:"sm",className:"gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9",onClick:n,"data-testid":"share-summary-button",children:[e.jsx(ln,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Share Summary"})]}),e.jsxs(E,{variant:"outline",size:"sm",className:"gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9",onClick:r,disabled:s,"data-testid":"refresh-button",children:[e.jsx(Et,{className:`w-3.5 h-3.5 sm:w-4 sm:h-4 ${s?"animate-spin":""}`}),e.jsx("span",{className:"hidden sm:inline",children:s?"Refreshing...":"Refresh"})]})]})]}),e.jsx("div",{className:"mt-3 ml-0 sm:ml-14",children:e.jsx("h2",{className:"text-base sm:text-lg md:text-xl font-semibold text-gray-900 line-clamp-2","data-testid":"request-title",children:t.title})})]}),l!==void 0&&e.jsx("div",{className:`px-3 sm:px-4 md:px-6 py-3 sm:py-4 border-b border-gray-200 ${o?"bg-gradient-to-r from-gray-100 to-gray-200":"bg-gradient-to-r from-blue-50 to-indigo-50"}`,"data-testid":"sla-section",children:e.jsx(WT,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function Zc(t){return(await be.get(`/summaries/${t}`)).data.data}async function YT(t,s){return(await be.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function KT(t={}){var n,i;const{page:s=1,limit:a=20}=t,r=await be.get("/summaries/shared",{params:{page:s,limit:a}});return{data:((n=r.data.data)==null?void 0:n.data)||r.data.data||[],pagination:((i=r.data.data)==null?void 0:i.pagination)||{page:s,limit:a,total:0,totalPages:1}}}async function m0(t){await be.patch(`/summaries/shared/${t}/view`)}async function u0(t){var s;try{return(await be.get(`/summaries/request/${t}`)).data.data}catch(a){return((s=a==null?void 0:a.response)==null?void 0:s.status)===404,null}}async function QT(t){return(await be.get(`/summaries/${t}/recipients`)).data.data||[]}function XT({activityInfo:t,className:s,createdAt:a,updatedAt:r}){if(!t)return console.warn("[ActivityInformationCard] activityInfo is missing"),e.jsx(Z,{className:s,children:e.jsx(te,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Activity information not available"})})});const n=l=>{const o=typeof l=="string"?parseFloat(l):l;return isNaN(o)?"N/A":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`},i=l=>{if(!l)return"N/A";try{return et(new Date(l),"MMM d, yyyy")}catch{return l}};return e.jsxs(Z,{className:s,children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx(ht,{className:"w-5 h-5 text-blue-600"}),"Activity Information"]})}),e.jsxs(te,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.activityName})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Activity Type"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.activityType})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Location"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(Xo,{className:"w-4 h-4 text-gray-400"}),t.location]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Requested Date"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:i(t.requestedDate)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Estimated Budget"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(Ga,{className:"w-4 h-4 text-green-600"}),t.estimatedBudget!==void 0&&t.estimatedBudget!==null?n(t.estimatedBudget):"TBD"]})]}),t.closedExpenses!==void 0&&t.closedExpenses!==null&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Closed Expenses"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1 flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-blue-600"}),n(t.closedExpensesBreakdown&&t.closedExpensesBreakdown.length>0?t.closedExpensesBreakdown.reduce((l,o)=>l+(o.totalAmt||Number(o.amount)+Number(o.gstAmt||0)),0):t.closedExpenses)]})]}),t.period&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Period"}),e.jsxs("p",{className:"text-sm text-gray-900 font-medium mt-1",children:[i(t.period.startDate)," - ",i(t.period.endDate)]})]})]}),t.closedExpensesBreakdown&&t.closedExpensesBreakdown.length>0&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Closed Expenses Breakdown"}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full text-xs sm:text-sm",children:[e.jsx("thead",{className:"bg-blue-100/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left font-semibold text-blue-900",children:"Description"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-24",children:"Base"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-24",children:"GST"}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold text-blue-900 w-28",children:"Total"})]})}),e.jsxs("tbody",{className:"divide-y divide-blue-200/50",children:[t.closedExpensesBreakdown.map((l,o)=>e.jsxs("tr",{className:"hover:bg-blue-100/30",children:[e.jsxs("td",{className:"px-3 py-2 text-gray-700",children:[l.description,l.gstRate?e.jsxs("span",{className:"text-[10px] text-gray-400 block",children:[l.gstRate,"% GST"]}):null]}),e.jsx("td",{className:"px-3 py-2 text-right text-gray-900",children:n(l.amount)}),e.jsx("td",{className:"px-3 py-2 text-right text-gray-900",children:n(l.gstAmt||0)}),e.jsx("td",{className:"px-3 py-2 text-right font-medium text-gray-900",children:n(l.totalAmt||Number(l.amount)+Number(l.gstAmt||0))})]},o)),e.jsxs("tr",{className:"bg-blue-100/50 font-bold",children:[e.jsx("td",{colSpan:3,className:"px-3 py-2 text-blue-900",children:"Final Claim Amount"}),e.jsx("td",{className:"px-3 py-2 text-right text-blue-700",children:n(t.closedExpensesBreakdown.reduce((l,o)=>l+(o.totalAmt||Number(o.amount)+Number(o.gstAmt||0)),0))})]})]})]})})]}),t.description&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Description"}),e.jsx("div",{className:"mt-2 bg-gray-50 p-3 rounded-lg border border-gray-200",children:e.jsx(Is,{content:t.description||"",className:"text-sm"})})]}),(a||r)&&e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t border-gray-300",children:[a&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Created"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:gs(a)})]}),r&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Last Updated"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:gs(r)})]})]})]})]})}function JT({dealerInfo:t,className:s}){return t?!t.dealerCode&&!t.dealerName?(console.warn("[DealerInformationCard] Dealer info missing essential fields:",t),e.jsx(Z,{className:s,children:e.jsx(te,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information incomplete"})})})):e.jsxs(Z,{className:s,children:[e.jsx(oe,{children:e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx(tl,{className:"w-5 h-5 text-purple-600"}),"Dealer Information"]})}),e.jsxs(te,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Code"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.dealerCode})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Name"}),e.jsx("p",{className:"text-sm text-gray-900 font-medium mt-1",children:t.dealerName})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Contact Information"}),e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx(ja,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{children:t.email})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx(Kn,{className:"w-4 h-4 text-gray-400"}),e.jsx("span",{children:t.phone})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-gray-700",children:[e.jsx(Xo,{className:"w-4 h-4 text-gray-400 mt-0.5"}),e.jsx("span",{children:t.address})]})]})]})]})]}):(console.warn("[DealerInformationCard] dealerInfo is missing"),e.jsx(Z,{className:s,children:e.jsx(te,{className:"py-8 text-center text-gray-500",children:e.jsx("p",{children:"Dealer information not available"})})}))}function ZT({ioDetails:t,dmsDetails:s,claimAmount:a,estimatedBudgetBreakdown:r,closedExpensesBreakdown:n,visibility:i,onEditClaimAmount:l,className:o}){const d=x=>x==null||Number.isNaN(x)?"₹0.00":`₹${x.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,c=x=>{if(!x)return"";try{return et(new Date(x),"MMM d, yyyy, h:mm a")}catch{return x||""}},m=x=>!x||x.length===0?0:x.reduce((u,g)=>u+(g.totalAmt??g.amount+(g.gstAmt??0)),0);return i.showIODetails&&t||i.showDMSDetails&&s||(s==null?void 0:s.creditNoteWfmData)&&s.creditNoteWfmData.length>0||i.showClaimAmount&&a&&a.amount!==void 0&&a.amount!==null||r&&r.length>0||n&&n.length>0?e.jsxs(Z,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${o}`,children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"text-base flex items-center gap-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-blue-600"}),"Process Details"]}),e.jsx(ye,{children:"Workflow reference numbers"})]}),e.jsxs(te,{className:"space-y-3",children:[i.showIODetails&&t&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-blue-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-blue-600"}),e.jsx(ae,{className:"text-xs font-semibold text-blue-900 uppercase tracking-wide",children:"IO Number"})]}),e.jsx("p",{className:"font-bold text-gray-900 mb-2",children:t.ioNumber}),t.remarks&&e.jsxs("div",{className:"pt-2 border-t border-blue-100",children:[e.jsx("p",{className:"text-xs text-gray-600 mb-1",children:"Remark:"}),e.jsx("p",{className:"text-xs text-gray-900",children:t.remarks})]}),(t.availableBalance!==void 0||t.blockedAmount!==void 0)&&e.jsxs("div",{className:"pt-2 border-t border-blue-100 mt-2 space-y-1",children:[t.availableBalance!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Available Balance:"}),e.jsx("span",{className:"font-medium text-gray-900",children:d(t.availableBalance)})]}),t.blockedAmount!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Blocked Amount:"}),e.jsx("span",{className:"font-medium text-blue-700",children:d(t.blockedAmount)})]}),t.remainingBalance!==void 0&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Remaining Balance:"}),e.jsx("span",{className:"font-medium text-green-700",children:d(t.remainingBalance)})]})]}),e.jsxs("div",{className:"pt-2 border-t border-blue-100 mt-2",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["By ",t.blockedByName]}),e.jsx("p",{className:"text-xs text-gray-500",children:c(t.blockedAt)})]})]}),i.showDMSDetails&&s&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Bt,{className:"w-4 h-4 text-purple-600"}),e.jsx(ae,{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"E-Invoice Details"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-2",children:s.ackNo&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Ack No"}),e.jsx("p",{className:"font-bold text-sm text-purple-700",children:s.ackNo})]})}),s.irn&&e.jsxs("div",{className:"mb-2 p-2 bg-purple-50 rounded border border-purple-100",children:[e.jsx("p",{className:"text-[10px] text-purple-600 uppercase font-semibold",children:"IRN"}),e.jsx("p",{className:"text-[10px] font-mono break-all text-gray-700 leading-tight",children:s.irn})]}),s.signedInvoiceUrl&&e.jsxs(E,{variant:"outline",size:"sm",className:"w-full h-8 text-xs gap-2 mb-2 border-purple-200 text-purple-700 hover:bg-purple-50",onClick:()=>window.open(s.signedInvoiceUrl,"_blank"),children:[e.jsx(Pt,{className:"w-3.5 h-3.5"}),"View E-Invoice"]}),s.remarks&&e.jsxs("div",{className:"pt-2 border-t border-purple-100",children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase mb-1",children:"Remarks"}),e.jsx("p",{className:"text-xs text-gray-900",children:s.remarks})]}),e.jsxs("div",{className:"pt-2 border-t border-purple-100 mt-2",children:[e.jsxs("p",{className:"text-[10px] text-gray-500",children:["By ",s.createdByName]}),e.jsx("p",{className:"text-[10px] text-gray-500",children:c(s.createdAt)})]})]}),(s==null?void 0:s.creditNoteWfmData)&&s.creditNoteWfmData.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-pink-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-pink-600"}),e.jsx(ae,{className:"text-xs font-semibold text-pink-900 uppercase tracking-wide",children:"Credit Note Validation"})]}),e.jsx("div",{className:"space-y-2",children:s.creditNoteWfmData.map((x,u)=>e.jsxs("div",{className:"bg-pink-50 p-2 rounded border border-pink-100 text-[10px]",children:[e.jsxs("div",{className:"flex justify-between mb-1 text-pink-900",children:[e.jsxs("span",{className:"font-semibold break-words flex-1 pr-2",children:["Credit Note No: ",x.DOC_NO||"N/A"]}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-sm text-white font-medium self-start whitespace-nowrap ${x.MSG_TYP==="E"?"bg-red-500":"bg-green-500"}`,children:x.MSG_TYP==="E"?"Error":x.MSG_TYP==="S"?"Success":x.MSG_TYP||"Unknown"})]}),e.jsxs("div",{className:"text-gray-500 mb-0.5",children:["Txn: ",x.TRNS_UNIQ_NO||"N/A"]}),e.jsx("div",{className:"text-gray-700 break-words font-medium",children:x.MESSAGE||"No Message"})]},u))})]}),i.showClaimAmount&&a&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"w-4 h-4 text-green-600"}),e.jsx(ae,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),i.canEditClaimAmount&&l&&e.jsxs(E,{variant:"outline",size:"sm",onClick:l,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(_i,{className:"w-3 h-3 mr-1 text-green-700"}),"Edit"]})]}),e.jsx("p",{className:"text-2xl font-bold text-green-700",children:d(a.amount)}),a.lastUpdatedBy&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-green-100",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:["Last updated by ",a.lastUpdatedBy]}),a.lastUpdatedAt&&e.jsx("p",{className:"text-xs text-gray-500",children:c(a.lastUpdatedAt)})]})]}),r&&r.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-amber-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-amber-600"}),e.jsx(ae,{className:"text-xs font-semibold text-amber-900 uppercase tracking-wide",children:"Estimated Budget Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[r.map((x,u)=>e.jsxs("div",{className:"flex justify-between items-center text-[10px] sm:text-xs",children:[e.jsx("div",{className:"text-gray-700 truncate mr-2",title:x.description,children:x.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:d(x.totalAmt??x.amount+(x.gstAmt??0))})]},u)),e.jsxs("div",{className:"pt-2 border-t border-amber-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-amber-700",children:d(m(r))})]})]})]}),n&&n.length>0&&e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-indigo-200",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-indigo-600"}),e.jsx(ae,{className:"text-xs font-semibold text-indigo-900 uppercase tracking-wide",children:"Closed Expenses Breakdown"})]}),e.jsxs("div",{className:"space-y-1.5 pt-1",children:[n.map((x,u)=>e.jsxs("div",{className:"flex justify-between items-center text-[10px] sm:text-xs",children:[e.jsx("div",{className:"text-gray-700 truncate mr-2",title:x.description,children:x.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:d(x.totalAmt??x.amount+(x.gstAmt??0))})]},u)),e.jsxs("div",{className:"pt-2 border-t border-indigo-200 flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-gray-900 text-xs",children:"Total"}),e.jsx("span",{className:"font-bold text-indigo-700",children:d(m(n))})]})]})]})]})]}):null}function qT({proposalDetails:t,className:s}){const r=(()=>{const o=t.totalEstimatedBudget??t.estimatedBudgetTotal;return o??(t.costBreakup&&t.costBreakup.length>0?t.costBreakup.reduce((c,m)=>{const p=m.amount||0,x=m.gstAmt||0,u=m.totalAmt||Number(p)+Number(x);return c+(Number.isNaN(u)?0:u)},0):0)})(),n=o=>o==null||Number.isNaN(o)?"₹0.00":`₹${o.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,i=o=>{if(!o)return"";try{return et(new Date(o),"MMM d, yyyy, h:mm a")}catch{return o||""}},l=o=>{if(!o)return"-";try{return et(new Date(o),"MMM d, yyyy")}catch{return o||"-"}};return e.jsxs(Z,{className:s,children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx(Pt,{className:"w-5 h-5 text-green-600"}),"Proposal Details"]}),t.submittedOn&&e.jsxs(ye,{children:["Submitted on ",i(t.submittedOn)]})]}),e.jsxs(te,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block",children:"Cost Breakup"}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-gray-50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-left text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Item Description"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Base Amount"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"GST"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide",children:"Total"})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-200",children:[(t.costBreakup||[]).map((o,d)=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsxs("td",{className:"px-4 py-3 text-sm text-gray-900",children:[e.jsx("div",{children:o.description}),o.gstRate?e.jsx("div",{className:"text-[10px] text-gray-400",children:o.cgstAmt?`CGST: ${o.gstRate/2}%, SGST: ${o.gstRate/2}%`:`IGST: ${o.gstRate}%`}):null]}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right",children:n(o.amount)}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right",children:n(o.gstAmt)}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 text-right font-medium",children:n(o.totalAmt||Number(o.amount||0)+Number(o.gstAmt||0))})]},d)),e.jsxs("tr",{className:"bg-green-50 font-semibold",children:[e.jsx("td",{colSpan:3,className:"px-4 py-3 text-sm text-gray-900",children:"Estimated Budget (Total Inclusive of GST)"}),e.jsx("td",{className:"px-4 py-3 text-sm text-green-700 text-right",children:n(r)})]})]})]})})]}),e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Timeline for Closure"}),e.jsx("div",{className:"mt-2 bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ht,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{className:"text-sm font-medium text-gray-900",children:["Expected completion by: ",l(t.timelineForClosure)]})]})})]}),t.dealerComments&&e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Dealer Comments"}),e.jsx("p",{className:"text-sm text-gray-700 mt-2 bg-gray-50 p-3 rounded-lg whitespace-pre-line",children:t.dealerComments})]})]})]})}function e5({initiatorInfo:t,className:s}){const a=r=>r.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2);return e.jsxs(Z,{className:s,children:[e.jsx(oe,{children:e.jsx(ce,{className:"text-base",children:"Request Initiator"})}),e.jsx(te,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(os,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(cs,{className:"bg-gray-700 text-white font-semibold text-lg",children:a(t.name)})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:t.name}),t.role&&e.jsx("p",{className:"text-sm text-gray-600",children:t.role}),t.department&&e.jsx("p",{className:"text-sm text-gray-500",children:t.department}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[e.jsx(ja,{className:"w-4 h-4"}),e.jsx("span",{children:t.email})]}),t.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[e.jsx(Kn,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function x0(t,s){var a,r;try{if(!Yn(t))return null;const n=t.claimDetails||{},i=t.proposalDetails||{},l=t.completionDetails||{},o=t.internalOrder||t.internal_order||{},d=t.budgetTracking||t.budget_tracking||{},c=t.invoice||{},m=t.creditNote||t.credit_note||{},p=t.completionExpenses||t.completion_expenses||[],x=n.periodStartDate||n.period_start_date,u=n.periodEndDate||n.period_end_date,g=n.activityName||n.activity_name||"",b=n.activityType||n.activity_type||"",f=n.location||"",j=d.proposalEstimatedBudget??d.proposal_estimated_budget??d.initialEstimatedBudget??d.initial_estimated_budget??n.estimatedBudget??n.estimated_budget,y=(d==null?void 0:d.closedExpenses)??(d==null?void 0:d.closed_expenses)??(l==null?void 0:l.totalClosedExpenses)??(l==null?void 0:l.total_closed_expenses)??(n==null?void 0:n.closedExpenses)??(n==null?void 0:n.closed_expenses),v=y!=null?Number(y):void 0,w=Array.isArray(p)&&p.length>0?p.map(A=>({description:A.description||A.itemDescription||A.item_description||"",amount:Number(A.amount)||0,gstRate:A.gstRate??A.gst_rate,gstAmt:A.gstAmt??A.gst_amt,cgstAmt:A.cgstAmt??A.cgst_amt,sgstAmt:A.sgstAmt??A.sgst_amt,igstAmt:A.igstAmt??A.igst_amt,totalAmt:A.totalAmt??A.total_amt})):(l==null?void 0:l.closedExpenses)||(l==null?void 0:l.closed_expenses)||(l==null?void 0:l.closedExpensesBreakdown)||[],S={activityName:g,activityType:b,defaultGstRate:n.defaultGstRate||18,requestedDate:n.activityDate||n.activity_date||t.createdAt,location:f,period:x&&u?{startDate:x,endDate:u}:void 0,estimatedBudget:j,closedExpenses:v,closedExpensesBreakdown:w,description:t.description||""},C={dealerCode:(n==null?void 0:n.dealerCode)||(n==null?void 0:n.dealer_code)||(n==null?void 0:n.DealerCode)||"",dealerName:(n==null?void 0:n.dealerName)||(n==null?void 0:n.dealer_name)||(n==null?void 0:n.DealerName)||"",email:(n==null?void 0:n.dealerEmail)||(n==null?void 0:n.dealer_email)||(n==null?void 0:n.DealerEmail)||"",phone:(n==null?void 0:n.dealerPhone)||(n==null?void 0:n.dealer_phone)||(n==null?void 0:n.DealerPhone)||"",address:(n==null?void 0:n.dealerAddress)||(n==null?void 0:n.dealer_address)||(n==null?void 0:n.DealerAddress)||""};(!C.dealerCode||!C.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!n,dealerCode:C.dealerCode,dealerName:C.dealerName,rawClaimDetails:n,availableKeys:n?Object.keys(n):[]});const I=(i==null?void 0:i.expectedCompletionDate)||(i==null?void 0:i.expected_completion_date),D=i?{proposalDocumentUrl:i.proposalDocumentUrl||i.proposal_document_url,costBreakup:Array.isArray(i.costItems||i.cost_items)?(i.costItems||i.cost_items).map(A=>({description:A.description||A.itemDescription||A.item_description||"",amount:Number(A.amount)||0,gstRate:Number(A.gstRate??A.gst_rate??0),gstAmt:Number(A.gstAmt??A.gst_amt??0),cgstAmt:Number(A.cgstAmt??A.cgst_amt??0),sgstAmt:Number(A.sgstAmt??A.sgst_amt??0),igstAmt:Number(A.igstAmt??A.igst_amt??0),totalAmt:Number(A.totalAmt??A.total_amt??0)})):Array.isArray(i.costBreakup||i.cost_breakup)?(i.costBreakup||i.cost_breakup).map(A=>({description:A.description||A.itemDescription||A.item_description||"",amount:Number(A.amount)||0,gstRate:A.gstRate??A.gst_rate,gstAmt:A.gstAmt??A.gst_amt,cgstAmt:A.cgstAmt??A.cgst_amt,sgstAmt:A.sgstAmt??A.sgst_amt,igstAmt:A.igstAmt??A.igst_amt,totalAmt:A.totalAmt??A.total_amt})):[],totalEstimatedBudget:i.totalEstimatedBudget||i.total_estimated_budget||0,timelineMode:i.timelineMode||i.timeline_mode,expectedCompletionDate:I,expectedCompletionDays:i.expectedCompletionDays||i.expected_completion_days,timelineForClosure:I,dealerComments:i.dealerComments||i.dealer_comments,submittedOn:i.submittedAt||i.submitted_at||i.submittedOn}:void 0,T={ioNumber:o.ioNumber||o.io_number||n.ioNumber||n.io_number,ioRemark:o.ioRemark||o.io_remark||"",availableBalance:o.ioAvailableBalance||o.io_available_balance||n.ioAvailableBalance||n.io_available_balance,blockedAmount:o.ioBlockedAmount||o.io_blocked_amount||n.ioBlockedAmount||n.io_blocked_amount,remainingBalance:o.ioRemainingBalance||o.io_remaining_balance||n.ioRemainingBalance||n.io_remaining_balance,organizedBy:((a=o.organizer)==null?void 0:a.displayName)||((r=o.organizer)==null?void 0:r.name)||o.organizedBy||"",organizedAt:o.organizedAt||o.organized_at||""},N={eInvoiceNumber:c.invoiceNumber||c.invoice_number||n.eInvoiceNumber||n.e_invoice_number,eInvoiceDate:c.invoiceDate||c.invoice_date||n.eInvoiceDate||n.e_invoice_date,dmsNumber:c.dmsNumber||c.dms_number||n.dmsNumber||n.dms_number,creditNoteNumber:m.creditNoteNumber||m.credit_note_number||n.creditNoteNumber||n.credit_note_number,creditNoteDate:m.creditNoteDate||m.credit_note_date||n.creditNoteDate||n.credit_note_date,creditNoteAmount:m.creditNoteAmount?Number(m.creditNoteAmount):m.credit_note_amount?Number(m.credit_note_amount):m.creditNoteAmount?Number(m.creditNoteAmount):n.creditNoteAmount?Number(n.creditNoteAmount):n.credit_note_amount?Number(n.credit_note_amount):void 0,irn:c.irn||n.irn,ackNo:c.ackNo||n.ackNo,ackDate:c.ackDate||n.ackDate,signedInvoiceUrl:c.signedInvoiceUrl||n.signedInvoiceUrl,taxBreakdown:c.taxBreakdown||n.taxBreakdown,creditNoteWfmData:t.creditNoteWfmData||n.creditNoteWfmData||[]},_={estimated:S.estimatedBudget||0,closed:S.closedExpenses||0};return{activityInfo:S,dealerInfo:C,proposalDetails:D,ioDetails:Object.keys(T).some(A=>T[A])?T:void 0,dmsDetails:Object.keys(N).some(A=>N[A])?N:void 0,claimAmount:_}}catch(n){return console.error("[claimDataMapper] Error mapping claim data:",n),null}}function h0(t,s){var a,r;try{if(t.initiatorId===s||((a=t.initiator)==null?void 0:a.userId)===s||((r=t.requestedBy)==null?void 0:r.userId)===s)return"INITIATOR";if((t.participants||[]).find(c=>{var m;return(c.userId===s||((m=c.user)==null?void 0:m.userId)===s)&&(c.participantType==="DEALER"||c.type==="DEALER")}))return"DEALER";const l=t.approvalLevels||[];return l.find(c=>{var m;return c.levelNumber===3&&(c.approverId===s||((m=c.approver)==null?void 0:m.userId)===s)})?"DEPARTMENT_LEAD":l.find(c=>{var m;return(c.approverId===s||((m=c.approver)==null?void 0:m.userId)===s)&&c.status==="PENDING"})?"APPROVER":"SPECTATOR"}catch(n){return console.error("[claimDataMapper] Error determining user role:",n),"SPECTATOR"}}function p0(t){switch(t){case"INITIATOR":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!0,showDMSDetails:!0,showClaimAmount:!0,canEditClaimAmount:!1};case"DEALER":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!1,showDMSDetails:!1,showClaimAmount:!0,canEditClaimAmount:!1};case"DEPARTMENT_LEAD":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!0,showDMSDetails:!0,showClaimAmount:!0,canEditClaimAmount:!1};case"APPROVER":return{showDealerInfo:!0,showProposalDetails:!0,showIODetails:!0,showDMSDetails:!0,showClaimAmount:!0,canEditClaimAmount:!1};case"SPECTATOR":default:return{showDealerInfo:!1,showProposalDetails:!1,showIODetails:!1,showDMSDetails:!1,showClaimAmount:!1,canEditClaimAmount:!1}}}function t5({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:l,onReject:o,onPause:d,onResume:c,onRetrigger:m,summaryId:p,refreshTrigger:x,pausedByUserId:u,currentUserId:g,apiRequest:b,onEditClaimAmount:f,hideApproveReject:j=!1}){var k,R,V,M,L;const{user:y}=ds(),[v,w]=h.useState([]),[S,C]=h.useState(!1),[I,D]=h.useState(!1),T=(t==null?void 0:t.status)==="closed",N=((k=t==null?void 0:t.pauseInfo)==null?void 0:k.isPaused)||!1,_=u||((V=(R=t==null?void 0:t.pauseInfo)==null?void 0:R.pausedBy)==null?void 0:V.userId),A=g||(y==null?void 0:y.userId)||"",z=!N&&!T&&(r||s),F=N&&c&&(r||s),O=N&&s&&_&&_!==A&&m;h.useEffect(()=>{if(!N||!r||!(t!=null&&t.requestId)){D(!1);return}(async()=>{var H;try{const $=(((H=(await nr.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:H.notifications)||[]).some(B=>B.requestId===t.requestId&&B.notificationType==="pause_retrigger_request");D($)}catch(X){console.error("Failed to check retrigger notifications:",X),D(!1)}})()},[N,r,t==null?void 0:t.requestId,x]),h.useEffect(()=>{(async()=>{if(!T||!p||!s){w([]);return}try{C(!0);const H=await QT(p);w(H)}catch(H){console.error("Failed to fetch shared recipients:",H),w([])}finally{C(!1)}})()},[T,p,s,x]);const P=h.useMemo(()=>{if(!b||!Yn(b))return null;const U=x0(b);if(!U)return null;const H=h0(b,A),X=p0(H);return{claimRequest:U,visibility:X}},[b,A]);return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[!a&&t.status!=="closed"&&e.jsxs(Z,{"data-testid":"quick-actions-card",children:[e.jsx(oe,{className:"pb-2",children:e.jsx(ce,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(te,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-gray-700 border-gray-300 hover:bg-gray-50 hover:text-gray-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:n,"data-testid":"add-approver-button",children:[e.jsx(qi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-gray-700 border-gray-300 hover:bg-gray-50 hover:text-gray-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:i,"data-testid":"add-spectator-button",children:[e.jsx(Nt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),z&&d&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:d,"data-testid":"pause-workflow-button",children:[e.jsx(lr,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),F&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-green-700 border-green-300 hover:bg-green-50 hover:text-green-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:c,"data-testid":"resume-workflow-button",children:[e.jsx(Ii,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),O&&e.jsxs(E,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:m,"data-testid":"request-resume-button",children:[e.jsx(Ze,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Request Resume"]}),e.jsxs("div",{className:"pt-3 sm:pt-4 space-y-2",children:[r&&!N&&!j&&e.jsxs(e.Fragment,{children:[e.jsxs(E,{className:"w-full bg-green-600 hover:bg-green-700 text-white h-9 sm:h-10 text-xs sm:text-sm",onClick:l,"data-testid":"approve-request-button",children:[e.jsx($e,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Approve Request"]}),e.jsxs(E,{variant:"destructive",className:"w-full h-9 sm:h-10 text-xs sm:text-sm",onClick:o,"data-testid":"reject-request-button",children:[e.jsx(Ct,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Reject Request"]})]}),N&&e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3 text-center",children:_===A?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-orange-800 font-medium flex items-center justify-center gap-1.5",children:[I&&e.jsx(Ze,{className:"w-3.5 h-3.5"}),I?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:I?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&_!==A&&I?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-orange-800 font-medium flex items-center justify-center gap-1.5",children:[e.jsx(Ze,{className:"w-3.5 h-3.5"}),"Initiator has requested resume"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"Please review and resume if appropriate"})]}):r&&_!==A?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Workflow is paused"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"You can resume to continue approval"})]}):s&&_&&_!==A?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Approver has paused this workflow"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:O?'Click "Request Resume" to notify approver':"Resume request sent - Waiting for approver"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-orange-800 font-medium",children:"Workflow is paused"}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:"Actions are disabled until resumed"})]})})]})]})]}),e.jsxs(Z,{"data-testid":"spectators-card",children:[e.jsx(oe,{className:"pb-2",children:e.jsx(ce,{className:"text-sm sm:text-base",children:"Spectators"})}),e.jsx(te,{className:"space-y-3",children:t.spectators&&t.spectators.length>0?t.spectators.map((U,H)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${H}`,children:[e.jsx(os,{className:"h-8 w-8",children:e.jsx(cs,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:U.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:U.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:U.role})]})]},H)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),T&&s&&e.jsxs(Z,{"data-testid":"shared-recipients-card",children:[e.jsx(oe,{className:"pb-2",children:e.jsxs(ce,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(ln,{className:"w-4 h-4"}),"Summary Shared With"]})}),e.jsx(te,{className:"space-y-3",children:S?e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Loading..."})}):v.length>0?v.map((U,H)=>{const X=(U.displayName||"NA").split(" ").map(J=>J[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${H}`,children:[e.jsx(os,{className:"h-8 w-8",children:e.jsx(cs,{className:"bg-green-100 text-green-800 text-xs font-semibold",children:X})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:U.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:U.email}),U.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},U.userId||H)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),P&&e.jsx(ZT,{ioDetails:P.claimRequest.ioDetails,dmsDetails:P.claimRequest.dmsDetails,claimAmount:{amount:P.claimRequest.claimAmount.closed||P.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:(M=P.claimRequest.proposalDetails)==null?void 0:M.costBreakup,closedExpensesBreakdown:(L=P.claimRequest.activityInfo)==null?void 0:L.closedExpensesBreakdown,visibility:P.visibility,onEditClaimAmount:f})]})}function s5({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:l}){const[o,d]=h.useState(r),[c,m]=h.useState(!1),p=(o==null?void 0:o.length)||0,x=h.useMemo(()=>o.slice(0,500),[o]),u=async()=>{try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(pt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(ut,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-green-100 flex items-center justify-center",children:e.jsx($e,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(xt,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide your approval comments and remarks"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:l||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(re,{className:"bg-green-100 text-green-800 border-green-200",variant:"outline",children:"APPROVE"})]})]}),e.jsxs("div",{className:"space-y-2 mt-4",children:[e.jsx("label",{className:"text-sm font-semibold text-gray-800",children:"Comments & Remarks *"}),e.jsx(Os,{value:x,onChange:g=>d(g.target.value),rows:5,placeholder:"Enter your approval comments and any conditions or notes...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(p,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-green-50 border-green-200 text-green-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx($e,{className:"w-4 h-4"})}),e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-semibold",children:"Approval Confirmation"}),e.jsx("div",{children:"This request will be forwarded to the next approver or completed if this is the final step."})]})]}),e.jsxs(It,{className:"mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,disabled:c,children:"Cancel"}),e.jsxs(E,{onClick:u,disabled:c,className:"bg-green-600 hover:bg-green-700",children:[e.jsx($e,{className:"w-4 h-4 mr-2"}),c?"Approving...":"Approve Request"]})]})]})})}function a5({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:l}){const[o,d]=h.useState(r),[c,m]=h.useState(!1),p=(o==null?void 0:o.length)||0,x=h.useMemo(()=>o.slice(0,500),[o]),u=async()=>{if(!x.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(x),s()}finally{m(!1)}};return e.jsx(pt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(ut,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-red-100 flex items-center justify-center",children:e.jsx(Ct,{className:"w-7 h-7 text-red-600"})}),e.jsxs("div",{children:[e.jsx(xt,{className:"text-lg",children:n}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Please provide detailed reasons for rejection"})]})]})}),e.jsxs("div",{className:"border rounded-lg p-4 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Request ID"}),e.jsx("span",{className:"text-xs bg-gray-100 border border-gray-300 text-gray-800 rounded-full px-2 py-0.5",children:i||"—"})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800 block",children:"Title"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:l||"—"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-bold text-gray-800",children:"Action"}),e.jsx(re,{className:"bg-red-100 text-red-800 border-red-200",variant:"outline",children:"REJECT"})]})]}),e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("label",{className:"text-sm font-semibold text-gray-800",children:"Comments & Remarks *"}),e.jsx(Os,{value:x,onChange:g=>d(g.target.value),rows:5,placeholder:"Enter detailed reasons for rejection and any suggestions for improvement...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(p,500),"/500"]})]})]}),e.jsxs("div",{className:"mt-4 border rounded-lg p-3 bg-red-50 border-red-200 text-red-900 flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx(Ze,{className:"w-4 h-4"})}),e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-semibold",children:"Rejection Guidelines"}),e.jsx("div",{children:"Please provide specific, actionable feedback to help the initiator improve their request."})]})]}),e.jsxs(It,{className:"mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,disabled:c,children:"Cancel"}),e.jsxs(E,{variant:"destructive",onClick:u,disabled:c,children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),c?"Rejecting...":"Reject Request"]})]})]})})}function r5({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:l}){const[o,d]=h.useState(""),[c,m]=h.useState(!1),p=async()=>{if(o.trim())try{m(!0),await a(o.trim()),d(""),s()}catch(u){console.error("Failed to skip approver:",u)}finally{m(!1)}},x=()=>{c||(d(""),s())};return e.jsx(pt,{open:t,onOpenChange:x,children:e.jsxs(ut,{className:"sm:max-w-md max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:x,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:c,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(gt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center",children:e.jsx(Ze,{className:"w-5 h-5 text-orange-600"})}),e.jsx(xt,{className:"text-xl font-bold text-gray-900",children:"Skip Approver"})]})}),e.jsxs("div",{className:"space-y-4 px-6 py-4 overflow-y-auto flex-1",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ze,{className:"w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-orange-900 mb-1",children:"Important Notice"}),e.jsx("p",{className:"text-sm text-orange-800",children:"You are about to skip the current approver. The request will be moved to the next approval level."})]})]})}),(i||l)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ae,{className:"text-sm font-semibold text-gray-700",children:"Request Details"}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3 space-y-1",children:[i&&e.jsxs("p",{className:"text-sm text-gray-900",children:[e.jsx("span",{className:"font-medium",children:"Request ID:"})," ",i]}),l&&e.jsxs("p",{className:"text-sm text-gray-700",children:[e.jsx("span",{className:"font-medium",children:"Title:"})," ",l]})]})]}),(r||n)&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ae,{className:"text-sm font-semibold text-gray-700",children:"Approver Being Skipped"}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-1",children:[n&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Level:"})," ",n]}),r&&e.jsxs("p",{className:"text-sm text-blue-900",children:[e.jsx("span",{className:"font-medium",children:"Approver:"})," ",r]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ae,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx(Os,{id:"skip-reason",placeholder:"Please provide a detailed reason for skipping this approver (e.g., 'Approver is on leave until [date]', 'Approver unavailable - escalating to next level')",value:o,onChange:u=>d(u.target.value),className:"min-h-[100px] border-2 border-gray-300 focus:border-orange-500",disabled:c,autoFocus:!0}),e.jsx("p",{className:"text-xs text-gray-500",children:"This reason will be recorded in the activity log and all participants will be notified."})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:x,className:"flex-1 h-11 border-gray-300",disabled:c,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:p,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:c||!o.trim(),children:[e.jsx(Ze,{className:"w-4 h-4 mr-2"}),c?"Skipping...":"Skip Approver"]})]})]})})}function n5({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:l,documentError:o,request:d,skipApproverData:c,actionStatus:m,existingParticipants:p,currentLevels:x,maxApprovalLevels:u,onPolicyViolation:g,setShowApproveModal:b,setShowRejectModal:f,setShowAddApproverModal:j,setShowAddSpectatorModal:y,setShowSkipApproverModal:v,setShowActionStatusModal:w,setPreviewDocument:S,setDocumentError:C,setSkipApproverData:I,setActionStatus:D,handleApproveConfirm:T,handleRejectConfirm:N,handleAddApprover:_,handleAddSpectator:A,handleSkipApprover:z,downloadDocument:F,documentPolicy:O}){return e.jsxs(e.Fragment,{children:[e.jsx(s5,{open:t,onClose:()=>b(!1),onConfirm:T,requestIdDisplay:d.id,requestTitle:d.title}),e.jsx(a5,{open:s,onClose:()=>f(!1),onConfirm:N,requestIdDisplay:d.id,requestTitle:d.title}),e.jsx(c0,{open:a,onClose:()=>j(!1),onConfirm:_,requestIdDisplay:d.id,requestTitle:d.title,existingParticipants:p,currentLevels:x,maxApprovalLevels:u,onPolicyViolation:g}),e.jsx(o0,{open:r,onClose:()=>y(!1),onConfirm:A,requestIdDisplay:d.id,requestTitle:d.title,existingParticipants:p}),e.jsx(r5,{open:n,onClose:()=>{v(!1),I(null)},onConfirm:z,approverName:c==null?void 0:c.approverName,levelNumber:c==null?void 0:c.levelNumber,requestIdDisplay:d.id,requestTitle:d.title}),l&&e.jsx(Or,{fileName:l.fileName,fileType:l.fileType,fileUrl:hn(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:F,open:!!l,onClose:()=>S(null)}),m&&e.jsx(l0,{open:i,onClose:()=>{w(!1),D(null)},success:m.success,title:m.title,message:m.message}),e.jsx(pt,{open:o.show,onOpenChange:P=>C(k=>({...k,show:P})),children:e.jsxs(ut,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(xt,{className:"flex items-center gap-2",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:o.errors.map((P,k)=>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:P.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:P.reason})]},k))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",O.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",O.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(It,{children:e.jsx(E,{onClick:()=>C({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const g0={DocumentsTab:ET,ActivityTab:OT,WorkNotesTab:zT,SummaryTab:HT,RequestDetailHeader:GT,QuickActionsSidebar:t5,RequestDetailModals:n5};function qc({className:t,...s}){return e.jsx(zf,{"data-slot":"checkbox",className:Me("peer border bg-input-background dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(Hf,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(Wa,{className:"size-3.5"})})})}function f0({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,l]=h.useState(""),[o,d]=h.useState([]),[c,m]=h.useState(new Set),[p,x]=h.useState(!1),[u,g]=h.useState(!1);h.useEffect(()=>{if(!t){d([]);return}if(!i||!i.startsWith("@")||i.length<2){d([]),x(!1);return}const y=setTimeout(async()=>{var v;try{x(!0);const w=i.slice(1),S=await ya(w,10),C=((v=S==null?void 0:S.data)==null?void 0:v.data)||(S==null?void 0:S.data)||[];d(Array.isArray(C)?C:[])}catch(w){console.error("Failed to search users:",w),G.error("Failed to search users")}finally{x(!1)}},300);return()=>clearTimeout(y)},[i,t]);const b=y=>{m(v=>{const w=new Set(v);return w.has(y)?w.delete(y):w.add(y),w})},f=async()=>{var y,v;if(c.size===0){G.error("Please select at least one user to share with");return}try{g(!0),await YT(a,Array.from(c)),G.success(`Summary shared with ${c.size} user(s)`),m(new Set),l(""),d([]),n==null||n(),s()}catch(w){console.error("Failed to share summary:",w),G.error(((v=(y=w==null?void 0:w.response)==null?void 0:y.data)==null?void 0:v.message)||"Failed to share summary")}finally{g(!1)}},j=()=>{m(new Set),l(""),d([]),s()};return e.jsx(pt,{open:t,onOpenChange:j,children:e.jsxs(ut,{className:"sm:max-w-[500px]",children:[e.jsx(gt,{children:e.jsx(xt,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(ae,{className:"text-sm font-medium text-gray-700",children:"Request"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:r})]}),e.jsxs("div",{children:[e.jsx(ae,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(ys,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(ke,{id:"user-search",placeholder:"Type @ to search users...",value:i,onChange:y=>l(y.target.value),className:"pl-10"})]}),i&&!i.startsWith("@")&&e.jsx("p",{className:"text-xs text-gray-500 mt-1 ml-1",children:"Start with @ to search users (e.g., @john)"})]}),p&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ke,{className:"h-5 w-5 animate-spin text-blue-600"})}),!p&&o.length>0&&e.jsx("div",{className:"border rounded-lg max-h-[300px] overflow-y-auto",children:o.map(y=>{const v=c.has(y.userId);return e.jsxs("div",{className:"flex items-center gap-3 p-3 hover:bg-gray-50 border-b last:border-b-0 cursor-pointer",onClick:()=>b(y.userId),children:[e.jsx("div",{onClick:w=>w.stopPropagation(),onMouseDown:w=>w.stopPropagation(),className:"flex items-center",children:e.jsx(qc,{checked:v,onCheckedChange:()=>b(y.userId)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zt,{className:"h-4 w-4 text-gray-400 flex-shrink-0"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 truncate",children:y.displayName||y.email})]}),(y.designation||y.department)&&e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:y.designation||y.department}),e.jsx("p",{className:"text-xs text-gray-400 truncate",children:y.email})]})]},y.userId)})}),!p&&i&&i.startsWith("@")&&o.length===0&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"No users found"}),!p&&i&&!i.startsWith("@")&&e.jsx("div",{className:"text-center py-8 text-gray-500 text-sm",children:"Start typing with @ to search users"}),c.size>0&&e.jsxs("div",{className:"border rounded-lg p-3 bg-blue-50",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-700 mb-2",children:["Selected (",c.size,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(c).map(y=>{const v=o.find(w=>w.userId===y);return e.jsxs("div",{className:"flex items-center gap-1 bg-white px-2 py-1 rounded-full text-xs",children:[e.jsx("span",{children:(v==null?void 0:v.displayName)||(v==null?void 0:v.email)||y}),e.jsx("button",{onClick:()=>b(y),className:"ml-1 hover:text-red-600",children:e.jsx(jt,{className:"h-3 w-3"})})]},y)})})]})]}),e.jsxs(It,{children:[e.jsx(E,{variant:"outline",onClick:j,disabled:u,children:"Cancel"}),e.jsx(E,{onClick:f,disabled:u||c.size===0,children:u?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${c.size} user(s)`})]})]})})}function b0({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,l]=h.useState(""),[o,d]=h.useState(""),[c,m]=h.useState(!1),p=()=>as().add(1,"month").format("YYYY-MM-DD"),x=()=>as().add(1,"month").format("YYYY-MM-DD"),u=()=>as().add(1,"day").format("YYYY-MM-DD");h.useEffect(()=>{t&&!o&&d(p())},[t]);const g=async()=>{var v,w,S,C;if(!i.trim()){G.error("Please provide a reason for pausing");return}if(!o){G.error("Please select a resume date");return}const f=as(o),j=as().add(1,"month"),y=as().add(1,"day");if(f.isAfter(j)){G.error("Resume date cannot be more than 1 month from now");return}if(f.isBefore(y,"day")){G.error("Resume date must be at least 1 day from now");return}try{m(!0),await Ew(a,r,i.trim(),f.toDate()),G.success("Workflow paused successfully"),n&&await n(),l(""),d(p()),s()}catch(I){console.error("Failed to pause workflow:",I),G.error(((w=(v=I==null?void 0:I.response)==null?void 0:v.data)==null?void 0:w.error)||((C=(S=I==null?void 0:I.response)==null?void 0:S.data)==null?void 0:C.message)||"Failed to pause workflow")}finally{m(!1)}},b=()=>{c||(l(""),d(p()),s())};return e.jsx(pt,{open:t,onOpenChange:b,children:e.jsxs(ut,{className:"sm:max-w-[500px]",children:[e.jsx(gt,{children:e.jsxs(xt,{className:"flex items-center gap-2",children:[e.jsx(lr,{className:"w-5 h-5 text-orange-600"}),"Pause Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-orange-800",children:[e.jsx("strong",{children:"Note:"})," Pausing will temporarily halt TAT calculations and notifications. The workflow will automatically resume on the selected date."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ae,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Os,{id:"pause-reason",value:i,onChange:f=>l(f.target.value),placeholder:"Enter the reason for pausing this workflow...",className:"min-h-[100px] text-sm",disabled:c}),e.jsxs("p",{className:"text-xs text-gray-500",children:[i.length," / 1000 characters"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ae,{htmlFor:"resume-date",className:"text-sm font-medium",children:["Resume Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ke,{id:"resume-date",type:"date",value:o,onChange:f=>d(f.target.value),min:u(),max:x(),className:"text-sm",disabled:c}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum 1 month from today. The workflow will automatically resume on this date."})]})]}),e.jsxs(It,{children:[e.jsx(E,{variant:"outline",onClick:b,disabled:c,children:"Cancel"}),e.jsx(E,{onClick:g,disabled:c||!i.trim()||!o,className:"bg-orange-600 hover:bg-orange-700 text-white",children:c?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function j0({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=h.useState(""),[l,o]=h.useState(!1),d=async()=>{var m,p,x,u;try{o(!0),await _w(a,n.trim()||void 0),G.success("Workflow resumed successfully"),r&&await r(),i(""),s()}catch(g){console.error("Failed to resume workflow:",g),G.error(((p=(m=g==null?void 0:g.response)==null?void 0:m.data)==null?void 0:p.error)||((u=(x=g==null?void 0:g.response)==null?void 0:x.data)==null?void 0:u.message)||"Failed to resume workflow")}finally{o(!1)}},c=()=>{l||(i(""),s())};return e.jsx(pt,{open:t,onOpenChange:c,children:e.jsxs(ut,{className:"sm:max-w-[500px]",children:[e.jsx(gt,{children:e.jsxs(xt,{className:"flex items-center gap-2",children:[e.jsx(Ii,{className:"w-5 h-5 text-green-600"}),"Resume Workflow"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-green-50 border border-green-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-green-800",children:[e.jsx("strong",{children:"Note:"})," Resuming will restart TAT calculations and notifications. The workflow will continue from where it was paused."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ae,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx(Os,{id:"resume-notes",value:n,onChange:m=>i(m.target.value),placeholder:"Add any notes about why you're resuming this workflow...",className:"min-h-[100px] text-sm",disabled:l}),e.jsxs("p",{className:"text-xs text-gray-500",children:[n.length," / 1000 characters"]})]})]}),e.jsxs(It,{children:[e.jsx(E,{variant:"outline",onClick:c,disabled:l,children:"Cancel"}),e.jsx(E,{onClick:d,disabled:l,className:"bg-green-600 hover:bg-green-700 text-white",children:l?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ii,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function y0({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,l]=h.useState(!1),o=async()=>{var d,c,m,p;try{l(!0),await Mw(a),G.success("Retrigger request sent to approver"),n&&await n(),s()}catch(x){console.error("Failed to retrigger pause:",x),G.error(((c=(d=x==null?void 0:x.response)==null?void 0:d.data)==null?void 0:c.error)||((p=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:p.message)||"Failed to send retrigger request")}finally{l(!1)}};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(ut,{className:"sm:max-w-[450px]",children:[e.jsx(gt,{children:e.jsxs(xt,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-5 h-5 text-orange-600"}),"Request Resume"]})}),e.jsxs("div",{className:"py-4",children:[e.jsxs("p",{className:"text-sm text-gray-700 mb-4",children:["You are requesting the approver",r?` (${r})`:""," to cancel the pause and resume work on this request."]}),e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-orange-800",children:"A notification will be sent to the approver who paused this workflow, requesting them to resume it."})})]}),e.jsxs(It,{children:[e.jsx(E,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(E,{onClick:o,disabled:i,className:"bg-orange-600 hover:bg-orange-700 text-white",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:i5,ActivityTab:l5,WorkNotesTab:o5,SummaryTab:c5,RequestDetailHeader:d5,QuickActionsSidebar:m5,RequestDetailModals:u5}=g0;let x5=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("Custom RequestDetail Error:",s,a)}render(){var s;return this.state.hasError?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center",children:[e.jsx(ts,{className:"w-16 h-16 text-red-500 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Error Loading Request"}),e.jsx("p",{className:"text-gray-600 mb-4",children:((s=this.state.error)==null?void 0:s.message)||"An unexpected error occurred"}),e.jsx(E,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(E,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function h5({requestId:t,onBack:s,dynamicRequests:a=[]}){var Br,Qa,hr,Xa,pr,gr,Ja,Da,Za;const n=Oa().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,d]=h.useState(l),[c,m]=h.useState(!1),[p,x]=h.useState(null),[u,g]=h.useState(null),[b,f]=h.useState(!1),[j,y]=h.useState(0),[v,w]=h.useState(!1),[S,C]=h.useState(!1),[I,D]=h.useState(!1),[T,N]=h.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[_,A]=h.useState({open:!1,violations:[]}),{user:z}=ds(),{request:F,apiRequest:O,loading:P,refreshing:k,refreshDetails:R,currentApprovalLevel:V,isSpectator:M,isInitiator:L,existingParticipants:U,accessDenied:H}=Xc(n,a,z),{mergedMessages:X,unreadWorkNotes:J,workNoteAttachments:$,setWorkNoteAttachments:B}=a0(n,O,o,z),{uploadingDocument:K,triggerFileInput:se,previewDocument:Y,setPreviewDocument:ee,documentPolicy:me,documentError:Se,setDocumentError:Je}=r0(O,R),{showApproveModal:Ve,setShowApproveModal:Ee,showRejectModal:Oe,setShowRejectModal:ie,showAddApproverModal:ge,setShowAddApproverModal:we,showAddSpectatorModal:Te,setShowAddSpectatorModal:de,showSkipApproverModal:q,setShowSkipApproverModal:ue,showActionStatusModal:Pe,setShowActionStatusModal:ve,skipApproverData:Ne,setSkipApproverData:Ue,actionStatus:nt,setActionStatus:ot,handleApproveConfirm:Tt,handleRejectConfirm:Mt,handleAddApprover:ne,handleSkipApprover:Ie,handleAddSpectator:le}=i0(n,V,R),{conclusionRemark:Xe,setConclusionRemark:ze,conclusionLoading:tt,conclusionSubmitting:Qe,aiGenerated:rt,handleGenerateConclusion:qe,handleFinalizeConclusion:ct,generationAttempts:$s,generationFailed:ns,maxAttemptsReached:yt}=n0(F,n,L,R,s,ot,ve);h.useEffect(()=>{(async()=>{var As;try{const aa=await ma("SYSTEM_SETTINGS"),fr=await ma("WORKFLOW_SHARING"),br=[...aa,...fr],wa={};br.forEach(qa=>{wa[qa.configKey]=qa.configValue}),N({maxApprovalLevels:parseInt(wa.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(wa.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((As=wa.ALLOW_ADD_SPECTATOR)==null?void 0:As.toLowerCase())==="true",maxSpectators:parseInt(wa.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(aa){console.error("Failed to load system policy:",aa)}})()},[]),h.useEffect(()=>{const As=new URLSearchParams(window.location.search).get("tab");As&&d(As)},[n]);const mt=()=>{R()},Ft=()=>{w(!0)},Ss=()=>{C(!0)},ss=async()=>{await R()},$a=()=>{D(!0)},Ua=async()=>{await R()},ur=async()=>{await R()},va=async()=>{if(!(O!=null&&O.requestId)){G.error("Request ID not found");return}if(!p){G.error("Summary not available. Please ensure the request is closed and the summary has been generated.");return}m(!0)},Lt=((F==null?void 0:F.status)==="approved"||(F==null?void 0:F.status)==="rejected")&&L,Na=(F==null?void 0:F.status)==="closed"||(F==null?void 0:F.status)==="approved"&&!L||(F==null?void 0:F.status)==="rejected"&&!L,Ms=((F==null?void 0:F.templateType)||(F==null?void 0:F.template_type)||"").toString().toUpperCase()==="FORM_16";h.useEffect(()=>{Ms&&o==="worknotes"&&d("overview")},[Ms,o]),h.useEffect(()=>{(async()=>{if(!Na||!(O!=null&&O.requestId)){g(null),x(null);return}try{f(!0);const As=await u0(O.requestId);if(As!=null&&As.summaryId){x(As.summaryId);try{const aa=await Zc(As.summaryId);g(aa)}catch(aa){console.error("Failed to fetch summary details:",aa),g(null),x(null)}}else g(null),x(null)}catch{g(null),x(null)}finally{f(!1)}})()},[Na,O==null?void 0:O.requestId]);const $r=((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}));if(P&&!F&&!O)return e.jsx("div",{className:"flex items-center justify-center h-screen bg-gray-50","data-testid":"loading-state",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Et,{className:"w-12 h-12 text-blue-600 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading custom request details..."})]})});if(H!=null&&H.denied)return 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(fh,{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:H.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(ws,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})});if(!F)return 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(De,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-3",children:"Custom Request Not Found"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"The custom request you're looking for doesn't exist or may have been deleted."}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(E,{variant:"outline",onClick:s||(()=>window.history.back()),className:"flex items-center gap-2",children:[e.jsx(ws,{className:"w-4 h-4"}),"Go Back"]}),e.jsx(E,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})});const Ur=(z==null?void 0:z.role)==="MANAGEMENT"||(z==null?void 0:z.role)==="ADMIN",xr=((Br=at.getUserData())==null?void 0:Br.jobTitle)==="Dealer";return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-screen bg-gray-50","data-testid":"custom-request-detail-page",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[Ms&&e.jsx("p",{className:"text-sm text-emerald-700 font-medium mb-2","data-testid":"form16-details-heading",children:"Form 16 Details"}),e.jsx(d5,{request:F,refreshing:k,onBack:s||(()=>window.history.back()),onRefresh:mt,onShareSummary:va,isInitiator:L,slaData:((Qa=F==null?void 0:F.summary)==null?void 0:Qa.sla)||(F==null?void 0:F.sla)||null,isPaused:((hr=F==null?void 0:F.pauseInfo)==null?void 0:hr.isPaused)||!1}),e.jsxs(ii,{value:o,onValueChange:d,className:"w-full","data-testid":"custom-request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(li,{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($t,{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(bh,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:Ms?"Form 16":"Overview"})]}),Na&&u&&e.jsxs($t,{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(Jo,{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($t,{value:"workflow",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900","data-testid":"tab-workflow",children:[e.jsx(zs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Workflow"})]}),e.jsxs($t,{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(De,{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($t,{value:"activity",className:"flex items-center justify-center gap-1 sm:gap-1.5 rounded-md px-2 sm:px-3 py-2.5 sm:py-1.5 text-xs sm:text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 data-[state=active]:text-gray-900 col-span-1 sm:col-span-1","data-testid":"tab-activity",children:[e.jsx(Bt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Activity"})]}),!Ms&&e.jsxs($t,{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(Vs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),J>0&&e.jsx(re,{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:J>9?"9+":J})]})]})}),e.jsxs("div",{className:o==="worknotes"&&!Ms?"":"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:o==="worknotes"&&!Ms?"":"lg:col-span-2",children:[e.jsx(Ut,{value:"overview",className:"mt-0","data-testid":"overview-tab-content",children:Ms?e.jsx(qw,{request:F}):e.jsx(Gw,{request:F,isInitiator:L,needsClosure:Lt,conclusionRemark:Xe,setConclusionRemark:ze,conclusionLoading:tt,conclusionSubmitting:Qe,aiGenerated:rt,handleGenerateConclusion:qe,handleFinalizeConclusion:ct,onPause:Ft,onResume:Ss,onRetrigger:$a,currentUserIsApprover:!!V,pausedByUserId:(pr=(Xa=F==null?void 0:F.pauseInfo)==null?void 0:Xa.pausedBy)==null?void 0:pr.userId,currentUserId:z==null?void 0:z.userId,generationAttempts:$s,generationFailed:ns,maxAttemptsReached:yt})}),Na&&e.jsx(Ut,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(c5,{summary:u,loading:b,onShare:va,isInitiator:L})}),e.jsx(Ut,{value:"workflow",className:"mt-0",children:Ms?e.jsx(t1,{request:F,requestId:(O==null?void 0:O.requestId)||n,isReUser:Ur,onRefresh:R}):e.jsx(Xw,{request:F,user:z,isInitiator:L,onSkipApprover:Yt=>{if(!Yt.levelId){alert("Level ID not available");return}Ue(Yt),ue(!0)},onRefresh:R})}),e.jsx(Ut,{value:"documents",className:"mt-0",children:e.jsx(i5,{request:F,workNoteAttachments:$,uploadingDocument:K,documentPolicy:me,triggerFileInput:se,setPreviewDocument:ee,downloadDocument:_s,isSpectator:M})}),e.jsx(Ut,{value:"activity",className:"mt-0",children:e.jsx(l5,{request:F})}),!Ms&&e.jsx(Ut,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(o5,{requestId:n,requestTitle:F.title,mergedMessages:X,setWorkNoteAttachments:B,isInitiator:L,isSpectator:M,currentLevels:$r,onAddApprover:ne,maxApprovalLevels:T.maxApprovalLevels,onPolicyViolation:Yt=>A({open:!0,violations:Yt})})})]}),!xr&&o!=="worknotes"&&e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[Ms&&Ur&&e.jsx(PT,{requestId:(O==null?void 0:O.requestId)||n,request:F,onRefresh:R}),e.jsx(m5,{request:F,isInitiator:L,isSpectator:M,currentApprovalLevel:V,onAddApprover:()=>we(!0),onAddSpectator:()=>de(!0),onApprove:()=>Ee(!0),onReject:()=>ie(!0),onPause:Ft,onResume:Ss,onRetrigger:$a,summaryId:p,refreshTrigger:j,pausedByUserId:(Ja=(gr=F==null?void 0:F.pauseInfo)==null?void 0:gr.pausedBy)==null?void 0:Ja.userId,currentUserId:z==null?void 0:z.userId,apiRequest:O,hideApproveReject:xr})]})]})]})]})}),c&&p&&e.jsx(f0,{isOpen:c,onClose:()=>m(!1),summaryId:p,requestTitle:(F==null?void 0:F.title)||"N/A",onSuccess:()=>{R(),y(Yt=>Yt+1)}}),v&&(O==null?void 0:O.requestId)&&e.jsx(b0,{isOpen:v,onClose:()=>w(!1),requestId:O.requestId,levelId:(V==null?void 0:V.levelId)||null,onSuccess:Ua}),S&&(O==null?void 0:O.requestId)&&e.jsx(j0,{isOpen:S,onClose:()=>C(!1),requestId:O.requestId,onSuccess:ss}),I&&(O==null?void 0:O.requestId)&&e.jsx(y0,{isOpen:I,onClose:()=>D(!1),requestId:O.requestId,approverName:(Za=(Da=F==null?void 0:F.pauseInfo)==null?void 0:Da.pausedBy)==null?void 0:Za.name,onSuccess:ur}),e.jsx(u5,{showApproveModal:Ve,showRejectModal:Oe,showAddApproverModal:ge,showAddSpectatorModal:Te,showSkipApproverModal:q,showActionStatusModal:Pe,previewDocument:Y,documentError:Se,request:F,skipApproverData:Ne,actionStatus:nt,existingParticipants:U,currentLevels:$r,maxApprovalLevels:T.maxApprovalLevels,onPolicyViolation:Yt=>A({open:!0,violations:Yt}),setShowApproveModal:Ee,setShowRejectModal:ie,setShowAddApproverModal:we,setShowAddSpectatorModal:de,setShowSkipApproverModal:ue,setShowActionStatusModal:ve,setPreviewDocument:ee,setDocumentError:Je,setSkipApproverData:Ue,setActionStatus:ot,handleApproveConfirm:Tt,handleRejectConfirm:Mt,handleAddApprover:ne,handleAddSpectator:le,handleSkipApprover:Ie,downloadDocument:_s,documentPolicy:me}),e.jsx(ni,{open:_.open,onClose:()=>A({open:!1,violations:[]}),violations:_.violations,policyDetails:{maxApprovalLevels:T.maxApprovalLevels,maxParticipants:T.maxParticipants,allowSpectators:T.allowSpectators,maxSpectators:T.maxSpectators}})]})}function p5(t){return e.jsx(x5,{children:e.jsx(h5,{...t})})}const g5=[{value:"Q1",label:"Q1 (April - June)"},{value:"Q2",label:"Q2 (July - September)"},{value:"Q3",label:"Q3 (October - December)"},{value:"Q4",label:"Q4 (January - March)"}];function f5(){const t=new Date().getFullYear(),s=[];for(let a=0;a<4;a++){const r=t-a,n=(r+1).toString().slice(-2);s.push(`${r}-${n}`)}return s}function b5({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,form16FinancialYear:n="",form16Quarter:i="",sortBy:l,sortOrder:o,onSearchChange:d,onStatusFilterChange:c,onPriorityFilterChange:m,onTemplateTypeFilterChange:p,onForm16FinancialYearChange:x,onForm16QuarterChange:u,onSortByChange:g,onSortOrderChange:b,onClearFilters:f,activeFiltersCount:j}){const y=f5(),v=r==="FORM_16";return e.jsxs(Z,{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(Ma,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ye,{className:"text-xs sm:text-sm",children:j>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[j," filter",j>1?"s":""," active"]})})]})]}),j>0&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:f,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3",children:[e.jsx(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(te,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ys,{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(ke,{placeholder:"Search requests, IDs...",value:t,onChange:w=>d(w.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(He,{value:a,onValueChange:m,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:"All Priorities"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Priorities"}),e.jsx(Q,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ra,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(Q,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(He,{value:s,onValueChange:c,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:"All Statuses"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Statuses"}),e.jsx(Q,{value:"pending",children:"Pending (In Approval)"}),e.jsx(Q,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs(He,{value:r,onValueChange: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",children:e.jsx(We,{placeholder:"Request type"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Templates"}),e.jsx(Q,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Q,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(Q,{value:"FORM_16",children:"Form 16"})]})]}),v&&x&&e.jsxs(He,{value:n||void 0,onValueChange:x,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:"Financial Year"})}),e.jsx(Ye,{children:y.map(w=>e.jsx(Q,{value:w,children:w},w))})]}),v&&u&&e.jsxs(He,{value:i||void 0,onValueChange:u,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:"Quarter"})}),e.jsx(Ye,{children:g5.map(w=>e.jsx(Q,{value:w.value,children:w.label},w.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:l,onValueChange:w=>g(w),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(Q,{value:"due",children:"Due Date"}),e.jsx(Q,{value:"created",children:"Date Created"}),e.jsx(Q,{value:"priority",children:"Priority"}),e.jsx(Q,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>b(o==="asc"?"desc":"asc"),className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11",children:o==="asc"?e.jsx(sl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(al,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}const j5=[{value:"Q1",label:"Q1 (April - June)"},{value:"Q2",label:"Q2 (July - September)"},{value:"Q3",label:"Q3 (October - December)"},{value:"Q4",label:"Q4 (January - March)"}];function y5(){const t=new Date().getFullYear(),s=[];for(let a=0;a<4;a++){const r=t-a,n=(r+1).toString().slice(-2);s.push(`${r}-${n}`)}return s}function v5({searchTerm:t,priorityFilter:s,statusFilter:a,templateTypeFilter:r,form16FinancialYear:n="",form16Quarter:i="",sortBy:l,sortOrder:o,activeFiltersCount:d,onSearchChange:c,onPriorityChange:m,onStatusChange:p,onTemplateTypeChange:x,onForm16FinancialYearChange:u,onForm16QuarterChange:g,onSortByChange:b,onSortOrderChange:f,onClearFilters:j}){const y=y5(),v=r==="FORM_16";return e.jsxs(Z,{className:"shadow-lg border-0","data-testid":"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(Ma,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(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(E,{variant:"ghost",size:"sm",onClick:j,className:"text-red-600 hover:bg-red-50 gap-1 h-8 sm:h-9 px-2 sm:px-3","data-testid":"closed-requests-clear-filters",children:[e.jsx(jt,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Clear"})]})]})}),e.jsx(te,{className:"space-y-3 sm:space-y-4 px-3 sm:px-6",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ys,{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(ke,{placeholder:"Search requests, IDs...",value:t,onChange:w=>c(w.target.value),className:"pl-9 sm:pl-10 h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white transition-colors","data-testid":"closed-requests-search"})]}),e.jsxs(He,{value:s,onValueChange:m,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","data-testid":"closed-requests-priority-filter",children:e.jsx(We,{placeholder:"All Priorities"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Priorities"}),e.jsx(Q,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ra,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(Q,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(He,{value:a,onValueChange: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","data-testid":"closed-requests-status-filter",children:e.jsx(We,{placeholder:"Closure Type"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Closures"}),e.jsx(Q,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($e,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(Q,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs(He,{value:r,onValueChange:x,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","data-testid":"closed-requests-template-type-filter",children:e.jsx(We,{placeholder:"Request type"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Templates"}),e.jsx(Q,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(Q,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(Q,{value:"FORM_16",children:"Form 16"})]})]}),v&&u&&e.jsxs(He,{value:n||void 0,onValueChange:u,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",children:e.jsx(We,{placeholder:"Financial Year"})}),e.jsx(Ye,{children:y.map(w=>e.jsx(Q,{value:w,children:w},w))})]}),v&&g&&e.jsxs(He,{value:i||void 0,onValueChange:g,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",children:e.jsx(We,{placeholder:"Quarter"})}),e.jsx(Ye,{children:j5.map(w=>e.jsx(Q,{value:w.value,children:w.label},w.value))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(He,{value:l,onValueChange:w=>b(w),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","data-testid":"closed-requests-sort-by",children:e.jsx(We,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"due",children:"Due Date"}),e.jsx(Q,{value:"created",children:"Date Created"}),e.jsx(Q,{value:"priority",children:"Priority"})]})]}),e.jsx(E,{variant:"outline",size:"sm",onClick:f,className:"px-2 sm:px-3 h-9 sm:h-10 md:h-11","data-testid":"closed-requests-sort-order",children:o==="asc"?e.jsx(sl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(al,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function N5({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,departmentFilter:n,slaComplianceFilter:i,initiatorFilter:l,approverFilter:o,approverFilterType:d,dateRange:c,customStartDate:m,customEndDate:p,showCustomDatePicker:x,departments:u,loadingDepartments:g,initiatorSearch:b,approverSearch:f,showForm16Filter:j=!1,form16FinancialYear:y="all",form16Quarter:v="all",onForm16FinancialYearChange:w,onForm16QuarterChange:S,onSearchChange:C,onStatusChange:I,onPriorityChange:D,onTemplateTypeChange:T,onDepartmentChange:N,onSlaComplianceChange:_,onInitiatorChange:A,onApproverChange:z,onApproverTypeChange:F,onDateRangeChange:O,onCustomStartDateChange:P,onCustomEndDateChange:k,onShowCustomDatePickerChange:R,onApplyCustomDate:V,onClearFilters:M,hasActiveFilters:L}){return e.jsx(Z,{className:"border-gray-200 shadow-md","data-testid":"user-all-requests-filters",children:e.jsx(te,{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(Ma,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),L&&e.jsx(re,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),L&&e.jsxs(E,{variant:"ghost",size:"sm",onClick:M,className:"gap-2",children:[e.jsx(Et,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Jt,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"relative md:col-span-3 lg:col-span-1",children:[e.jsx(ys,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(ke,{placeholder:"Search requests...",value:t,onChange:U=>C(U.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(He,{value:s,onValueChange:I,children:[e.jsx(Ge,{className:"h-10","data-testid":"status-filter",children:e.jsx(We,{placeholder:"All Status"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Status"}),e.jsx(Q,{value:"pending",children:"Pending"}),e.jsx(Q,{value:"paused",children:"Paused"}),e.jsx(Q,{value:"approved",children:"Approved"}),e.jsx(Q,{value:"rejected",children:"Rejected"}),e.jsx(Q,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:a,onValueChange:D,children:[e.jsx(Ge,{className:"h-10","data-testid":"priority-filter",children:e.jsx(We,{placeholder:"All Priority"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Priority"}),e.jsx(Q,{value:"express",children:"Express"}),e.jsx(Q,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:r,onValueChange:T,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(Q,{value:"all",children:"All Templates"}),e.jsx(Q,{value:"CUSTOM",children:"Custom"}),e.jsx(Q,{value:"DEALER CLAIM",children:"Dealer Claim"}),j&&e.jsx(Q,{value:"FORM_16",children:"Form 16"})]})]}),j&&r==="FORM_16"&&e.jsxs(e.Fragment,{children:[e.jsxs(He,{value:y,onValueChange:w??(()=>{}),children:[e.jsx(Ge,{className:"h-10","data-testid":"form16-financial-year-filter",children:e.jsx(We,{placeholder:"Financial Year"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Years"}),e.jsx(Q,{value:"2024-25",children:"2024-25"}),e.jsx(Q,{value:"2023-24",children:"2023-24"}),e.jsx(Q,{value:"2022-23",children:"2022-23"})]})]}),e.jsxs(He,{value:v,onValueChange:S??(()=>{}),children:[e.jsx(Ge,{className:"h-10","data-testid":"form16-quarter-filter",children:e.jsx(We,{placeholder:"Quarter"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Quarters"}),e.jsx(Q,{value:"Q1",children:"Q1"}),e.jsx(Q,{value:"Q2",children:"Q2"}),e.jsx(Q,{value:"Q3",children:"Q3"}),e.jsx(Q,{value:"Q4",children:"Q4"})]})]})]}),e.jsxs(He,{value:n,onValueChange:N,disabled:g||u.length===0,children:[e.jsx(Ge,{className:"h-10","data-testid":"department-filter",children:e.jsx(We,{placeholder:g?"Loading...":"All Departments"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Departments"}),u.map(U=>e.jsx(Q,{value:U,children:U},U))]})]}),e.jsxs(He,{value:i,onValueChange:_,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(Q,{value:"all",children:"All SLA Status"}),e.jsx(Q,{value:"compliant",children:"Compliant"}),e.jsx(Q,{value:"on-track",children:"On Track"}),e.jsx(Q,{value:"approaching",children:"Approaching"}),e.jsx(Q,{value:"critical",children:"Critical"}),e.jsx(Q,{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(ae,{className:"text-sm font-medium text-gray-700 mb-2",children:"Initiator"}),e.jsx("div",{className:"relative",children:b.selectedUser?e.jsxs("div",{className:"flex items-center gap-2 h-10 px-3 bg-white border border-gray-300 rounded-md",children:[e.jsx("span",{className:"flex-1 text-sm text-gray-900 truncate",children:b.selectedUser.displayName||b.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:b.handleClear,children:e.jsx(jt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{placeholder:"Search initiator...",value:b.searchQuery,onChange:U=>b.handleSearch(U.target.value),onFocus:()=>{b.searchResults.length>0&&b.setShowResults(!0)},onBlur:()=>setTimeout(()=>b.setShowResults(!1),200),className:"h-10","data-testid":"initiator-search-input"}),b.showResults&&b.searchResults.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto",children:b.searchResults.map(U=>e.jsx("button",{type:"button",onClick:()=>b.handleSelect(U),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:U.displayName||U.email}),U.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:U.email})]})},U.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ae,{className:"text-sm font-medium text-gray-700",children:"Approver"}),o!=="all"&&F&&e.jsxs(He,{value:d,onValueChange:U=>F(U),children:[e.jsx(Ge,{className:"h-7 w-32 text-xs",children:e.jsx(We,{})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"current",children:"Current Only"}),e.jsx(Q,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children:f.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:f.selectedUser.displayName||f.selectedUser.email}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:f.handleClear,children:e.jsx(jt,{className:"h-3 w-3"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{placeholder:"Search approver...",value:f.searchQuery,onChange:U=>f.handleSearch(U.target.value),onFocus:()=>{f.searchResults.length>0&&f.setShowResults(!0)},onBlur:()=>setTimeout(()=>f.setShowResults(!1),200),className:"h-10","data-testid":"approver-search-input"}),f.showResults&&f.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:f.searchResults.map(U=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(U),className:"w-full px-4 py-2 text-left hover:bg-gray-50",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-gray-900",children:U.displayName||U.email}),U.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:U.email})]})},U.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(ht,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:c,onValueChange:U=>O(U),children:[e.jsx(Ge,{className:"w-[160px] h-10",children:e.jsx(We,{placeholder:"Date Range"})}),e.jsxs(Ye,{children:[e.jsx(Q,{value:"all",children:"All Time"}),e.jsx(Q,{value:"today",children:"Today"}),e.jsx(Q,{value:"week",children:"This Week"}),e.jsx(Q,{value:"month",children:"This Month"}),e.jsx(Q,{value:"last7days",children:"Last 7 Days"}),e.jsx(Q,{value:"last30days",children:"Last 30 Days"}),e.jsx(Q,{value:"custom",children:"Custom Range"})]})]}),c==="custom"&&e.jsxs(oa,{open:x,onOpenChange:R,children:[e.jsx(ca,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(ht,{className:"w-4 h-4"}),m&&p?`${et(m,"MMM d, yyyy")} - ${et(p,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(da,{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(ae,{htmlFor:"start-date",children:"Start Date"}),e.jsx(Xs,{value:m||null,onChange:U=>{const H=U?new Date(U):void 0;H?(P==null||P(H),p&&H>p&&(k==null||k(H))):P==null||P(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ae,{htmlFor:"end-date",children:"End Date"}),e.jsx(Xs,{value:p||null,onChange:U=>{const H=U?new Date(U):void 0;H?(k==null||k(H),m&&H{R==null||R(!1),P==null||P(void 0),k==null||k(void 0),O("month")},children:"Cancel"})]})]})})]})]})]})})})}function w5({request:t,apiRequest:s,currentUserId:a,isInitiator:r,onEditClaimAmount:n,className:i="",needsClosure:l=!1,conclusionRemark:o="",setConclusionRemark:d,conclusionLoading:c=!1,conclusionSubmitting:m=!1,aiGenerated:p=!1,handleGenerateConclusion:x,handleFinalizeConclusion:u,generationAttempts:g=0,generationFailed:b=!1,maxAttemptsReached:f=!1}){var S,C,I,D,T,N,_,A,z;if(!Yn(s))return e.jsx("div",{className:"text-center py-8 text-gray-500",children:e.jsx("p",{children:"This is not a claim management request."})});const j=x0(s);if(!j)return console.warn("[ClaimManagementOverviewTab] Failed to map claim data:",{apiRequest:s,hasClaimDetails:!!(s!=null&&s.claimDetails),hasProposalDetails:!!(s!=null&&s.proposalDetails),hasCompletionDetails:!!(s!=null&&s.completionDetails)}),e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx("p",{children:"Unable to load claim management data."}),e.jsx("p",{className:"text-xs mt-2",children:"Please ensure the request has been properly initialized."})]});const y=h0(s,a),v=p0(y),w={name:((S=s.initiator)==null?void 0:S.name)||((C=s.initiator)==null?void 0:C.displayName)||((I=s.initiator)==null?void 0:I.email)||"Unknown",role:((D=s.initiator)==null?void 0:D.role)||((T=s.initiator)==null?void 0:T.designation)||"Initiator",department:((N=s.initiator)==null?void 0:N.department)||s.department||"",email:((_=s.initiator)==null?void 0:_.email)||"N/A",phone:((A=s.initiator)==null?void 0:A.phone)||((z=s.initiator)==null?void 0:z.mobile)};return e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx(XT,{activityInfo:j.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(JT,{dealerInfo:j.dealerInfo}),v.showProposalDetails&&j.proposalDetails&&e.jsx(qT,{proposalDetails:j.proposalDetails}),e.jsx(e5,{initiatorInfo:w}),(s==null?void 0:s.status)==="closed"&&(s==null?void 0:s.conclusionRemark)&&e.jsxs(Z,{children:[e.jsxs(oe,{children:[e.jsxs(ce,{className:"flex items-center gap-2 text-base",children:[e.jsx($e,{className:"w-5 h-5 text-gray-600"}),"Conclusion Remark"]}),e.jsx(ye,{className:"mt-1 text-xs sm:text-sm",children:"Final summary of this closed request"})]}),e.jsxs(te,{className:"pt-4",children:[e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:e.jsx(Is,{content:s.conclusionRemark||"",className:"text-sm"})}),s.closureDate&&e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs text-gray-500 border-t border-gray-200 pt-3",children:[e.jsxs("span",{children:["Request closed on ",gs(s.closureDate)]}),e.jsxs("span",{children:["By ",w.name]})]})]})]}),l&&e.jsxs(Z,{"data-testid":"conclusion-remark-card",children:[e.jsx(oe,{className:`bg-gradient-to-r border-b ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"from-red-50 to-rose-50 border-red-200":"from-green-50 to-emerald-50 border-green-200"}`,children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(ce,{className:`flex items-center gap-2 text-base sm:text-lg ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"text-red-700":"text-green-700"}`,children:[e.jsx($e,{className:`w-5 h-5 ${((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"text-red-600":"text-green-600"}`}),"Conclusion Remark - Final Step"]}),e.jsx(ye,{className:"mt-1 text-xs sm:text-sm",children:((s==null?void 0:s.status)||"").toLowerCase()==="rejected"?"This request was rejected. Please review the AI-generated closure remark and finalize it to close this request.":"All approvals are complete. Please review and finalize the conclusion to close this request."})]}),x&&e.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:x,disabled:c||f,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx(Et,{className:`w-3.5 h-3.5 ${c?"animate-spin":""}`}),p?"Regenerate":"Generate with AI"]}),p&&!f&&!b&&e.jsxs("span",{className:"text-[10px] text-gray-500 font-medium px-1",children:[2-g," attempts remaining"]})]})]})}),e.jsx(te,{className:"pt-4",children:c?e.jsx("div",{className:"flex items-center justify-center py-8","data-testid":"conclusion-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ke,{className:"w-8 h-8 text-blue-600 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Preparing conclusion remark..."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Conclusion Remark"}),p&&e.jsx("span",{className:"text-xs text-blue-600","data-testid":"ai-generated-label",children:"✓ System-generated suggestion (editable)"})]}),d&&e.jsx(ei,{value:o,onChange:F=>d(F),placeholder:"Enter a professional conclusion remark summarizing the request outcome, key decisions, and approvals...",className:"text-sm",minHeight:"160px","data-testid":"conclusion-remark-textarea"}),e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx("p",{className:"text-xs text-gray-500",children:"This will be the final summary for this request"}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":"character-count",children:[o?o.replace(/<[^>]*>/g,"").length:0," / 2000 characters"]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs sm:text-sm font-semibold text-blue-900 mb-1.5",children:"Finalizing this request will:"}),e.jsxs("ul",{className:"text-xs sm:text-sm text-blue-800 space-y-0.5 pl-4",children:[e.jsx("li",{className:"list-disc",children:'Change request status to "CLOSED"'}),e.jsx("li",{className:"list-disc",children:"Notify all participants of closure"}),e.jsx("li",{className:"list-disc",children:"Move request to Closed Requests"}),e.jsx("li",{className:"list-disc",children:"Save conclusion remark permanently"})]})]}),u&&e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(E,{onClick:u,disabled:m||!o.trim(),className:"bg-green-600 hover:bg-green-700 text-white","data-testid":"finalize-close-button",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function C5({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n="Request",requestDescription:i="",requestId:l,levelName:o="Approval Level",approverName:d="Approver"}){const[c,m]=h.useState(""),[p,x]=h.useState(!1),[u,g]=h.useState(null),b=async()=>{if(!c.trim()){G.error("Please provide approval comments");return}try{x(!0),g("approve"),await a(c),j(),s()}catch(v){console.error("Failed to approve request:",v),G.error("Failed to approve request. Please try again.")}finally{x(!1),g(null)}},f=async()=>{if(!c.trim()){G.error("Please provide rejection reason");return}try{x(!0),g("reject"),await r(c),j(),s()}catch(v){console.error("Failed to reject request:",v),G.error("Failed to reject request. Please try again.")}finally{x(!1),g(null)}},j=()=>{m(""),g(null)},y=()=>{p||(j(),s())};return t?e.jsx(pt,{open:t,onOpenChange:y,children:e.jsxs(ut,{className:"dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl",children:[e.jsxs(gt,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(xt,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx($e,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),"Review Request"]}),e.jsxs(_t,{className:"text-xs lg:text-sm",children:[o,": Review request details and make a decision"]}),e.jsx("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:"Request ID:"})," ",l||"N/A"]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Approver:"})," ",d]})]})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden py-3 lg:py-4 px-6",children:e.jsxs("div",{className:"space-y-4",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(De,{className:"w-4 h-4 text-blue-600"}),"Request Title"]})}),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-medium text-gray-900",children:n})})]}),i&&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(Vs,{className:"w-4 h-4 text-blue-600"}),"Request Description"]})}),e.jsx("div",{className:"border rounded-lg p-2.5 lg:p-3 bg-gray-50 max-h-[200px] overflow-y-auto",children:e.jsx(Is,{content:i,className:"text-xs lg:text-sm text-gray-700"})})]}),e.jsxs("div",{className:"space-y-2 border-t pt-3 lg:pt-3",children:[e.jsx("h3",{className:"font-semibold text-sm lg:text-base",children:"Your Decision & Comments"}),e.jsx(Os,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:c,onChange:v=>m(v.target.value),className:"min-h-[80px] lg:min-h-[90px] text-xs lg:text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[c.length," characters"]})]}),!c.trim()&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-2 flex items-start gap-2",children:[e.jsx(Ct,{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(It,{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end px-6 pb-6 pt-3 lg:pt-4 flex-shrink-0 border-t bg-gray-50",children:[e.jsx(E,{variant:"outline",onClick:y,disabled:p,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{onClick:f,disabled:!c.trim()||p,variant:"destructive",className:"bg-red-600 hover:bg-red-700",children:p&&u==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),"Reject"]})}),e.jsx(E,{onClick:b,disabled:!c.trim()||p,className:"bg-green-600 hover:bg-green-700 text-white",children:p&&u==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"w-4 h-4 mr-2"}),"Approve"]})})]})]})]})}):null}function S5({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:l,requestNumber:o,requestId:d,dueDate:c,taxationType:m}){const[p,x]=h.useState(!1),[u,g]=h.useState(!1),b=m==="Non GST"||m==="Non-GST",f=(n==null?void 0:n.creditNoteNumber)&&(n==null?void 0:n.creditNoteNumber)!=="",j=(n==null?void 0:n.creditNoteNumber)||"",y=n!=null&&n.creditNoteDate?gs(n.creditNoteDate,{includeTime:!1,format:"short"}):"",v=(n==null?void 0:n.creditNoteAmount)||0,w=(n==null?void 0:n.status)||"PENDING",S=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",C=(i==null?void 0:i.dealerCode)||"RE-JP-009",I=l||"Activity",D=o||"RE-REQ-2024-CM-101",T=c?gs(c,{includeTime:!1,format:"short"}):"Jan 4, 2026",N=async()=>{if(a)try{x(!0),await a(),G.success("Credit note downloaded successfully")}catch(z){console.error("Failed to download credit note:",z),G.error("Failed to download credit note. Please try again.")}finally{x(!1)}else G.info("Credit note will be automatically saved to Documents tab")},_=async()=>{if(r)try{g(!0),await r(),G.success("Credit note sent to dealer successfully"),s()}catch(z){console.error("Failed to send credit note to dealer:",z),G.error("Failed to send credit note. Please try again.")}finally{g(!1)}else G.info("Email notification will be sent to dealer with credit note attachment")},A=z=>`₹${z.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(ut,{className:"sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(gt,{children:[e.jsxs(xt,{className:"font-semibold flex items-center gap-2 text-2xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note from SAP"]}),m&&e.jsx(re,{className:`ml-2 border-none shadow-sm ${b?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-emerald-600 text-white hover:bg-emerald-700"}`,children:b?"Non-GST Claim":"GST Claim"})]}),e.jsx(_t,{className:"text-base",children:"Review and send credit note to dealer"})]}),e.jsxs("div",{className:"space-y-5 py-4",children:[f?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-200 rounded-lg p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-green-900 text-xl mb-1",children:"Royal Enfield"}),e.jsx("p",{className:"text-sm text-green-700",children:"Credit Note Document"})]}),e.jsxs(re,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx($e,{className:"w-4 h-4 mr-2"}),w==="APPROVED"?"Approved":w==="ISSUED"?"Issued":w==="SENT"?"Sent":"Pending"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100",children:[e.jsxs(ae,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Pb,{className:"w-3 h-3"}),"Credit Note Number"]}),e.jsx("p",{className:"font-bold text-gray-900 mt-1 text-lg",children:j})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100",children:[e.jsxs(ae,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(ht,{className:"w-3 h-3"}),"Issue Date"]}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:y})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-5",children:[e.jsxs(ae,{className:"font-medium text-xs text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-3",children:[e.jsx(Ga,{className:"w-4 h-4"}),"Credit Note Amount"]}),e.jsx("p",{className:"text-4xl font-bold text-blue-700",children:A(v)})]})]}):e.jsx("div",{className:"bg-gray-50 border-2 border-gray-300 rounded-lg p-8 text-center",children:e.jsxs("div",{className:"flex flex-col items-center justify-center space-y-4",children:[e.jsx("div",{className:"w-16 h-16 bg-gray-200 rounded-full flex items-center justify-center",children:e.jsx(Pt,{className:"w-8 h-8 text-gray-400"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-700 mb-2",children:"No Credit Note Available"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Credit note has not been generated yet. Please wait for the credit note to be generated from DMS."})]})]})}),e.jsxs("div",{className:"bg-purple-50 border-2 border-purple-200 rounded-lg p-5",children:[e.jsxs("h3",{className:"font-semibold text-purple-900 mb-4 flex items-center gap-2",children:[e.jsx(tl,{className:"w-5 h-5"}),"Dealer Information"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(ae,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Name"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:S})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(ae,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Dealer Code"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:C})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(ae,{className:"flex items-center gap-2 font-medium text-xs text-gray-600 uppercase tracking-wider",children:"Activity"}),e.jsx("p",{className:"font-semibold text-gray-900 mt-1",children:I})]})]})]}),e.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4",children:[e.jsxs("h3",{className:"font-semibold text-gray-900 mb-3 flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4"}),"Reference Details"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx(ae,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Request ID"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:D})]}),e.jsxs("div",{children:[e.jsx(ae,{className:"flex items-center gap-2 font-medium text-xs text-gray-600",children:"Due Date"}),e.jsx("p",{className:"font-medium text-gray-900 mt-1",children:T})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(De,{className:"w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm text-blue-800",children:[e.jsx("p",{className:"font-semibold mb-2",children:"Available Actions"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-xs",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Download:"})," Credit note will be automatically saved to Documents tab"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Send to Dealer:"})," Email notification will be sent to dealer with credit note attachment"]}),e.jsx("li",{children:"All actions will be recorded in activity trail for audit purposes"})]})]})]})]}),e.jsxs(It,{className:"flex-col-reverse gap-2 sm:flex-row flex items-center justify-between sm:justify-between",children:[e.jsx(E,{variant:"outline",onClick:s,disabled:p||u,className:"border-2",children:"Close"}),e.jsx("div",{className:"flex gap-2",children:f&&e.jsxs(e.Fragment,{children:[e.jsxs(E,{variant:"outline",onClick:N,disabled:p||u,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(At,{className:"w-4 h-4 mr-2"}),p?"Downloading...":"Download"]}),e.jsxs(E,{onClick:_,disabled:p||u,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(ph,{className:"w-4 h-4 mr-2"}),u?"Sending...":"Send to Dealer"]})]})})]})]})})}const Jr=(t,s)=>{if(!t)return{isValid:!0,message:""};const a=t.trim();if(!/^\d+$/.test(a))return{isValid:!1,message:"Code must contain only digits"};if(s){if(!a.startsWith("99"))return{isValid:!1,message:"SAC (Service) code must start with 99"};if(a.length!==6)return{isValid:!1,message:"SAC code must be exactly 6 digits"}}else{if(![4,6,8].includes(a.length))return{isValid:!1,message:"HSN code must be 4, 6, or 8 digits"};if(a.startsWith("99"))return{isValid:!1,message:"HSN code should not start with 99 (use SAC type for services)"}}return{isValid:!0,message:""}},A5={"01":"Jammu and Kashmir","02":"Himachal Pradesh","03":"Punjab","04":"Chandigarh","05":"Uttarakhand","06":"Haryana","07":"Delhi","08":"Rajasthan","09":"Uttar Pradesh",10:"Bihar",11:"Sikkim",12:"Arunachal Pradesh",13:"Nagaland",14:"Manipur",15:"Mizoram",16:"Tripura",17:"Meghalaya",18:"Assam",19:"West Bengal",20:"Jharkhand",21:"Odisha",22:"Chhattisgarh",23:"Madhya Pradesh",24:"Gujarat",25:"Daman and Diu",26:"Dadra and Nagar Haveli",27:"Maharashtra",29:"Karnataka",30:"Goa",31:"Lakshadweep Islands",32:"Kerala",33:"Tamil Nadu",34:"Pondicherry",35:"Andaman and Nicobar",36:"Telangana",37:"Andhra Pradesh",38:"Ladakh",97:"Others"},T5="33",k5=new Set(["04","25","26","31","35","38"]),v0=t=>{if(!t||t.length<2)return null;const s=t.substring(0,2);return A5[s]?s:null},R5=t=>t?k5.has(t):!1,D5=t=>t?t!==T5:!1,N0=t=>{if(!t)return{isIGST:!1,isCGST:!0,isSGST:!0,isUTGST:!1};if(D5(t))return{isIGST:!0,isCGST:!1,isSGST:!1,isUTGST:!1};const a=R5(t);return{isIGST:!1,isCGST:!0,isSGST:!a,isUTGST:a}};function F5({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",dealerGSTIN:n,activityName:i="Activity",requestId:l,defaultGstRate:o=18,documentPolicy:d,taxationType:c}){var we,Te;const[m,p]=h.useState(""),[x,u]=h.useState(""),g=h.useMemo(()=>{const de=v0(n);return N0(de)},[n]),b=h.useMemo(()=>c==="Non GST"||c==="Non-GST",[c]),[f,j]=h.useState([]),[y,v]=h.useState([]),[w,S]=h.useState([]),[C,I]=h.useState([]),[D,T]=h.useState(null),[N,_]=h.useState(""),[A,z]=h.useState(!1),[F,O]=h.useState(null),P=h.useRef(null),k=h.useRef(null),R=h.useRef(null),V=h.useRef(null),M=de=>{const q=de.type.toLowerCase(),ue=de.name.toLowerCase();return q.includes("image")||q.includes("pdf")||ue.endsWith(".pdf")||ue.endsWith(".jpg")||ue.endsWith(".jpeg")||ue.endsWith(".png")||ue.endsWith(".gif")||ue.endsWith(".webp")};h.useEffect(()=>()=>{F!=null&&F.url&&URL.revokeObjectURL(F.url)},[F]),h.useEffect(()=>{f.length===0&&j([{id:"1",description:"",amount:0,gstRate:o||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},[o]);const L=de=>{if(!M(de)){G.error("Preview is only available for images and PDF files");return}F!=null&&F.url&&URL.revokeObjectURL(F.url);const q=URL.createObjectURL(de);O({file:de,url:q})},U=de=>{const q=URL.createObjectURL(de),ue=document.createElement("a");ue.href=q,ue.download=de.name,document.body.appendChild(ue),ue.click(),document.body.removeChild(ue),URL.revokeObjectURL(q)},H=h.useMemo(()=>f.reduce((de,q)=>de+(q.totalAmt||q.amount||0),0),[f]),X=(de,q,ue=1)=>{const Pe=de*ue,ve=Pe*(q.cgstRate||0)/100,Ne=Pe*(q.sgstRate||0)/100,Ue=Pe*(q.utgstRate||0)/100,nt=Pe*(q.igstRate||0)/100,ot=ve+Ne+Ue+nt,Tt=Pe+ot;return{cgstRate:q.cgstRate,cgstAmt:ve,sgstRate:q.sgstRate,sgstAmt:Ne,utgstRate:q.utgstRate,utgstAmt:Ue,igstRate:q.igstRate,igstAmt:nt,gstAmt:ot,gstRate:(q.cgstRate||0)+(q.sgstRate||0)+(q.utgstRate||0)+(q.igstRate||0),totalAmt:Tt}},J=h.useMemo(()=>{const de=m!=="",q=y.length>0,ue=w.length>0,Pe=N.trim().length>0,ve=f.length>0&&f.every(Ue=>Ue.description.trim()!==""&&Ue.amount>0),Ne=b?!1:f.some(Ue=>{const{isValid:nt}=Jr(Ue.hsnCode,Ue.isService);return!nt});return de&&q&&ue&&Pe&&ve&&!Ne},[m,y,w,N,b,f]),$=new Date().toISOString().split("T")[0],B=()=>{j([...f,{id:Date.now().toString(),description:"",amount:0,gstRate:o||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},K=(de,q,ue)=>{j(f.map(Pe=>{if(Pe.id===de){let ve={...Pe,[q]:ue};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate","quantity"].includes(q)){const Ne=parseFloat(ue);if(!isNaN(Ne)&&Ne<0)return G.error("Value cannot be negative"),Pe;const Ue=q==="amount"?parseFloat(ue)||0:Pe.amount,nt=q==="quantity"?parseInt(ue)||1:Pe.quantity;let ot=Pe.cgstRate,Tt=Pe.sgstRate,Mt=Pe.utgstRate,ne=Pe.igstRate;if(q==="cgstRate"){if(!g.isCGST)return Pe;ot=parseFloat(ue)||0,g.isUTGST?(Mt=ot,Tt=0):(Tt=ot,Mt=0),ne=0}else if(q==="sgstRate"){if(!g.isSGST)return Pe;Tt=parseFloat(ue)||0,ot=Tt,Mt=0,ne=0}else if(q==="utgstRate"){if(!g.isUTGST)return Pe;Mt=parseFloat(ue)||0,ot=Mt,Tt=0,ne=0}else if(q==="igstRate"){if(!g.isIGST)return Pe;ne=parseFloat(ue)||0,ot=0,Tt=0,Mt=0}else if(q==="gstRate"){const le=parseFloat(ue)||0;g.isIGST?(ne=le,ot=0,Tt=0,Mt=0):(ot=le/2,g.isUTGST?(Mt=le/2,Tt=0):(Tt=le/2,Mt=0),ne=0)}const Ie=X(Ue,{cgstRate:ot,sgstRate:Tt,igstRate:ne,utgstRate:Mt},nt);return{...ve,amount:Ue,quantity:nt,...Ie}}return ve}return Pe}))},se=de=>{j(f.filter(q=>q.id!==de))},Y=de=>{const q=Array.from(de.target.files||[]);if(q.length>0){const ue=[],Pe=d.maxFileSizeMB*1024*1024,ve=[".pdf",".doc",".docx",".zip",".rar"];q.forEach(Ne=>{var ot,Tt;const Ue="."+((ot=Ne.name.split(".").pop())==null?void 0:ot.toLowerCase()),nt=((Tt=Ne.name.split(".").pop())==null?void 0:Tt.toLowerCase())||"";if(Ne.size>Pe){G.error(`"${Ne.name}" exceeds ${d.maxFileSizeMB}MB limit and was not added.`);return}if(!ve.includes(Ue)){G.error(`"${Ne.name}" is not a supported document type (PDF, DOC, ZIP).`);return}if(!d.allowedFileTypes.includes(nt)){G.error(`"${Ne.name}" has an unallowed file type according to system policy.`);return}ue.push(Ne)}),ue.length>0&&v([...y,...ue]),P.current&&(P.current.value="")}},ee=de=>{v(y.filter((q,ue)=>ue!==de))},me=de=>{const q=Array.from(de.target.files||[]);if(q.length>0){const ue=[],Pe=d.maxFileSizeMB*1024*1024;q.forEach(ve=>{var Ue;const Ne=((Ue=ve.name.split(".").pop())==null?void 0:Ue.toLowerCase())||"";if(ve.size>Pe){G.error(`Photo "${ve.name}" exceeds ${d.maxFileSizeMB}MB limit.`);return}if(!ve.type.startsWith("image/")){G.error(`"${ve.name}" is not an image file.`);return}if(!d.allowedFileTypes.includes(Ne)){G.error(`"${ve.name}" has an unsupported image format.`);return}ue.push(ve)}),ue.length>0&&S([...w,...ue]),k.current&&(k.current.value="")}},Se=de=>{S(w.filter((q,ue)=>ue!==de))},Je=de=>{const q=Array.from(de.target.files||[]);if(q.length>0){const ue=[],Pe=d.maxFileSizeMB*1024*1024,ve=[".pdf",".jpg",".jpeg",".png"];q.forEach(Ne=>{var ot,Tt;const Ue="."+((ot=Ne.name.split(".").pop())==null?void 0:ot.toLowerCase()),nt=((Tt=Ne.name.split(".").pop())==null?void 0:Tt.toLowerCase())||"";if(Ne.size>Pe){G.error(`Invoice "${Ne.name}" exceeds ${d.maxFileSizeMB}MB limit.`);return}if(!ve.includes(Ue)){G.error(`"${Ne.name}" is not a supported type (PDF, JPG, PNG).`);return}if(!d.allowedFileTypes.includes(nt)){G.error(`"${Ne.name}" format is not allowed by system policy.`);return}ue.push(Ne)}),ue.length>0&&I([...C,...ue]),R.current&&(R.current.value="")}},Ve=de=>{I(C.filter((q,ue)=>ue!==de))},Ee=de=>{var ue,Pe,ve;const q=(ue=de.target.files)==null?void 0:ue[0];if(q){const Ne=d.maxFileSizeMB*1024*1024,Ue=[".pdf",".xlsx",".xls",".csv"],nt="."+((Pe=q.name.split(".").pop())==null?void 0:Pe.toLowerCase()),ot=((ve=q.name.split(".").pop())==null?void 0:ve.toLowerCase())||"";if(q.size>Ne){G.error(`Attendance file exceeds ${d.maxFileSizeMB}MB limit.`),V.current&&(V.current.value="");return}if(!Ue.includes(nt)){G.error("Please upload PDF, Excel, or CSV files only"),V.current&&(V.current.value="");return}if(!d.allowedFileTypes.includes(ot)){G.error(`"${q.name}" format is not allowed by system policy.`),V.current&&(V.current.value="");return}T(q)}},Oe=async()=>{if(!J){G.error("Please fill all required fields");return}if(f.some(Pe=>Pe.amount<0||Pe.quantity<1)){G.error("Please ensure all amounts are non-negative and quantity is at least 1");return}const q=f.filter(Pe=>Pe.description.trim()!==""&&Pe.amount>0);if(!b&&q.some(Pe=>Pe.description.trim()!==""&&Pe.amount>0&&(Pe.gstRate===0||!Pe.gstRate))&&!window.confirm(`One or more expenses have 0% GST. Are you sure you want to proceed? Note: If these items are taxable, please provide a valid GST rate to ensure correct E-Invoice generation.`)){z(!1);return}try{z(!0),await a({activityCompletionDate:m,numberOfParticipants:x?parseInt(x):void 0,closedExpenses:q,totalClosedExpenses:H,completionDocuments:y,activityPhotos:w,invoicesReceipts:C.length>0?C:void 0,attendanceSheet:D||void 0,completionDescription:N}),ie(),s()}catch(Pe){console.error("Failed to submit completion documents:",Pe),Jc(Pe)||G.error("Failed to submit completion documents. Please try again.")}finally{z(!1)}},ie=()=>{F!=null&&F.url&&URL.revokeObjectURL(F.url),O(null),p(""),u(""),j([{id:"1",description:"",amount:0,gstRate:o||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),v([]),S([]),I([]),T(null),_(""),P.current&&(P.current.value=""),k.current&&(k.current.value=""),R.current&&(R.current.value=""),V.current&&(V.current.value="")},ge=()=>{A||(ie(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(pt,{open:t,onOpenChange:ge,children:e.jsxs(ut,{className:"dealer-completion-documents-modal overflow-hidden flex flex-col",children:[e.jsxs(gt,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs(xt,{className:"font-semibold flex items-center gap-2 text-xl sm:text-2xl flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{className:"w-5 h-5 sm:w-6 sm:h-6 text-[--re-green]"}),"Activity Completion Documents"]}),c&&e.jsx(re,{className:`ml-2 border-none shadow-sm ${c==="GST"?"bg-emerald-600 text-white hover:bg-emerald-700":"bg-indigo-600 text-white hover:bg-indigo-700"}`,children:c==="GST"?"GST Claim":"Non-GST Claim"})]}),e.jsx(_t,{className:"text-sm sm:text-base",children:"Step 5: Upload completion proof and final documents"}),e.jsxs("div",{className:"space-y-1 mt-2 text-xs sm:text-sm text-gray-600",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Dealer:"})," ",r]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Activity:"})," ",i]}),e.jsx("div",{className:"mt-2",children:"Please upload completion documents, photos, and provide details about the completed activity."})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-6 py-3",children:[e.jsxs("div",{className:"space-y-5 sm:space-y-6",children:[e.jsxs("div",{className:"space-y-1.5 sm:space-y-2",children:[e.jsxs(ae,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDate",children:[e.jsx(ht,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Completion Date *"]}),e.jsx(Xs,{value:m||null,onChange:de=>p(de||""),maxDate:$,placeholderText:"dd/mm/yyyy",className:"w-full max-w-[280px]",wrapperClassName:"max-w-[280px]"})]}),e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h3",{className:"font-semibold text-base sm:text-lg",children:"Closed Expenses"})}),!b&&e.jsx("div",{className:"text-[10px] text-gray-500 italic mt-0.5",children:"Tax fields are automatically toggled based on the dealer's state (Inter-state vs Intra-state)."}),e.jsxs(E,{type:"button",onClick:B,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(bs,{className:"w-4 h-4 mr-1"}),"Add Expense"]})]}),e.jsx("div",{className:"space-y-3 sm:space-y-4 max-h-[400px] overflow-y-auto pr-1",children:f.map(de=>e.jsxs("div",{className:"p-4 border rounded-lg bg-gray-50/50 space-y-4 relative group",children:[e.jsxs("div",{className:"flex gap-3 items-start w-full",children:[e.jsxs("div",{className:`${b?"flex-[3]":"flex-1"} min-w-0`,children:[e.jsx(ae,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item description"}),e.jsx(ke,{placeholder:"e.g., Venue rental, Refreshments",value:de.description,onChange:q=>K(de.id,"description",q.target.value),className:"w-full bg-white text-sm"})]}),b&&e.jsxs("div",{className:"w-28 sm:w-36 flex-shrink-0",children:[e.jsx(ae,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount"}),e.jsxs("div",{className:"relative",children:[e.jsx(Zs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(ke,{type:"number",placeholder:"0.00",min:"0",step:"0.01",value:de.amount||"",onChange:q=>K(de.id,"amount",q.target.value),className:"w-full bg-white text-sm pl-8"})]})]}),!b&&e.jsxs("div",{className:"w-28 sm:w-36 flex-shrink-0",children:[e.jsx(ae,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsxs("div",{className:"relative",children:[e.jsx(Zs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),e.jsx(ke,{type:"number",placeholder:"0.00",min:"0",step:"0.01",value:de.amount||"",onChange:q=>K(de.id,"amount",q.target.value),className:"w-full bg-white text-sm pl-8"})]})]}),!b&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"w-20 sm:w-24 flex-shrink-0",children:[e.jsx(ae,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"HSN/SAC Code"}),e.jsx(ke,{placeholder:"HSN/SAC Code",value:de.hsnCode||"",onChange:q=>K(de.id,"hsnCode",q.target.value),className:`w-full bg-white text-sm ${Jr(de.hsnCode,de.isService).isValid?"":"border-red-500 focus-visible:ring-red-500"}`}),!Jr(de.hsnCode,de.isService).isValid&&e.jsx("span",{className:"text-[9px] text-red-500 mt-1 block leading-tight",children:Jr(de.hsnCode,de.isService).message})]}),e.jsxs("div",{className:"w-24 sm:w-28 flex-shrink-0",children:[e.jsx(ae,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item Type"}),e.jsxs("select",{value:de.isService?"SAC":"HSN",onChange:q=>K(de.id,"isService",q.target.value==="SAC"),className:"flex h-9 w-full rounded-md border border-input bg-white px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",children:[e.jsx("option",{value:"HSN",children:"HSN (Goods)"}),e.jsx("option",{value:"SAC",children:"SAC (Service)"})]})]}),e.jsxs("div",{className:"w-14 sm:w-16 flex-shrink-0",children:[e.jsx(ae,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"CGST %"}),e.jsx(ke,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:de.cgstRate||"",onChange:q=>K(de.id,"cgstRate",q.target.value),disabled:!g.isCGST,className:"w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-14 sm:w-16 flex-shrink-0",children:[e.jsx(ae,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"SGST %"}),e.jsx(ke,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:de.sgstRate||"",onChange:q=>K(de.id,"sgstRate",q.target.value),disabled:!g.isSGST,className:"w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-14 sm:w-16 flex-shrink-0",children:[e.jsx(ae,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"UTGST %"}),e.jsx(ke,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:de.utgstRate||"",onChange:q=>K(de.id,"utgstRate",q.target.value),disabled:!g.isUTGST,className:"w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"})]}),e.jsxs("div",{className:"w-14 sm:w-16 flex-shrink-0",children:[e.jsx(ae,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"IGST %"}),e.jsx(ke,{type:"number",placeholder:"%",min:"0",max:"100",step:"0.1",value:de.igstRate||"",onChange:q=>K(de.id,"igstRate",q.target.value),disabled:!g.isIGST,className:"w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"})]})]}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"mt-5 hover:bg-red-100 hover:text-red-700 flex-shrink-0 h-9 w-9 p-0",onClick:()=>se(de.id),children:e.jsx(jt,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:`grid grid-cols-2 sm:grid-cols-5 gap-3 pt-3 border-t border-dashed border-gray-200 ${b?"items-center":""}`,children:[b?e.jsx("div",{className:"col-span-4 invisible"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-4 text-gray-500 font-medium",children:[e.jsxs("span",{children:["CGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(de.cgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),de.sgstAmt>0&&e.jsxs("span",{children:["SGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(de.sgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),de.utgstAmt>0&&e.jsxs("span",{children:["UTGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(de.utgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs("span",{children:["IGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(de.igstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 items-center sm:justify-end",children:[e.jsxs("span",{className:"text-gray-500",children:["GST Total: ",e.jsxs("span",{className:"text-gray-900 font-bold",children:["₹",(de.gstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs(re,{className:"bg-[#2d4a3e] text-white px-3 py-1 text-xs",children:["Item Total: ₹",(de.totalAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]})]}),e.jsxs("div",{className:"flex flex-col items-end",children:[e.jsx("span",{className:"text-[10px] text-gray-500 uppercase",children:"Item Total"}),e.jsxs("span",{className:"text-sm font-bold text-[#2d4a3e]",children:["₹",(de.amount||0).toLocaleString("en-IN",{minimumFractionDigits:2})]})]})]})]},de.id))}),f.length===0&&e.jsx("p",{className:"text-xs sm:text-sm text-gray-500 italic",children:'No expenses added. Click "Add Expense" to add expense items.'}),f.length>0&&H>0&&e.jsx("div",{className:"pt-2 border-t",children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"font-semibold text-sm sm:text-base",children:"Total Closed Expenses:"}),e.jsxs("span",{className:"font-semibold text-base sm:text-lg",children:["₹",H.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})})]})]}),e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base sm:text-lg",children:"Completion Evidence"}),e.jsx(re,{variant:"outline",className:"text-xs border-red-500 text-red-700 bg-red-50 font-medium",children:"Required"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs("div",{children:[e.jsxs(ae,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(De,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Completion Documents *"]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload documents proving activity completion (reports, certificates, etc.) - Can upload multiple files or ZIP folder"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${y.length>0?"border-green-500 bg-green-50 hover:border-green-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:P,type:"file",multiple:!0,accept:[".pdf",".doc",".docx",".zip",".rar"].filter(de=>d.allowedFileTypes.includes(de.replace(".",""))).join(","),className:"hidden",id:"completionDocs",onChange:Y}),e.jsx("label",{htmlFor:"completionDocs",className:"cursor-pointer flex flex-col items-center gap-2",children:y.length>0?e.jsxs(e.Fragment,{children:[e.jsx(xs,{className:"w-8 h-8 text-green-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-green-700",children:[y.length," document",y.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-green-600",children:"Click to add more documents"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(js,{className:"w-8 h-8 text-gray-400"}),e.jsxs("span",{className:"text-sm text-gray-600",children:["Click to upload documents (Max ",d.maxFileSizeMB,"MB)"]}),e.jsx("p",{className:"text-[10px] text-gray-400",children:"PDF, DOC, ZIP allowed"})]})})]}),y.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Documents (",y.length,"):"]}),y.map((de,q)=>e.jsxs("div",{className:"flex items-start justify-between bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 p-2 sm:p-3 rounded-lg text-xs sm:text-sm shadow-sm hover:shadow-md transition-shadow w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 flex-1 min-w-0 pr-2",children:[e.jsx(De,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-green-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:de.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(de)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>L(de),title:"Preview file",children:e.jsx(Nt,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>U(de),title:"Download file",children:e.jsx(At,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>ee(q),title:"Remove document",children:e.jsx(jt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},q))]})]}),e.jsxs("div",{children:[e.jsxs(ae,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(bi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Photos *"]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload photos from the completed activity (event photos, installations, etc.)"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${w.length>0?"border-green-500 bg-green-50 hover:border-green-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:k,type:"file",multiple:!0,accept:[".jpg",".jpeg",".png",".gif",".webp"].filter(de=>d.allowedFileTypes.includes(de.replace(".",""))).join(","),className:"hidden",id:"completionPhotos",onChange:me}),e.jsx("label",{htmlFor:"completionPhotos",className:"cursor-pointer flex flex-col items-center gap-2",children:w.length>0?e.jsxs(e.Fragment,{children:[e.jsx(xs,{className:"w-8 h-8 text-green-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-green-700",children:[w.length," photo",w.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-green-600",children:"Click to add more photos"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(bi,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload photos (JPG, PNG - multiple files allowed)"})]})})]}),w.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Photos (",w.length,"):"]}),w.map((de,q)=>e.jsxs("div",{className:"flex items-start justify-between bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 p-2 sm:p-3 rounded-lg text-xs sm:text-sm shadow-sm hover:shadow-md transition-shadow w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 flex-1 min-w-0 pr-2",children:[e.jsx(bi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-green-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:de.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(de)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>L(de),title:"Preview photo",children:e.jsx(Nt,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>U(de),title:"Download photo",children:e.jsx(At,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>Se(q),title:"Remove photo",children:e.jsx(jt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},q))]})]})]})]}),e.jsxs("div",{className:"space-y-3 sm:space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-base sm:text-lg",children:"Supporting Documents"}),e.jsx(re,{className:"bg-secondary text-secondary-foreground text-xs",children:"Optional"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6",children:[e.jsxs("div",{children:[e.jsxs(ae,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Pt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Invoices / Receipts"]}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload invoices and receipts for expenses incurred"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${C.length>0?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:R,type:"file",multiple:!0,accept:[".pdf",".jpg",".jpeg",".png"].filter(de=>d.allowedFileTypes.includes(de.replace(".",""))).join(","),className:"hidden",id:"invoiceReceipts",onChange:Je}),e.jsx("label",{htmlFor:"invoiceReceipts",className:"cursor-pointer flex flex-col items-center gap-2",children:C.length>0?e.jsxs(e.Fragment,{children:[e.jsx(xs,{className:"w-8 h-8 text-blue-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-blue-700",children:[C.length," document",C.length!==1?"s":""," selected"]}),e.jsx("span",{className:"text-xs text-blue-600",children:"Click to add more documents"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Pt,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload invoices/receipts (PDF, JPG, PNG)"})]})})]}),C.length>0&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium text-gray-600 mb-1",children:["Selected Documents (",C.length,"):"]}),C.map((de,q)=>e.jsxs("div",{className:"flex items-start justify-between bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 p-2 sm:p-3 rounded-lg text-xs sm:text-sm shadow-sm hover:shadow-md transition-shadow w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 flex-1 min-w-0 pr-2",children:[e.jsx(Pt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:de.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(de)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>L(de),title:"Preview file",children:e.jsx(Nt,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>U(de),title:"Download file",children:e.jsx(At,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>Ve(q),title:"Remove document",children:e.jsx(jt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},q))]})]}),e.jsxs("div",{children:[e.jsx(ae,{className:"text-sm sm:text-base font-semibold",children:"Attendance Sheet / Participant List"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 mb-2",children:"Upload attendance records or participant lists (if applicable)"}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${D?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:V,type:"file",accept:[".pdf",".xlsx",".xls",".csv"].filter(de=>d.allowedFileTypes.includes(de.replace(".",""))).join(","),className:"hidden",id:"attendanceDoc",onChange:Ee}),e.jsx("label",{htmlFor:"attendanceDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:D?e.jsxs(e.Fragment,{children:[e.jsx(xs,{className:"w-8 h-8 text-blue-600"}),e.jsxs("div",{className:"flex flex-col items-center gap-1 w-full max-w-full px-2",children:[e.jsx("span",{className:"text-sm font-semibold text-blue-700 break-words text-center w-full max-w-full",children:D.name}),e.jsx("span",{className:"text-xs text-blue-600",children:"Document selected"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(js,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload attendance sheet (Excel, PDF, CSV)"})]})})]}),D&&e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"text-xs font-medium text-gray-600 mb-2",children:"Selected Document:"}),e.jsxs("div",{className:"flex items-start justify-between bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 p-2 sm:p-3 rounded-lg text-xs sm:text-sm shadow-sm hover:shadow-md transition-shadow w-full",children:[e.jsxs("div",{className:"flex items-start gap-2 flex-1 min-w-0 pr-2",children:[e.jsx(De,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:"text-gray-800 font-medium break-words break-all",children:D.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[M(D)&&e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>L(D),title:"Preview file",children:e.jsx(Nt,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>U(D),title:"Download file",children:e.jsx(At,{className:"w-3.5 h-3.5"})}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>{T(null),V.current&&(V.current.value="")},title:"Remove document",children:e.jsx(jt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5 sm:space-y-2 max-w-3xl",children:[e.jsx(ae,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDescription",children:"Brief Description of Completion *"}),e.jsx(Os,{id:"completionDescription",placeholder:"Provide a brief description of the completed activity, including key highlights, outcomes, challenges faced, and any relevant observations...",value:N,onChange:de=>_(de.target.value),className:"min-h-[100px] sm:min-h-[120px] text-sm"}),e.jsxs("p",{className:"text-xs text-gray-500",children:[N.length," characters"]})]}),!J&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 sm:p-4 flex items-start gap-2 sm:gap-3",children:[e.jsx(Ze,{className:"w-4 h-4 sm:w-5 sm:h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs sm:text-sm text-amber-800",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Missing or Invalid Information"}),e.jsx("p",{children:"Please ensure completion date, documents/photos, description, and expense details (non-negative amounts and descriptions) are provided before submitting."})]})]})]}),e.jsxs(It,{className:"flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 pt-3 pb-6 border-t flex-shrink-0",children:[e.jsx(E,{variant:"outline",onClick:ge,disabled:A,className:"border-2",children:"Cancel"}),e.jsx(E,{onClick:Oe,disabled:A||!J,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:A?"Submitting...":"Submit Documents"})]})]})}),F&&e.jsx(pt,{open:!!F,onOpenChange:()=>{F!=null&&F.url&&URL.revokeObjectURL(F.url),O(null)},children:e.jsx(ut,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(gt,{className:"pb-4 flex-shrink-0 pr-8",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(Nt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(xt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:F.file.name}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[F.file.type||"Unknown type"," • ",(F.file.size/1024).toFixed(1)," KB"]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>U(F.file),className:"gap-2 h-9",children:[e.jsx(At,{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:(we=F.file.type)!=null&&we.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:F.url,alt:F.file.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):(Te=F.file.type)!=null&&Te.includes("pdf")||F.file.name.toLowerCase().endsWith(".pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:F.url,className:"w-full h-full rounded-lg border-0",title:F.file.name,style:{minHeight:"70vh",height:"100%"}})}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(Nt,{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."}),e.jsxs(E,{onClick:()=>U(F.file),className:"gap-2",children:[e.jsx(At,{className:"h-4 w-4"}),"Download ",F.file.name]})]})})]})})})]})}function P5({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",dealerGSTIN:n,activityName:i="Activity",requestId:l,previousProposalData:o,defaultGstRate:d=18,documentPolicy:c,taxationType:m,totalBlockedAmount:p=0}){const[x,u]=h.useState(null),g=h.useMemo(()=>{const ie=v0(n);return N0(ie)},[n]),b=h.useMemo(()=>m==="Non GST"||m==="Non-GST",[m]),[f,j]=h.useState([{id:"1",description:"",amount:0,gstRate:d||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),y=(ie,ge,we=1)=>{const Te=ie*we,de=Te*(ge.cgstRate||0)/100,q=Te*(ge.sgstRate||0)/100,ue=Te*(ge.utgstRate||0)/100,Pe=Te*(ge.igstRate||0)/100,ve=de+q+ue+Pe,Ne=Te+ve;return{cgstRate:ge.cgstRate,cgstAmt:de,sgstRate:ge.sgstRate,sgstAmt:q,utgstRate:ge.utgstRate,utgstAmt:ue,igstRate:ge.igstRate,igstAmt:Pe,gstAmt:ve,gstRate:(ge.cgstRate||0)+(ge.sgstRate||0)+(ge.utgstRate||0)+(ge.igstRate||0),totalAmt:Ne}},[v,w]=h.useState("date"),[S,C]=h.useState(""),[I,D]=h.useState(""),[T,N]=h.useState([]),[_,A]=h.useState(""),[z,F]=h.useState(!1),[O,P]=h.useState(null),[k,R]=h.useState(!1),V=h.useRef(null),M=h.useRef(null),L=ie=>{if(!ie)return!1;const ge=ie.toLowerCase();return ge.endsWith(".pdf")||!!ge.match(/\.(jpg|jpeg|png|gif|webp)$/i)},U=ie=>L(ie.name);h.useEffect(()=>()=>{O!=null&&O.fileUrl&&O.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(O.fileUrl)},[O]);const H=ie=>{if(!U(ie)){G.error("Preview is only available for images and PDF files");return}O!=null&&O.fileUrl&&O.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(O.fileUrl);const ge=URL.createObjectURL(ie);P({fileName:ie.name,fileType:ie.type,documentId:"",fileUrl:ge,fileSize:ie.size})},X=ie=>{const ge=ie.originalFileName||ie.fileName||ie.name||"Document",we=ie.documentId||ie.id||"",Te=ge.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let de="";if(we)de=hn(we);else if(de=ie.storageUrl||ie.documentUrl||"",de&&!de.startsWith("http")){const q="https://reflow-uat.royalenfield.com",ue=q.endsWith("/")?q.slice(0,-1):q,Pe=de.startsWith("/")?de:`/${de}`;de=`${ue}${Pe}`}P({fileName:ge,fileType:Te,documentId:we,fileUrl:de})},J=ie=>{const ge=URL.createObjectURL(ie),we=document.createElement("a");we.href=ge,we.download=ie.name,document.body.appendChild(we),we.click(),document.body.removeChild(we),URL.revokeObjectURL(ge)};h.useEffect(()=>{if(t&&o){const ie=p>0;if(o.costItems&&o.costItems.length>0){const ge=o.costItems.map((we,Te)=>({id:`original-${Te}`,description:we.itemDescription||we.description||"",amount:Number(we.amount)||0,quantity:Number(we.quantity)||1,hsnCode:we.hsnCode||"",isService:!!we.isService,gstRate:Number(we.gstRate)||d,cgstRate:Number(we.cgstRate)||0,sgstRate:Number(we.sgstRate)||0,utgstRate:Number(we.utgstRate)||0,igstRate:Number(we.igstRate)||0,gstAmt:Number(we.gstAmt)||0,cgstAmt:Number(we.cgstAmt)||0,sgstAmt:Number(we.sgstAmt)||0,utgstAmt:Number(we.utgstAmt)||0,igstAmt:Number(we.igstAmt)||0,cessRate:Number(we.cessRate)||0,cessAmt:Number(we.cessAmt)||0,totalAmt:Number(we.totalAmt)||0,isOriginal:ie}));j(ge)}o.expectedCompletionDate&&(C(o.expectedCompletionDate.split("T")[0]),w("date"))}else t&&!o&&(j([{id:"1",description:"",amount:0,gstRate:d||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}]),C(""),A(""))},[t,o,d,p]);const $=h.useMemo(()=>f.reduce((ie,ge)=>ie+(ge.totalAmt||ge.amount||0),0),[f]),B=h.useMemo(()=>{const ie=x!==null,ge=f.length>0&&f.every(q=>q.description.trim()!==""&&q.amount>0),we=v==="date"?S!=="":I!==""&&parseInt(I)>0,Te=_.trim().length>0,de=b?!1:f.some(q=>{const{isValid:ue}=Jr(q.hsnCode,q.isService);return!ue});return ie&&ge&&we&&Te&&!de},[x,f,v,S,I,_,b]),K=ie=>{var we,Te,de;const ge=(we=ie.target.files)==null?void 0:we[0];if(ge){const q=c.maxFileSizeMB*1024*1024;if(ge.size>q){G.error(`File size exceeds the maximum allowed size of ${c.maxFileSizeMB}MB. Current size: ${(ge.size/(1024*1024)).toFixed(2)}MB`),V.current&&(V.current.value="");return}const ue=[".pdf",".doc",".docx"],Pe="."+((Te=ge.name.split(".").pop())==null?void 0:Te.toLowerCase()),ve=((de=ge.name.split(".").pop())==null?void 0:de.toLowerCase())||"";if(!ue.includes(Pe)||!c.allowedFileTypes.includes(ve)){G.error("Please upload a valid PDF, DOC, or DOCX file as per system policy"),V.current&&(V.current.value="");return}u(ge)}},se=ie=>{const ge=Array.from(ie.target.files||[]),we=[],Te=c.maxFileSizeMB*1024*1024;ge.forEach(de=>{var ue;if(de.size>Te){G.error(`"${de.name}" exceeds ${c.maxFileSizeMB}MB limit and was not added.`);return}const q=((ue=de.name.split(".").pop())==null?void 0:ue.toLowerCase())||"";if(!c.allowedFileTypes.includes(q)){G.error(`"${de.name}" has an unsupported file type and was not added.`);return}we.push(de)}),we.length>0&&N(de=>[...de,...we]),M.current&&(M.current.value="")},Y=()=>{j(ie=>[...ie,{id:Date.now().toString(),description:"",amount:0,gstRate:d||0,gstAmt:0,quantity:1,hsnCode:"",isService:!1,cgstRate:0,cgstAmt:0,sgstRate:0,sgstAmt:0,igstRate:0,igstAmt:0,utgstRate:0,utgstAmt:0,cessRate:0,cessAmt:0,totalAmt:0}])},ee=ie=>{f.length>1&&j(ge=>ge.filter(we=>we.id!==ie))},me=(ie,ge,we)=>{j(Te=>Te.map(de=>{if(de.id===ie){let q={...de,[ge]:we};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate"].includes(ge)){const ue=parseFloat(we);if(!isNaN(ue)&&ue<0)return G.error("Value cannot be negative"),de;const Pe=ge==="amount"?parseFloat(we)||0:de.amount,ve=1;let Ne=de.cgstRate,Ue=de.sgstRate,nt=de.utgstRate,ot=de.igstRate;if(ge==="cgstRate"){if(!g.isCGST)return de;Ne=parseFloat(we)||0,g.isUTGST?(nt=Ne,Ue=0):(Ue=Ne,nt=0),ot=0}else if(ge==="sgstRate"){if(!g.isSGST)return de;Ue=parseFloat(we)||0,Ne=Ue,nt=0,ot=0}else if(ge==="utgstRate"){if(!g.isUTGST)return de;nt=parseFloat(we)||0,Ne=nt,Ue=0,ot=0}else if(ge==="igstRate"){if(!g.isIGST)return de;ot=parseFloat(we)||0,Ne=0,Ue=0,nt=0}else if(ge==="gstRate"){const Mt=parseFloat(we)||0;g.isIGST?(ot=Mt,Ne=0,Ue=0,nt=0):(Ne=Mt/2,g.isUTGST?(nt=Mt/2,Ue=0):(Ue=Mt/2,nt=0),ot=0)}const Tt=y(Pe,{cgstRate:Ne,sgstRate:Ue,igstRate:ot,utgstRate:nt},ve);return{...q,amount:Pe,quantity:ve,...Tt}}return q}return de}))},Se=ie=>{N(ge=>ge.filter((we,Te)=>Te!==ie))},Je=async()=>{if(!B){G.error("Please fill all required fields");return}if(f.some(we=>we.amount<0)){G.error("Please ensure all amounts are non-negative");return}if(v==="days"&&(parseInt(I)<=0||isNaN(parseInt(I)))){G.error("Please enter a valid number of days greater than 0");return}let ge=S||"";if(v==="days"&&I){const we=parseInt(I),Te=new Date;Te.setDate(Te.getDate()+we),ge=Te.toISOString().split("T")[0]}try{if(F(!0),!b&&f.some(q=>q.description.trim()!==""&&q.amount>0&&(q.gstRate===0||!q.gstRate))&&!window.confirm(`One or more items have 0% GST. Are you sure you want to proceed? diff --git a/build/index.html b/build/index.html index ae5ae00..fc372df 100644 --- a/build/index.html +++ b/build/index.html @@ -13,7 +13,7 @@ - + diff --git a/src/validators/dealerClaim.validator.ts b/src/validators/dealerClaim.validator.ts index 0148912..1839fad 100644 --- a/src/validators/dealerClaim.validator.ts +++ b/src/validators/dealerClaim.validator.ts @@ -62,18 +62,18 @@ export const testSapBlockSchema = z.object({ export const costItemSchema = z.object({ description: z.string().min(1, 'Description is required'), - amount: z.number().min(0, 'Amount cannot be negative'), + amount: z.number().gt(0, 'Amount must be greater than zero'), quantity: z.number().min(1, 'Quantity must be at least 1').optional(), - totalAmt: z.number().min(0, 'Total amount cannot be negative').optional(), + totalAmt: z.number().gt(0, 'Total amount must be greater than zero').optional(), }).passthrough(); export const costBreakupSchema = z.array(costItemSchema); export const expenseItemSchema = z.object({ description: z.string().min(1, 'Description is required'), - amount: z.number().min(0, 'Amount cannot be negative'), + amount: z.number().gt(0, 'Amount must be greater than zero'), quantity: z.number().min(1, 'Quantity must be at least 1').optional(), - totalAmt: z.number().min(0, 'Total amount cannot be negative').optional(), + totalAmt: z.number().gt(0, 'Total amount must be greater than zero').optional(), }).passthrough(); export const closedExpensesSchema = z.array(expenseItemSchema);