From b76aa9b322ee61a54915d62f3a489e3e37308e4c Mon Sep 17 00:00:00 2001 From: laxman h Date: Thu, 26 Mar 2026 15:57:50 +0530 Subject: [PATCH] minor amount visibity change added --- ...{conclusionApi-CELRkQli.js => conclusionApi-ZgWYxicR.js} | 2 +- build/assets/{index-Cealtfd6.js => index-D9FSmDLr.js} | 6 +++--- build/index.html | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) rename build/assets/{conclusionApi-CELRkQli.js => conclusionApi-ZgWYxicR.js} (90%) rename build/assets/{index-Cealtfd6.js => index-D9FSmDLr.js} (92%) diff --git a/build/assets/conclusionApi-CELRkQli.js b/build/assets/conclusionApi-ZgWYxicR.js similarity index 90% rename from build/assets/conclusionApi-CELRkQli.js rename to build/assets/conclusionApi-ZgWYxicR.js index 6b53eb1..57cd78a 100644 --- a/build/assets/conclusionApi-CELRkQli.js +++ b/build/assets/conclusionApi-ZgWYxicR.js @@ -1 +1 @@ -import{a as s}from"./index-Cealtfd6.js";import"./radix-vendor-CLtqm-Ae.js";import"./charts-vendor-CmYZJIYl.js";import"./utils-vendor-BTBPSQfW.js";import"./ui-vendor-DgwXkk2Y.js";import"./socket-vendor-TjCxX7sJ.js";import"./redux-vendor-tbZCm13o.js";import"./router-vendor-HW_ujxKo.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-D9FSmDLr.js";import"./radix-vendor-CLtqm-Ae.js";import"./charts-vendor-CmYZJIYl.js";import"./utils-vendor-BTBPSQfW.js";import"./ui-vendor-DgwXkk2Y.js";import"./socket-vendor-TjCxX7sJ.js";import"./redux-vendor-tbZCm13o.js";import"./router-vendor-HW_ujxKo.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-Cealtfd6.js b/build/assets/index-D9FSmDLr.js similarity index 92% rename from build/assets/index-Cealtfd6.js rename to build/assets/index-D9FSmDLr.js index 2022368..c6990bf 100644 --- a/build/assets/index-Cealtfd6.js +++ b/build/assets/index-D9FSmDLr.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-CELRkQli.js","assets/radix-vendor-CLtqm-Ae.js","assets/charts-vendor-CmYZJIYl.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-DgwXkk2Y.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-HW_ujxKo.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-ZgWYxicR.js","assets/radix-vendor-CLtqm-Ae.js","assets/charts-vendor-CmYZJIYl.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-DgwXkk2Y.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-HW_ujxKo.js"])))=>i.map(i=>d[i]); var Of=Object.defineProperty;var $f=(t,s,a)=>s in t?Of(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var Fl=(t,s,a)=>$f(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as yh,R as vh,I as Nh,F as wh,a as Uf,T as Bf,P as Vf,C as zf,b as Hf,O as Ch,c as Sh,d as Gf,e as Wf,f as Yf,D as Kf,g as Qf,A as Xf,h as Jf,i as Zf,k as qf,l as eb,m as tb,n as sb,V as ab,o as rb,p as nb,q as ib,r as lb,s as ob,t as cb,u as db,v as mb,w as ub,x as xb,y as hb,z as pb,B as gb,E as fb,G as bb,H as jb,J as yb,K as vb,L as Nb,M as wb,N as Cb,Q as ic,U as lc,W as Sb,X as Ah,Y as Th,Z as kh,_ as Dh,$ as Ab,a0 as Tb,a1 as kb,a2 as Db,a3 as Rb,a4 as Fb,a5 as Ib,a6 as Pb,a7 as Eb,a8 as ln,a9 as xr,aa as Yn,ab as _b,ac as Mb,ad as Lb,ae as Ob}from"./radix-vendor-CLtqm-Ae.js";import{a as $b,r as x,d as Rh,e as on,B as To,C as Ui,X as Bi,Y as Vi,T as cn,L as zi,f as Pa,P as Fh,g as Ih,h as Ph,i as Ub,j as au,k as sl,l as al,b as Bb}from"./charts-vendor-CmYZJIYl.js";import{a as rl,f as Eh,s as da,e as oc,b as ru,c as Vb,d as La,g as Kn,i as cc,h as _h,j as qs,k as la,l as Il,m as Ya,n as zb,o as ko,p as Hb,q as et,r as Do,t as Gb,u as Wb,v as Yb,w as Kb,x as Pl,y as nu,z as Qb,A as Mh,B as Lh,C as dc,D as mc,E as Xb,F as Jb,G as Oh,H as Xr,I as El,J as Zb,K as qb,L as ej}from"./utils-vendor-BTBPSQfW.js";import{u as G,A as js,S as fs,C as Je,a as ps,L as ze,X as jt,H as tj,b as $h,U as zt,F as Re,c as Be,d as pn,R as _t,e as gn,f as Br,P as ms,g as sj,h as aj,B as Es,i as lr,j as _l,k as uc,l as Oa,m as nl,n as il,o as gt,p as $a,q as Pt,I as Vr,T as ts,r as rt,s as Fa,t as rj,v as ss,M as zs,w as ll,x as Bt,y as Ro,D as Tt,Z as ol,z as qt,E as nj,G as ij,J as lj,K as oj,N as cj,O as dj,Q as mj,V as uj,W as xj,Y as Uh,_ as hj,$ as pj,a0 as Bh,a1 as ya,a2 as ri,a3 as or,a4 as Hi,a5 as iu,a6 as ji,a7 as Gi,a8 as Vh,a9 as Ct,aa as gj,ab as Hs,ac as xc,ad as ws,ae as cl,af as zh,ag as vt,ah as fj,ai as bj,aj as Hh,ak as dl,al as Gh,am as jj,an as hc,ao as ys,ap as ka,aq as Wh,ar as ml,as as ul,at as Jt,au as yj,av as vj,aw as Yh,ax as Kh,ay as Di,az as nr,aA as pc,aB as xl,aC as Qn,aD as Qh,aE as Xh,aF as gc,aG as hl,aH as pl,aI as Fo,aJ as Nj,aK as Os,aL as Jh,aM as Wi,aN as wj,aO as Cj,aP as Sj,aQ as gl,aR as fl,aS as fc,aT as Aj,aU as lu,aV as Ua,aW as zr,aX as Tj,aY as en,aZ as ou,a_ as kj,a$ as Dj,b0 as Zh,b1 as cu,b2 as qh,b3 as Rj,b4 as Fj,b5 as Ij,b6 as Pj,b7 as ep,b8 as Ej,b9 as _j,ba as Mj,bb as bl,bc as Lj,bd as Oj,be as $j,bf as Uj}from"./ui-vendor-DgwXkk2Y.js";import{l as Bj}from"./socket-vendor-TjCxX7sJ.js";import{c as fn,a as Vj}from"./redux-vendor-tbZCm13o.js";import{u as Cs,a as Ba,b as tp,c as zj,B as Hj,R as Gj,d as kt,O as Wj}from"./router-vendor-HW_ujxKo.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 Io={},du=$b;Io.createRoot=du.createRoot,Io.hydrateRoot=du.hydrateRoot;var sp={exports:{}},ap={};var ni=x;function Yj(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var Kj=typeof Object.is=="function"?Object.is:Yj,Qj=ni.useSyncExternalStore,Xj=ni.useRef,Jj=ni.useEffect,Zj=ni.useMemo,qj=ni.useDebugValue;ap.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=Xj(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=Zj(function(){function c(h){if(!d){if(d=!0,m=h,h=r(h),n!==void 0&&l.hasValue){var g=l.value;if(n(g,h))return p=g}return p=h}if(g=p,Kj(m,h))return g;var b=r(h);return n!==void 0&&n(g,b)?(m=h,g):(m=h,p=b)}var d=!1,m,p,u=a===void 0?null:a;return[function(){return c(s())},u===null?void 0:function(){return c(u())}]},[s,a,r,n]);var o=Qj(t,i[0],i[1]);return Jj(function(){l.hasValue=!0,l.value=o},[o]),qj(o),o};sp.exports=ap;var ey=sp.exports;function ty(t){t()}function sy(){let t=null,s=null;return{clear(){t=null,s=null},notify(){ty(()=>{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 mu={notify(){},get:()=>[]};function ay(t,s){let a,r=mu,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 c(){g.onStateChange&&g.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=sy())}function p(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=mu)}function u(){i||(i=!0,m())}function h(){i&&(i=!1,p())}const g={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:c,isSubscribed:d,trySubscribe:u,tryUnsubscribe:h,getListeners:()=>r};return g}var ry=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",ny=ry(),iy=()=>typeof navigator<"u"&&navigator.product==="ReactNative",ly=iy(),oy=()=>ny||ly?x.useLayoutEffect:x.useEffect,cy=oy(),Ml=Symbol.for("react-redux-context"),Ll=typeof globalThis<"u"?globalThis:{};function dy(){if(!x.createContext)return{};const t=Ll[Ml]??(Ll[Ml]=new Map);let s=t.get(x.createContext);return s||(s=x.createContext(null),t.set(x.createContext,s)),s}var cr=dy();function my(t){const{children:s,context:a,serverState:r,store:n}=t,i=x.useMemo(()=>{const c=ay(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=x.useMemo(()=>n.getState(),[n]);cy(()=>{const{subscription:c}=i;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),l!==n.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[i,l]);const o=a||cr;return x.createElement(o.Provider,{value:i},s)}var uy=my;function bc(t=cr){return function(){return x.useContext(t)}}var rp=bc();function np(t=cr){const s=t===cr?rp:bc(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var xy=np();function hy(t=cr){const s=t===cr?xy:np(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var py=hy(),gy=(t,s)=>t===s;function fy(t=cr){const s=t===cr?rp:bc(t),a=(r,n={})=>{const{equalityFn:i=gy}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:c,getServerState:d}=l;x.useRef(!0);const m=x.useCallback({[r.name](u){return r(u)}}[r.name],[r]),p=ey.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return x.useDebugValue(p),p};return Object.assign(a,{withTypes:()=>a}),a}var by=fy(),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 jy(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 Yi=function(){return Yi=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(h,v):h(null)}}window.addEventListener("storage",j),m.addToWaiting(j);var y=setTimeout(j,Math.max(0,p-Date.now()))})];case 1:return u.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(u){return u!==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(u){switch(u.label){case 0:return[4,this.releaseLock__private__(p)];case 1:return[2,u.sent()]}})})},m.prototype.releaseLock__private__=function(p){return a(this,void 0,void 0,function(){var u,h,g,b;return r(this,function(f){switch(f.label){case 0:return u=this.storageHandler===void 0?l:this.storageHandler,h=i+"-"+p,(g=u.getItemSync(h))===null?[2]:(b=JSON.parse(g)).id!==this.id?[3,2]:[4,Sr.default().lock(b.iat)];case 1:f.sent(),this.acquiredIatSet.delete(b.iat),u.removeItemSync(h),Sr.default().unlock(b.iat),m.notifyWaiters(),f.label=2;case 2:return[2]}})})},m.lockCorrector=function(p){for(var u=Date.now()-5e3,h=p,g=[],b=0;;){var f=h.keySync(b);if(f===null)break;g.push(f),b++}for(var j=!1,y=0;y.")},Ny=Yi(Yi({},vy),{buildAuthorizeUrl:Xs,buildLogoutUrl:Xs,getAccessTokenSilently:Xs,getAccessTokenWithPopup:Xs,getIdTokenClaims:Xs,loginWithRedirect:Xs,loginWithPopup:Xs,connectAccountWithRedirect:Xs,logout:Xs,handleRedirectCallback:Xs,getDpopNonce:Xs,setDpopNonce:Xs,generateDpopProof:Xs,createFetcher:Xs}),wy=x.createContext(Ny);(function(t){jy(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 Cy=function(t){return t===void 0&&(t=wy),x.useContext(t)};const Ol="idToken",$l="userData",Sy=()=>!0;class at{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(Ol,s)}static getIdToken(){return sessionStorage.getItem(Ol)}static setUserData(s){localStorage.setItem($l,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem($l);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($l),sessionStorage.removeItem(Ol)}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 Sy()}static setAuthError(s){s?sessionStorage.setItem("__auth_error__",s):sessionStorage.removeItem("__auth_error__")}static getAuthError(){return sessionStorage.getItem("__auth_error__")}}function Ul(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,n,i;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){if(((i=(n=t.response)==null?void 0:n.data)==null?void 0:i.errorCode)==="SESSION_SUPERSEDED"){const l=at.getIdToken(),o=sessionStorage.getItem("auth_provider")||(l!=null&&l.includes("tanflow")?"tanflow":"okta");return at.setAuthError("SESSION_SUPERSEDED"),G.error("You have been logged out because an active session was detected from another device.",{duration:2e3,id:"session-superseded-toast"}),setTimeout(async()=>{sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),o==="tanflow"&&l?cp(l):dp(l||void 0)},1e3),Promise.reject(t)}if(!s._retry){s._retry=!0;const l=!0;try{const o=at.getRefreshToken(),c=await rl.post(`${vc}/auth/refresh`,l?{}:{refreshToken:o},{withCredentials:!0}),m=(c.data.data||c.data).accessToken;return be(s)}catch(o){return at.clearAll(),window.location.href="/",Promise.reject(o)}}}return Promise.reject(t)});async function ky(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 Dy(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 Ry(){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 Ln(){const s=(await be.get("/auth/me")).data;return s.data||s}async function Fy(){var t,s;try{await rl.post(`${vc}/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})}}let Nr=null;function Iy(){return"https://reflow-uat.royalenfield.com"}function $r(t){const s=Iy();return Nr||(Nr=Bj(s,{withCredentials:!0,transports:["websocket","polling"],path:"/socket.io",reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5}),Nr.on("connect",()=>{}),Nr.on("connect_error",a=>{console.error("[Socket] Connection error:",a.message)}),Nr.on("disconnect",a=>{}),Nr)}function Eo(t,s,a){a?t.emit("join:request",{requestId:s,userId:a}):t.emit("join:request",s)}function mp(t,s){t.emit("leave:request",s)}function Nc(t,s){t.emit("join:user",{userId:s})}const up=x.createContext(void 0);function Py({children:t}){const[s,a]=x.useState(!1),[r,n]=x.useState(!0),[i,l]=x.useState(null),[o,c]=x.useState(null),[d,m]=x.useState(!1);x.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(k){console.error("Error clearing storage:",k)}a(!1),l(null),n(!1),c(null);return}const S=new URLSearchParams(window.location.search),C=S.has("code"),E=sessionStorage.getItem("__logout_type__");if((S.has("logout")||S.has("okta_logged_out")||S.has("tanflow_logged_out")||E)&&!C){console.log("🚪 Logout parameter detected in URL, clearing all tokens and backend session"),Fy().catch(k=>console.warn("🚪 Final backend logout cleanup failed:",k)),at.clearAll(),sessionStorage.removeItem("__logout_type__"),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(k){console.warn("Could not set force reauth flag:",k)}window.history.replaceState({},document.title,"/");return}window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback"||(at.getUserData(),d?n(!1):u())},[d]),x.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]),x.useEffect(()=>{if(!s||!(i!=null&&i.userId))return;const v=$r();Nc(v,i.userId);const w=S=>{console.log("📡 [Socket] Session superseded event received:",S),at.setAuthError("SESSION_SUPERSEDED"),G.error("Session Expired",{description:"You have been logged out because another session was started on a different device.",duration:4e3,id:"session-superseded-socket"}),setTimeout(()=>{b()},1e3)};return v.on("SESSION_SUPERSEDED",w),()=>{v.off("SESSION_SUPERSEDED",w)}},[s,i==null?void 0:i.userId]);const p=x.useRef(!1);x.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;const C=sessionStorage.getItem("__logout_type__");if((w.has("logout")||w.has("tanflow_logged_out")||w.has("okta_logged_out")||C)&&!w.get("code")){console.log("🚪 Logout redirect detected in callback, redirecting to home");const N=new URLSearchParams;(w.has("tanflow_logged_out")||C==="tanflow")&&N.set("tanflow_logged_out","true"),(w.has("okta_logged_out")||C==="okta")&&N.set("okta_logged_out","true"),w.has("logout")&&N.set("logout",w.get("logout")||Date.now().toString());const O=N.toString()?`/?${N.toString()}`:"/?logout="+Date.now();window.location.replace(O);return}p.current=!0;const R=w.get("code"),k=w.get("error");if(window.history.replaceState({},document.title,"/login/callback"),k){c(new Error(`Authentication error: ${k}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!R){n(!1),sessionStorage.removeItem("auth_provider");return}try{n(!0),a(!1),c(null);const N=`${window.location.origin}/login/callback`,O=await Dy(R,N);l(O.user),a(!0),c(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(N){console.error("❌ Token exchange error in AuthContext:",N),c(N),a(!1),l(null),sessionStorage.removeItem("auth_provider"),p.current=!1}finally{n(!1)}})()},[]);const u=async()=>{var w;if(d){n(!1);return}const v=!0;try{if(n(!0),v){const E=at.getUserData();try{const R=await Ln();l(R),at.setUserData(R),a(!0)}catch(R){if(((w=R==null?void 0:R.response)==null?void 0:w.status)===401)try{await j();const k=await Ln();l(k),at.setUserData(k),a(!0)}catch{at.clearAll(),a(!1),l(null)}else R!=null&&R.isConnectionError?E?(l(E),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(Ul(S))try{await j();const E=at.getAccessToken();if(E&&!Ul(E)){const R=at.getUserData();if(R)l(R),a(!0);else try{const k=await Ln();l(k),at.setUserData(k),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 E=await Ln();l(E),at.setUserData(E),a(!0)}catch{at.clearAll(),a(!1),l(null)}}catch(S){console.error("Error checking auth status:",S),c(S),at.clearAll(),a(!1),l(null)}finally{n(!1)}},h=async()=>{try{c(null);const v="https://dev-830839.oktapreview.com",w="0oa2jgzvrpdwx2iqd0h8",S=`${window.location.origin}/login/callback`,C="code",E="openid profile email",R=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const k=new URLSearchParams(window.location.search),N=k.has("logout")||k.has("okta_logged_out")||k.has("tanflow_logged_out"),O=sessionStorage.getItem("__force_reauth_after_logout__")==="true",I=N||O;let B=`${v}/oauth2/default/v1/authorize?client_id=${w}&redirect_uri=${encodeURIComponent(S)}&response_type=${C}&scope=${encodeURIComponent(E)}&state=${R}`;I&&(B+="&prompt=login",sessionStorage.removeItem("__force_reauth_after_logout__")),window.location.href=B}catch(v){throw c(v),v}},g=async(v,w)=>{c(null),n(!0);try{const S=await ky(v,w);l(S.user),a(!0),window.history.replaceState({},document.title,"/")}catch(S){throw c(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),c(null),n(!0);const S=sessionStorage.getItem("__logout_in_progress__"),C=sessionStorage.getItem("__force_logout__"),E=sessionStorage.getItem("auth_provider");if(at.clearAll(),S&&sessionStorage.setItem("__logout_in_progress__",S),C&&sessionStorage.setItem("__force_logout__",C),v&&at.setIdToken(v),E&&sessionStorage.setItem("auth_provider",E),await new Promise(R=>setTimeout(R,100)),w==="tanflow"&&v){console.log("🚪 Initiating Tanflow logout...");try{cp(v);return}catch(R){console.error("🚪 Tanflow logout error:",R)}}console.log("🚪 Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),dp(v||void 0)}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&&!Ul(v))return v;try{return await j(),at.getAccessToken()}catch{return null}},j=async()=>{try{const w=await Ry();return}catch(w){throw at.clearAll(),a(!1),l(null),w}},y={isAuthenticated:s,isLoading:r,user:i,error:o,login:h,loginWithPassword:g,logout:b,getAccessTokenSilently:f,refreshTokenSilently:j};return e.jsx(up.Provider,{value:y,children:t})}function Ey({children:t}){return e.jsx(Py,{children:t})}function us(){const t=x.useContext(up);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function Ar(t){return(t==null?void 0:t.role)==="ADMIN"}function kn(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function jl(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const hu=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,pu=Rh,wc=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return pu(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,l=Object.keys(n).map(d=>{const m=a==null?void 0:a[d],p=i==null?void 0:i[d];if(m===null)return null;const u=hu(m)||hu(p);return n[d][u]}),o=a&&Object.entries(a).reduce((d,m)=>{let[p,u]=m;return u===void 0||(d[p]=u),d},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((d,m)=>{let{class:p,className:u,...h}=m;return Object.entries(h).every(g=>{let[b,f]=g;return Array.isArray(f)?f.includes({...i,...o}[b]):{...i,...o}[b]===f})?[...d,p,u]:d},[]);return pu(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},Cc="-",_y=t=>{const s=Ly(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(Cc);return o[0]===""&&o.length!==1&&o.shift(),xp(o,s)||My(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},xp=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?xp(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(Cc);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},gu=/^\[(.+)\]$/,My=t=>{if(gu.test(t)){const s=gu.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},Ly=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return $y(Object.entries(t.classGroups),a).forEach(([i,l])=>{_o(l,r,i,s)}),r},_o=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:fu(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(Oy(n)){_o(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{_o(l,fu(s,i),a,r)})})},fu=(t,s)=>{let a=t;return s.split(Cc).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},Oy=t=>t.isThemeGetter,$y=(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,Uy=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)}}},hp="!",By=t=>{const{separator:s,experimentalParseClassName:a}=t,r=s.length===1,n=s[0],i=s.length,l=o=>{const c=[];let d=0,m=0,p;for(let f=0;fm?p-m:void 0;return{modifiers:c,hasImportantModifier:h,baseClassName:g,maybePostfixModifierPosition:b}};return a?o=>a({className:o,parseClassName:l}):l},Vy=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},zy=t=>({cache:Uy(t.cacheSize),parseClassName:By(t),..._y(t)}),Hy=/\s+/,Gy=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(Hy);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:m,hasImportantModifier:p,baseClassName:u,maybePostfixModifierPosition:h}=a(d);let g=!!h,b=r(g?u.substring(0,h):u);if(!b){if(!g){o=d+(o.length>0?" "+o:o);continue}if(b=r(u),!b){o=d+(o.length>0?" "+o:o);continue}g=!1}const f=Vy(m).join(":"),j=p?f+hp: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 Wy(){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=zy(d),r=a.cache.get,n=a.cache.set,i=o,o(c)}function o(c){const d=r(c);if(d)return d;const m=Gy(c,a);return n(c,m),m}return function(){return i(Wy.apply(null,arguments))}}const Qt=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},gp=/^\[(?:([a-z-]+):)?(.+)\]$/i,Ky=/^\d+\/\d+$/,Qy=new Set(["px","full","screen"]),Xy=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Jy=/\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$/,Zy=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,qy=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ev=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ha=t=>dn(t)||Qy.has(t)||Ky.test(t),sr=t=>bn(t,"length",ov),dn=t=>!!t&&!Number.isNaN(Number(t)),Bl=t=>bn(t,"number",dn),Dn=t=>!!t&&Number.isInteger(Number(t)),tv=t=>t.endsWith("%")&&dn(t.slice(0,-1)),bt=t=>gp.test(t),ar=t=>Xy.test(t),sv=new Set(["length","size","percentage"]),av=t=>bn(t,sv,fp),rv=t=>bn(t,"position",fp),nv=new Set(["image","url"]),iv=t=>bn(t,nv,dv),lv=t=>bn(t,"",cv),Rn=()=>!0,bn=(t,s,a)=>{const r=gp.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},ov=t=>Jy.test(t)&&!Zy.test(t),fp=()=>!1,cv=t=>qy.test(t),dv=t=>ev.test(t),mv=()=>{const t=Qt("colors"),s=Qt("spacing"),a=Qt("blur"),r=Qt("brightness"),n=Qt("borderColor"),i=Qt("borderRadius"),l=Qt("borderSpacing"),o=Qt("borderWidth"),c=Qt("contrast"),d=Qt("grayscale"),m=Qt("hueRotate"),p=Qt("invert"),u=Qt("gap"),h=Qt("gradientColorStops"),g=Qt("gradientColorStopPositions"),b=Qt("inset"),f=Qt("margin"),j=Qt("opacity"),y=Qt("padding"),v=Qt("saturate"),w=Qt("scale"),S=Qt("sepia"),C=Qt("skew"),E=Qt("space"),R=Qt("translate"),k=()=>["auto","contain","none"],N=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto",bt,s],I=()=>[bt,s],B=()=>["",Ha,sr],T=()=>["auto",dn,bt],M=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],F=()=>["solid","dashed","dotted","double","none"],D=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],A=()=>["start","end","center","between","around","evenly","stretch"],H=()=>["","0",bt],$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],_=()=>[dn,bt];return{cacheSize:500,separator:":",theme:{colors:[Rn],spacing:[Ha,sr],blur:["none","",ar,bt],brightness:_(),borderColor:[t],borderRadius:["none","","full",ar,bt],borderSpacing:I(),borderWidth:B(),contrast:_(),grayscale:H(),hueRotate:_(),invert:H(),gap:I(),gradientColorStops:[t],gradientColorStopPositions:[tv,sr],inset:O(),margin:O(),opacity:_(),padding:I(),saturate:_(),scale:_(),sepia:H(),skew:_(),space:I(),translate:I()},classGroups:{aspect:[{aspect:["auto","square","video",bt]}],container:["container"],columns:[{columns:[ar]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...M(),bt]}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],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",Dn,bt]}],basis:[{basis:O()}],"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:H()}],shrink:[{shrink:H()}],order:[{order:["first","last","none",Dn,bt]}],"grid-cols":[{"grid-cols":[Rn]}],"col-start-end":[{col:["auto",{span:["full",Dn,bt]},bt]}],"col-start":[{"col-start":T()}],"col-end":[{"col-end":T()}],"grid-rows":[{"grid-rows":[Rn]}],"row-start-end":[{row:["auto",{span:[Dn,bt]},bt]}],"row-start":[{"row-start":T()}],"row-end":[{"row-end":T()}],"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:[u]}],"gap-x":[{"gap-x":[u]}],"gap-y":[{"gap-y":[u]}],"justify-content":[{justify:["normal",...A()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...A(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...A(),"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":[E]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[E]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",bt,s]}],"min-w":[{"min-w":[bt,s,"min","max","fit"]}],"max-w":[{"max-w":[bt,s,"none","full","min","max","fit","prose",{screen:[ar]},ar]}],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",ar,sr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Bl]}],"font-family":[{font:[Rn]}],"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",dn,Bl]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Ha,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:[...F(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Ha,sr]}],"underline-offset":[{"underline-offset":["auto",Ha,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:I()}],"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:[...M(),rv]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",av]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},iv]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[h]}],"gradient-via":[{via:[h]}],"gradient-to":[{to:[h]}],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:[...F(),"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:F()}],"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:["",...F()]}],"outline-offset":[{"outline-offset":[Ha,bt]}],"outline-w":[{outline:[Ha,sr]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:B()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[Ha,sr]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",ar,lv]}],"shadow-color":[{shadow:[Rn]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...D(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":D()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",ar,bt]}],grayscale:[{grayscale:[d]}],"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":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[j]}],"backdrop-saturate":[{"backdrop-saturate":[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:_()}],ease:[{ease:["linear","in","out","in-out",bt]}],delay:[{delay:_()}],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:[Dn,bt]}],"translate-x":[{"translate-x":[R]}],"translate-y":[{"translate-y":[R]}],"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":I()}],"scroll-mx":[{"scroll-mx":I()}],"scroll-my":[{"scroll-my":I()}],"scroll-ms":[{"scroll-ms":I()}],"scroll-me":[{"scroll-me":I()}],"scroll-mt":[{"scroll-mt":I()}],"scroll-mr":[{"scroll-mr":I()}],"scroll-mb":[{"scroll-mb":I()}],"scroll-ml":[{"scroll-ml":I()}],"scroll-p":[{"scroll-p":I()}],"scroll-px":[{"scroll-px":I()}],"scroll-py":[{"scroll-py":I()}],"scroll-ps":[{"scroll-ps":I()}],"scroll-pe":[{"scroll-pe":I()}],"scroll-pt":[{"scroll-pt":I()}],"scroll-pr":[{"scroll-pr":I()}],"scroll-pb":[{"scroll-pb":I()}],"scroll-pl":[{"scroll-pl":I()}],"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:[Ha,sr,Bl]}],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"]}}},uv=Yy(mv);function Me(...t){return uv(Rh(t))}const Xn=wc("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"}}),P=x.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?yh:"button";return e.jsx(l,{"data-slot":"button",className:Me(Xn({variant:s,size:a,className:t})),ref:i,...n})});P.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 ie({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 le({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 yl="/assets/Re_Logo-By51taPS.png",bu="/assets/landing_page_image-ClTD-4qZ.jpg";function xv(){var p,u;const{login:t,isLoading:s,error:a}=us(),[r,n]=x.useState(!1),[i,l]=x.useState(null),[o,c]=x.useState(!1);x.useEffect(()=>{const h=new Image;h.src=bu,h.onload=()=>c(!0),h.complete&&c(!0)},[]);const d=async()=>{const h=sessionStorage.getItem("__force_reauth_after_logout__");localStorage.clear(),sessionStorage.clear(),h&&sessionStorage.setItem("__force_reauth_after_logout__",h);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{Ay()}catch(h){const g=h instanceof Error?h.message:"Dealer login failed. Check console for details.";console.error("TANFLOW LOGIN ERROR",h),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(${bu})`:"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(ie,{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:yl,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"))||((u=a.message)==null?void 0:u.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(P,{onClick:d,disabled:s||r,className:"w-full h-12 bg-re-red hover:bg-re-red/90 text-white font-semibold text-base border-0",size:"lg",children:s?e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-white border-t-transparent"}):e.jsxs(e.Fragment,{children:[e.jsx(js,{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(P,{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(fs,{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 bp(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=us(),[n,i]=x.useState("exchanging");x.useEffect(()=>{if(a){i("error");return}if(s){const c=new URLSearchParams(window.location.search).get("code");i(c&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else 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:yl,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(Je,{className:"w-16 h-16 text-red-500"})}),e.jsx(Je,{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(ps,{className:"w-16 h-16 text-green-500"})}),e.jsx(ps,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(ze,{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 Of=Object.defineProperty;var $f=(t,s,a)=>s in t?Of(t,s,{enumerable:!0,config ${g}px !important; top: ${p}px !important; } - `),()=>{f.contains(b)&&f.removeChild(b)}},[s]),e.jsx(z2,{isPresent:s,childRef:i,sizeRef:l,children:x.cloneElement(t,{ref:c})})}const G2=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=Lc(W2),m=x.useId();let p=!0,u=x.useMemo(()=>(p=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:h=>{d.set(h,!0);for(const g of d.values())if(!g)return;r&&r()},register:h=>(d.set(h,!1),()=>d.delete(h))}),[a,d,r]);return i&&p&&(u={...u}),x.useMemo(()=>{d.forEach((h,g)=>d.set(g,!1))},[a]),x.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(H2,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(wl.Provider,{value:u,children:t})};function W2(){return new Map}function Qg(t=!0){const s=x.useContext(wl);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=x.useId();x.useEffect(()=>{if(t)return n(i)},[t]);const l=x.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const wi=t=>t.key||"";function qu(t){const s=[];return x.Children.forEach(t,a=>{x.isValidElement(a)&&s.push(a)}),s}const Cl=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",root:c})=>{const[d,m]=Qg(l),p=x.useMemo(()=>qu(t),[t]),u=l&&!d?[]:p.map(wi),h=x.useRef(!0),g=x.useRef(p),b=Lc(()=>new Map),[f,j]=x.useState(p),[y,v]=x.useState(p);rg(()=>{h.current=!1,g.current=p;for(let C=0;C{const E=wi(C),R=l&&!d?!1:p===y||u.includes(E),k=()=>{if(b.has(E))b.set(E,!0);else return;let N=!0;b.forEach(O=>{O||(N=!1)}),N&&(S==null||S(),v(g.current),l&&(m==null||m()),r&&r())};return e.jsx(G2,{isPresent:R,initial:!h.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:R?void 0:k,anchorX:o,children:C},E)})})},Xg=x.createContext({strict:!1}),ex={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"]},hn={};for(const t in ex)hn[t]={isEnabled:s=>ex[t].some(a=>!!s[a])};function Y2(t){for(const s in t)hn[s]={...hn[s],...t[s]}}const K2=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 Zi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||K2.has(t)}let Jg=t=>!Zi(t);function Q2(t){typeof t=="function"&&(Jg=s=>s.startsWith("on")?!Zi(s):t(s))}try{Q2(require("@emotion/is-prop-valid").default)}catch{}function X2(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(Jg(n)||a===!0&&Zi(n)||!s&&!Zi(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Sl=x.createContext({});function Al(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function ei(t){return typeof t=="string"||Array.isArray(t)}const ld=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],od=["initial",...ld];function Tl(t){return Al(t.animate)||od.some(s=>ei(t[s]))}function Zg(t){return!!(Tl(t)||t.variants)}function J2(t,s){if(Tl(t)){const{initial:a,animate:r}=t;return{initial:a===!1||ei(a)?a:void 0,animate:ei(r)?r:void 0}}return t.inherit!==!1?s:{}}function Z2(t){const{initial:s,animate:a}=J2(t,x.useContext(Sl));return x.useMemo(()=>({initial:s,animate:a}),[tx(s),tx(a)])}function tx(t){return Array.isArray(t)?t.join(" "):t}const ti={};function q2(t){for(const s in t)ti[s]=t[s],Wc(s)&&(ti[s].isCSSVariable=!0)}function qg(t,{layout:s,layoutId:a}){return wn.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!ti[t]||t==="opacity")}const eS={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},tS=Nn.length;function sS(t,s,a){let r="",n=!0;for(let i=0;i({style:{},transform:{},transformOrigin:{},vars:{}});function e0(t,s,a){for(const r in s)!Ls(s[r])&&!qg(r,a)&&(t[r]=s[r])}function aS({transformTemplate:t},s){return x.useMemo(()=>{const a=dd();return cd(a,s,t),Object.assign({},a.vars,a.style)},[s])}function rS(t,s){const a=t.style||{},r={};return e0(r,a,t),Object.assign(r,aS(t,s)),r}function nS(t,s){const a={},r=rS(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 iS={offset:"stroke-dashoffset",array:"stroke-dasharray"},lS={offset:"strokeDashoffset",array:"strokeDasharray"};function oS(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?iS:lS;t[i.offset]=ot.transform(-r);const l=ot.transform(s),o=ot.transform(a);t[i.array]=`${l} ${o}`}function t0(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(cd(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:p,style:u}=t;p.transform&&(u.transform=p.transform,delete p.transform),(u.transform||p.transformOrigin)&&(u.transformOrigin=p.transformOrigin??"50% 50%",delete p.transformOrigin),u.transform&&(u.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&&oS(p,n,i,l,!1)}const s0=()=>({...dd(),attrs:{}}),a0=t=>typeof t=="string"&&t.toLowerCase()==="svg";function cS(t,s,a,r){const n=x.useMemo(()=>{const i=s0();return t0(i,s,a0(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};e0(i,t.style,t),n.style={...i,...n.style}}return n}const dS=["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 md(t){return typeof t!="string"||t.includes("-")?!1:!!(dS.indexOf(t)>-1||/[A-Z]/u.test(t))}function mS(t,s,a,{latestValues:r},n,i=!1){const o=(md(t)?cS:nS)(s,r,n,t),c=X2(s,typeof t=="string",i),d=t!==x.Fragment?{...c,...o,ref:a}:{},{children:m}=s,p=x.useMemo(()=>Ls(m)?m.get():m,[m]);return x.createElement(t,{...d,children:p})}function sx(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function ud(t,s,a,r){if(typeof s=="function"){const[n,i]=sx(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]=sx(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Li(t){return Ls(t)?t.get():t}function uS({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:xS(a,r,n,t),renderState:s()}}function xS(t,s,a,r){const n={},i=r(t,{});for(const u in i)n[u]=Li(i[u]);let{initial:l,animate:o}=t;const c=Tl(t),d=Zg(t);s&&d&&!c&&t.inherit!==!1&&(l===void 0&&(l=s.initial),o===void 0&&(o=s.animate));let m=a?a.initial===!1:!1;m=m||l===!1;const p=m?o:l;if(p&&typeof p!="boolean"&&!Al(p)){const u=Array.isArray(p)?p:[p];for(let h=0;h(s,a)=>{const r=x.useContext(Sl),n=x.useContext(wl),i=()=>uS(t,s,r,n);return a?i():Lc(i)};function xd(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(Ls(r[l])||s.style&&Ls(s.style[l])||qg(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const hS=r0({scrapeMotionValuesFromProps:xd,createRenderState:dd});function n0(t,s,a){const r=xd(t,s,a);for(const n in t)if(Ls(t[n])||Ls(s[n])){const i=Nn.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const pS=r0({scrapeMotionValuesFromProps:n0,createRenderState:s0}),gS=Symbol.for("motionComponentSymbol");function sn(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function fS(t,s,a){return x.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):sn(a)&&(a.current=r))},[s])}const hd=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),bS="framerAppearId",i0="data-"+hd(bS),l0=x.createContext({});function jS(t,s,a,r,n){var b,f;const{visualElement:i}=x.useContext(Sl),l=x.useContext(Xg),o=x.useContext(wl),c=x.useContext(id).reducedMotion,d=x.useRef(null);r=r||l.renderer,!d.current&&r&&(d.current=r(t,{visualState:s,parent:i,props:a,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:c}));const m=d.current,p=x.useContext(l0);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&yS(d.current,a,n,p);const u=x.useRef(!1);x.useInsertionEffect(()=>{m&&u.current&&m.update(a,o)});const h=a[i0],g=x.useRef(!!h&&!((b=window.MotionHandoffIsComplete)!=null&&b.call(window,h))&&((f=window.MotionHasOptimisedAnimation)==null?void 0:f.call(window,h)));return rg(()=>{m&&(u.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),x.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var j;(j=window.MotionHandoffMarkAsComplete)==null||j.call(window,h)}),g.current=!1),m.enteringChildren=void 0)}),m}function yS(t,s,a,r){const{layoutId:n,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:o0(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&sn(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function o0(t){if(t)return t.options.allowProjection!==!1?t.projection:o0(t.parent)}function eo(t,{forwardMotionProps:s=!1}={},a,r){a&&Y2(a);const n=md(t)?pS:hS;function i(o,c){let d;const m={...x.useContext(id),...o,layoutId:vS(o)},{isStatic:p}=m,u=Z2(o),h=n(o,p);if(!p&&Oc){NS();const g=wS(m);d=g.MeasureLayout,u.visualElement=jS(t,h,m,r,g.ProjectionNode)}return e.jsxs(Sl.Provider,{value:u,children:[d&&u.visualElement?e.jsx(d,{visualElement:u.visualElement,...m}):null,mS(t,o,fS(h,u.visualElement,c),h,p,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=x.forwardRef(i);return l[gS]=t,l}function vS({layoutId:t}){const s=x.useContext(Mc).id;return s&&t!==void 0?s+"-"+t:t}function NS(t,s){x.useContext(Xg).strict}function wS(t){const{drag:s,layout:a}=hn;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 CS(t,s){if(typeof Proxy>"u")return eo;const a=new Map,r=(i,l)=>eo(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,eo(l,void 0,t,s)),a.get(l))})}function c0({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function SS({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function AS(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 to(t){return t===void 0||t===1}function Qo({scale:t,scaleX:s,scaleY:a}){return!to(t)||!to(s)||!to(a)}function kr(t){return Qo(t)||d0(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function d0(t){return ax(t.x)||ax(t.y)}function ax(t){return t&&t!=="0%"}function qi(t,s,a){const r=t-a,n=s*r;return a+n}function rx(t,s,a,r,n){return n!==void 0&&(t=qi(t,n,r)),qi(t,a,r)+s}function Xo(t,s=0,a=1,r,n){t.min=rx(t.min,s,a,r,n),t.max=rx(t.max,s,a,r,n)}function m0(t,{x:s,y:a}){Xo(t.x,s.translate,s.scale,s.originPoint),Xo(t.y,a.translate,a.scale,a.originPoint)}const nx=.999999999999,ix=1.0000000000001;function TS(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,l;for(let o=0;onx&&(s.x=1),s.ynx&&(s.y=1)}function an(t,s){t.min=t.min+s,t.max=t.max+s}function lx(t,s,a,r,n=.5){const i=ns(t.min,t.max,n);Xo(t,s,a,i,r)}function rn(t,s){lx(t.x,s.x,s.scaleX,s.scale,s.originX),lx(t.y,s.y,s.scaleY,s.scale,s.originY)}function u0(t,s){return c0(AS(t.getBoundingClientRect(),s))}function kS(t,s,a){const r=u0(t,a),{scroll:n}=s;return n&&(an(r.x,n.offset.x),an(r.y,n.offset.y)),r}const ox=()=>({translate:0,scale:1,origin:0,originPoint:0}),nn=()=>({x:ox(),y:ox()}),cx=()=>({min:0,max:0}),hs=()=>({x:cx(),y:cx()}),Jo={current:null},x0={current:!1};function DS(){if(x0.current=!0,!!Oc)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>Jo.current=t.matches;t.addEventListener("change",s),s()}else Jo.current=!1}const RS=new WeakMap;function FS(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,xn(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,xn(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const dx=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class IS{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=td,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 u=ta.now();this.renderScheduledAtthis.bindToMotionValue(n,r)),x0.current||DS(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Jo.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),dr(this.notifyUpdate),dr(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=wn.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&es.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 hn){const a=hn[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):hs()}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=xn(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"&&(ng(r)||lg(r))?r=parseFloat(r):!U2(r)&&mr.test(a)&&(r=Vg(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=ud(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 zc),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){rd.render(this.render)}}class h0 extends IS{constructor(){super(...arguments),this.KeyframeResolver=k2}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 p0(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 PS(t){return window.getComputedStyle(t)}class ES extends h0{constructor(){super(...arguments),this.type="html",this.renderInstance=p0}readValueFromInstance(s,a){var r;if(wn.has(a))return(r=this.projection)!=null&&r.isProjecting?Vo(a):YC(s,a);{const n=PS(s),i=(Wc(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return u0(s,a)}build(s,a,r){cd(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return xd(s,a,r)}}const g0=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 _S(t,s,a,r){p0(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(g0.has(n)?n:hd(n),s.attrs[n])}class MS extends h0{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=hs}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(wn.has(a)){const r=Bg(a);return r&&r.default||0}return a=g0.has(a)?a:hd(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return n0(s,a,r)}build(s,a,r){t0(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){_S(s,a,r,n)}mount(s){this.isSVGTag=a0(s.tagName),super.mount(s)}}const LS=(t,s)=>md(t)?new MS(s):new ES(s,{allowProjection:t!==x.Fragment});function un(t,s,a){const r=t.getProps();return ud(r,s,a!==void 0?a:r.custom,t)}const Zo=t=>Array.isArray(t);function OS(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,xn(a))}function $S(t){return Zo(t)?t[t.length-1]||0:t}function US(t,s){const a=un(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=$S(i[l]);OS(t,l,o)}}function BS(t){return!!(Ls(t)&&t.add)}function qo(t,s){const a=t.getValue("willChange");if(BS(a))return a.add(s);if(!a&&Qa.WillChange){const r=new Qa.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function f0(t){return t.props[i0]}const VS=t=>t!==null;function zS(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(VS),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const HS={type:"spring",stiffness:500,damping:25,restSpeed:10},GS=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),WS={type:"keyframes",duration:.8},YS={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},KS=(t,{keyframes:s})=>s.length>2?WS:wn.has(t)?t.startsWith("scale")?GS(s[1]):HS:YS;function QS({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:l,repeatDelay:o,from:c,elapsed:d,...m}){return!!Object.keys(m).length}const pd=(t,s,a,r={},n,i)=>l=>{const o=sd(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-_a(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-d,onUpdate:u=>{s.set(u),o.onUpdate&&o.onUpdate(u)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:t,motionValue:s,element:i?void 0:n};QS(o)||Object.assign(m,KS(t,m)),m.duration&&(m.duration=_a(m.duration)),m.repeatDelay&&(m.repeatDelay=_a(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let p=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(Yo(m),m.delay===0&&(p=!0)),(Qa.instantAnimations||Qa.skipAnimations)&&(p=!0,Yo(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,p&&!i&&s.get()!==void 0){const u=zS(m.keyframes,o);if(u!==void 0){es.update(()=>{m.onUpdate(u),m.onComplete()});return}}return o.isSync?new ed(m):new g2(m)};function XS({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function b0(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in o){const p=t.getValue(m,t.latestValues[m]??null),u=o[m];if(u===void 0||d&&XS(d,m))continue;const h={delay:a,...sd(i||{},m)},g=p.get();if(g!==void 0&&!p.isAnimating&&!Array.isArray(u)&&u===g&&!h.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const j=f0(t);if(j){const y=window.MotionHandoffAnimation(j,m,es);y!==null&&(h.startTime=y,b=!0)}}qo(t,m),p.start(pd(m,p,u,t.shouldReduceMotion&&Og.has(m)?{type:!1}:h,t,b));const f=p.animation;f&&c.push(f)}return l&&Promise.all(c).then(()=>{es.update(()=>{l&&US(t,l)})}),c}function j0(t,s,a,r=0,n=1){const i=Array.from(t).sort((d,m)=>d.sortNodePosition(m)).indexOf(s),l=t.size,o=(l-1)*r;return typeof a=="function"?a(i,l):n===1?i*r:o-i*r}function ec(t,s,a={}){var c;const r=un(t,s,a.type==="exit"?(c=t.presenceContext)==null?void 0:c.custom:void 0);let{transition:n=t.getDefaultTransition()||{}}=r||{};a.transitionOverride&&(n=a.transitionOverride);const i=r?()=>Promise.all(b0(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:p,staggerDirection:u}=n;return JS(t,s,d,m,p,u,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[d,m]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function JS(t,s,a=0,r=0,n=0,i=1,l){const o=[];for(const c of t.variantChildren)c.notify("AnimationStart",s),o.push(ec(c,s,{...l,delay:a+(typeof r=="function"?0:r)+j0(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function ZS(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>ec(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=ec(t,s,a);else{const n=typeof s=="function"?un(t,s,a.custom):s;r=Promise.all(b0(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function y0(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})=>ZS(t,a,r)))}function aA(t){let s=sA(t),a=mx(),r=!0;const n=c=>(d,m)=>{var u;const p=un(t,m,c==="exit"?(u=t.presenceContext)==null?void 0:u.custom:void 0);if(p){const{transition:h,transitionEnd:g,...b}=p;d={...d,...b,...g}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=v0(t.parent)||{},p=[],u=new Set;let h={},g=1/0;for(let f=0;fg&&w,k=!1;const N=Array.isArray(v)?v:[v];let O=N.reduce(n(j),{});S===!1&&(O={});const{prevResolvedValues:I={}}=y,B={...I,...O},T=D=>{R=!0,u.has(D)&&(k=!0,u.delete(D)),y.needsAnimating[D]=!0;const A=t.getValue(D);A&&(A.liveStyle=!1)};for(const D in B){const A=O[D],H=I[D];if(h.hasOwnProperty(D))continue;let $=!1;Zo(A)&&Zo(H)?$=!y0(A,H):$=A!==H,$?A!=null?T(D):u.add(D):A!==void 0&&u.has(D)?T(D):y.protectedKeys[D]=!0}y.prevProp=v,y.prevResolvedValues=O,y.isActive&&(h={...h,...O}),r&&t.blockInitialAnimation&&(R=!1);const M=C&&E;R&&(!M||k)&&p.push(...N.map(D=>{const A={type:j};if(typeof D=="string"&&r&&!M&&t.manuallyAnimateOnMount&&t.parent){const{parent:H}=t,$=un(H,D);if(H.enteringChildren&&$){const{delayChildren:_}=$.transition||{};A.delay=j0(H.enteringChildren,t,_)}}return{animation:D,options:A}}))}if(u.size){const f={};if(typeof d.initial!="boolean"){const j=un(t,Array.isArray(d.initial)?d.initial[0]:d.initial);j&&j.transition&&(f.transition=j.transition)}u.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&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(b=!1),r=!1,b?s(p):Promise.resolve()}function o(c,d){var p;if(a[c].isActive===d)return Promise.resolve();(p=t.variantChildren)==null||p.forEach(u=>{var h;return(h=u.animationState)==null?void 0:h.setActive(c,d)}),a[c].isActive=d;const m=l(c);for(const u in a)a[u].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=mx()}}}function rA(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!y0(s,t):!1}function Cr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function mx(){return{animate:Cr(!0),whileInView:Cr(),whileHover:Cr(),whileTap:Cr(),whileDrag:Cr(),whileFocus:Cr(),exit:Cr()}}class hr{constructor(s){this.isMounted=!1,this.node=s}update(){}}class nA extends hr{constructor(s){super(s),s.animationState||(s.animationState=aA(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Al(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 iA=0;class lA extends hr{constructor(){super(...arguments),this.id=iA++}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 oA={animation:{Feature:nA},exit:{Feature:lA}};function si(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function hi(t){return{point:{x:t.pageX,y:t.pageY}}}const cA=t=>s=>nd(s)&&t(s,hi(s));function Hn(t,s,a,r){return si(t,s,cA(a),r)}const N0=1e-4,dA=1-N0,mA=1+N0,w0=.01,uA=0-w0,xA=0+w0;function Vs(t){return t.max-t.min}function hA(t,s,a){return Math.abs(t-s)<=a}function ux(t,s,a,r=.5){t.origin=r,t.originPoint=ns(s.min,s.max,t.origin),t.scale=Vs(a)/Vs(s),t.translate=ns(a.min,a.max,t.origin)-t.originPoint,(t.scale>=dA&&t.scale<=mA||isNaN(t.scale))&&(t.scale=1),(t.translate>=uA&&t.translate<=xA||isNaN(t.translate))&&(t.translate=0)}function Gn(t,s,a,r){ux(t.x,s.x,a.x,r?r.originX:void 0),ux(t.y,s.y,a.y,r?r.originY:void 0)}function xx(t,s,a){t.min=a.min+s.min,t.max=t.min+Vs(s)}function pA(t,s,a){xx(t.x,s.x,a.x),xx(t.y,s.y,a.y)}function hx(t,s,a){t.min=s.min-a.min,t.max=t.min+Vs(s)}function Wn(t,s,a){hx(t.x,s.x,a.x),hx(t.y,s.y,a.y)}function pa(t){return[t("x"),t("y")]}const C0=({current:t})=>t?t.ownerDocument.defaultView:null,px=(t,s)=>Math.abs(t-s);function gA(t,s){const a=px(t.x,s.x),r=px(t.y,s.y);return Math.sqrt(a**2+r**2)}class S0{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 u=ao(this.lastMoveEventInfo,this.history),h=this.startEvent!==null,g=gA(u.offset,{x:0,y:0})>=this.distanceThreshold;if(!h&&!g)return;const{point:b}=u,{timestamp:f}=Fs;this.history.push({...b,timestamp:f});const{onStart:j,onMove:y}=this.handlers;h||(j&&j(this.lastMoveEvent,u),this.startEvent=this.lastMoveEvent),y&&y(this.lastMoveEvent,u)},this.handlePointerMove=(u,h)=>{this.lastMoveEvent=u,this.lastMoveEventInfo=so(h,this.transformPagePoint),es.update(this.updatePoint,!0)},this.handlePointerUp=(u,h)=>{this.end();const{onEnd:g,onSessionEnd:b,resumeAnimation:f}=this.handlers;if(this.dragSnapToOrigin&&f&&f(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const j=ao(u.type==="pointercancel"?this.lastMoveEventInfo:so(h,this.transformPagePoint),this.history);this.startEvent&&g&&g(u,j),b&&b(u,j)},!nd(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=hi(s),c=so(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=Fs;this.history=[{...d,timestamp:m}];const{onSessionStart:p}=a;p&&p(s,ao(c,this.history)),this.removeListeners=mi(Hn(this.contextWindow,"pointermove",this.handlePointerMove),Hn(this.contextWindow,"pointerup",this.handlePointerUp),Hn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),dr(this.updatePoint)}}function so(t,s){return s?{point:s(t.point)}:t}function gx(t,s){return{x:t.x-s.x,y:t.y-s.y}}function ao({point:t},s){return{point:t,delta:gx(t,A0(s)),offset:gx(t,fA(s)),velocity:bA(s,.1)}}function fA(t){return t[0]}function A0(t){return t[t.length-1]}function bA(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=A0(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>_a(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 jA(t,{min:s,max:a},r){return s!==void 0&&ta&&(t=r?ns(a,t,r.max):Math.min(t,a)),t}function fx(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 yA(t,{top:s,left:a,bottom:r,right:n}){return{x:fx(t.x,a,n),y:fx(t.y,s,r)}}function bx(t,s){let a=s.min-t.min,r=s.max-t.max;return s.max-s.minr?a=Jn(s.min,s.max-r,t.min):r>n&&(a=Jn(t.min,t.max-n,s.min)),Ka(0,1,a)}function wA(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 tc=.35;function CA(t=tc){return t===!1?t=0:t===!0&&(t=tc),{x:jx(t,"left","right"),y:jx(t,"top","bottom")}}function jx(t,s,a){return{min:yx(t,s),max:yx(t,a)}}function yx(t,s){return typeof t=="number"?t:t[s]||0}const SA=new WeakMap;class AA{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=hs(),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:u}=this.getProps();u?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(hi(p).point)},l=(p,u)=>{const{drag:h,dragPropagation:g,onDragStart:b}=this.getProps();if(h&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=I2(h),!this.openDragLock))return;this.latestPointerEvent=p,this.latestPanInfo=u,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(Ma.test(y)){const{projection:v}=this.visualElement;if(v&&v.layout){const w=v.layout.layoutBox[j];w&&(y=Vs(w)*(parseFloat(y)/100))}}this.originPoint[j]=y}),b&&es.postRender(()=>b(p,u)),qo(this.visualElement,"transform");const{animationState:f}=this.visualElement;f&&f.setActive("whileDrag",!0)},o=(p,u)=>{this.latestPointerEvent=p,this.latestPanInfo=u;const{dragPropagation:h,dragDirectionLock:g,onDirectionLock:b,onDrag:f}=this.getProps();if(!h&&!this.openDragLock)return;const{offset:j}=u;if(g&&this.currentDirection===null){this.currentDirection=TA(j),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",u.point,j),this.updateAxis("y",u.point,j),this.visualElement.render(),f&&f(p,u)},c=(p,u)=>{this.latestPointerEvent=p,this.latestPanInfo=u,this.stop(p,u),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>pa(p=>{var u;return this.getAnimationState(p)==="paused"&&((u=this.getAxisMotionValue(p).animation)==null?void 0:u.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new S0(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:C0(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&&es.postRender(()=>o(r,n))}cancel(){this.isDragging=!1;const{projection:s,animationState:a}=this.visualElement;s&&(s.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),a&&a.setActive("whileDrag",!1)}updateAxis(s,a,r){const{drag:n}=this.getProps();if(!r||!Ci(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=jA(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&&sn(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=yA(r.layoutBox,s):this.constraints=!1,this.elastic=CA(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&pa(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=wA(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!sn(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=kS(r,n.root,this.visualElement.getTransformPagePoint());let l=vA(n.layout.layoutBox,i);if(a){const o=a(SS(l));this.hasMutatedConstraints=!!o,o&&(l=c0(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=pa(m=>{if(!Ci(m,a,this.currentDirection))return;let p=c&&c[m]||{};l&&(p={min:0,max:0});const u=n?200:1e6,h=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:u,bounceDamping:h,timeConstant:750,restDelta:1,restSpeed:10,...i,...p};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return qo(this.visualElement,s),r.start(pd(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(!Ci(a,r,this.currentDirection))return;const{projection:n}=this.visualElement,i=this.getAxisMotionValue(a);if(n&&n.layout){const{min:l,max:o}=n.layout.layoutBox[a];i.set(s[a]-ns(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!sn(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 c=o.get();n[l]=NA({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),pa(l=>{if(!Ci(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(ns(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;SA.set(this.visualElement,this);const s=this.visualElement.current,a=Hn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();sn(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,i=n.addEventListener("measure",r);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),es.read(r);const l=si(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(pa(m=>{const p=this.getAxisMotionValue(m);p&&(this.originPoint[m]+=c[m].translate,p.set(p.get()+c[m].translate))}),this.visualElement.render())});return()=>{l(),a(),i(),o&&o()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:l=tc,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Ci(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function TA(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class kA extends hr{constructor(s){super(s),this.removeGroupControls=ba,this.removeListeners=ba,this.controls=new AA(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ba}unmount(){this.removeGroupControls(),this.removeListeners()}}const vx=t=>(s,a)=>{t&&es.postRender(()=>t(s,a))};class DA extends hr{constructor(){super(...arguments),this.removePointerDownListener=ba}onPointerDown(s){this.session=new S0(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:C0(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:vx(s),onStart:vx(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&es.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=Hn(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 Oi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Nx(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const Fn={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(ot.test(t))t=parseFloat(t);else return t;const a=Nx(t,s.target.x),r=Nx(t,s.target.y);return`${a}% ${r}%`}},RA={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=mr.parse(t);if(n.length>5)return r;const i=mr.createTransformer(t),l=typeof n[0]!="number"?1:0,o=a.x.scale*s.x,c=a.y.scale*s.y;n[0+l]/=o,n[1+l]/=c;const d=ns(o,c,.5);return typeof n[2+l]=="number"&&(n[2+l]/=d),typeof n[3+l]=="number"&&(n[3+l]/=d),i(n)}};let ro=!1;class FA extends x.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;q2(IA),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),ro&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Oi.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,ro=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||es.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),rd.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;ro=!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 T0(t){const[s,a]=Qg(),r=x.useContext(Mc);return e.jsx(FA,{...t,layoutGroup:r,switchLayoutGroup:x.useContext(l0),isPresent:s,safeToRemove:a})}const IA={borderRadius:{...Fn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Fn,borderTopRightRadius:Fn,borderBottomLeftRadius:Fn,borderBottomRightRadius:Fn,boxShadow:RA};function PA(t,s,a){const r=Ls(t)?t:xn(t);return r.start(pd("",r,s,a)),r.animation}const EA=(t,s)=>t.depth-s.depth;class _A{constructor(){this.children=[],this.isDirty=!1}add(s){$c(this.children,s),this.isDirty=!0}remove(s){Uc(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(EA),this.isDirty=!1,this.children.forEach(s)}}function MA(t,s){const a=ta.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(dr(r),t(i-s))};return es.setup(r,!0),()=>dr(r)}const k0=["TopLeft","TopRight","BottomLeft","BottomRight"],LA=k0.length,wx=t=>typeof t=="string"?parseFloat(t):t,Cx=t=>typeof t=="number"||ot.test(t);function OA(t,s,a,r,n,i){n?(t.opacity=ns(0,a.opacity??1,$A(r)),t.opacityExit=ns(s.opacity??1,0,UA(r))):i&&(t.opacity=ns(s.opacity??1,a.opacity??1,r));for(let l=0;lrs?1:a(Jn(t,s,r))}function Ax(t,s){t.min=s.min,t.max=s.max}function ha(t,s){Ax(t.x,s.x),Ax(t.y,s.y)}function Tx(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function kx(t,s,a,r,n){return t-=s,t=qi(t,1/a,r),n!==void 0&&(t=qi(t,1/n,r)),t}function BA(t,s=0,a=1,r=.5,n,i=t,l=t){if(Ma.test(s)&&(s=parseFloat(s),s=ns(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=ns(i.min,i.max,r);t===i&&(o-=s),t.min=kx(t.min,s,a,o,n),t.max=kx(t.max,s,a,o,n)}function Dx(t,s,[a,r,n],i,l){BA(t,s[a],s[r],s[n],s.scale,i,l)}const VA=["x","scaleX","originX"],zA=["y","scaleY","originY"];function Rx(t,s,a,r){Dx(t.x,s,VA,a?a.x:void 0,r?r.x:void 0),Dx(t.y,s,zA,a?a.y:void 0,r?r.y:void 0)}function Fx(t){return t.translate===0&&t.scale===1}function R0(t){return Fx(t.x)&&Fx(t.y)}function Ix(t,s){return t.min===s.min&&t.max===s.max}function HA(t,s){return Ix(t.x,s.x)&&Ix(t.y,s.y)}function Px(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function F0(t,s){return Px(t.x,s.x)&&Px(t.y,s.y)}function Ex(t){return Vs(t.x)/Vs(t.y)}function _x(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class GA{constructor(){this.members=[]}add(s){$c(this.members,s),s.scheduleRender()}remove(s){if(Uc(this.members,s),s===this.prevLead&&(this.prevLead=void 0),s===this.lead){const a=this.members[this.members.length-1];a&&this.promote(a)}}relegate(s){const a=this.members.findIndex(n=>s===n);if(a===0)return!1;let r;for(let n=a;n>=0;n--){const i=this.members[n];if(i.isPresent!==!1){r=i;break}}return r?(this.promote(r),!0):!1}promote(s,a){const r=this.lead;if(s!==r&&(this.prevLead=r,this.lead=s,s.show(),r)){r.instance&&r.scheduleRender(),s.scheduleRender(),s.resumeFrom=r,a&&(s.resumeFrom.preserveOpacity=!0),r.snapshot&&(s.snapshot=r.snapshot,s.snapshot.latestValues=r.animationValues||r.latestValues),s.root&&s.root.isUpdating&&(s.isLayoutDirty=!0);const{crossfade:n}=s.options;n===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(s=>{const{options:a,resumingFrom:r}=s;a.onExitComplete&&a.onExitComplete(),r&&r.options.onExitComplete&&r.options.onExitComplete()})}scheduleRender(){this.members.forEach(s=>{s.instance&&s.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function WA(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,l=(a==null?void 0:a.z)||0;if((n||i||l)&&(r=`translate3d(${n}px, ${i}px, ${l}px) `),(s.x!==1||s.y!==1)&&(r+=`scale(${1/s.x}, ${1/s.y}) `),a){const{transformPerspective:d,rotate:m,rotateX:p,rotateY:u,skewX:h,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),p&&(r+=`rotateX(${p}deg) `),u&&(r+=`rotateY(${u}deg) `),h&&(r+=`skewX(${h}deg) `),g&&(r+=`skewY(${g}deg) `)}const o=t.x.scale*s.x,c=t.y.scale*s.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const no=["","X","Y","Z"],YA=1e3;let KA=0;function io(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function I0(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=f0(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",es,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&I0(r)}function P0({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=KA++,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(JA),this.nodes.forEach(tT),this.nodes.forEach(sT),this.nodes.forEach(ZA)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=l,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let c=0;cthis.root.updateBlockedByResize=!1;es.read(()=>{p=window.innerWidth}),t(l,()=>{const h=window.innerWidth;h!==p&&(p=h,this.root.updateBlockedByResize=!0,m&&m(),m=MA(u,250),Oi.hasAnimatedSinceResize&&(Oi.hasAnimatedSinceResize=!1,this.nodes.forEach(Ox)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:p,hasRelativeLayoutChanged:u,layout:h})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||lT,{onLayoutAnimationStart:b,onLayoutAnimationComplete:f}=d.getProps(),j=!this.targetLayout||!F0(this.targetLayout,h),y=!p&&u;if(this.options.layoutRoot||this.resumeFrom||y||p&&(j||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const v={...sd(g,"layout"),onPlay:b,onComplete:f};(d.shouldReduceMotion||this.options.layoutRoot)&&(v.delay=0,v.type=!1),this.startAnimation(v),this.setAnimationOrigin(m,y)}else p||Ox(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=h})}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(),dr(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(aT),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&&I0(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&&!Vs(this.snapshot.measuredBox.x)&&!Vs(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c{const S=w/1e3;$x(p.x,l.x,S),$x(p.y,l.y,S),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Wn(u,this.layout.layoutBox,this.relativeParent.layout.layoutBox),nT(this.relativeTarget,this.relativeTargetOrigin,u,S),v&&HA(this.relativeTarget,v)&&(this.isProjectionDirty=!1),v||(v=hs()),ha(v,this.relativeTarget)),b&&(this.animationValues=m,OA(m,d,this.latestValues,S,y,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=S},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(dr(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=es.update(()=>{Oi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=xn(0)),this.currentAnimation=PA(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(YA),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:m}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&E0(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||hs();const p=Vs(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+p;const u=Vs(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+u}ha(o,c),rn(o,m),Gn(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new GA),this.sharedNodes.get(l).add(o);const d=o.options.initialPromotionConfig;o.promote({transition:d?d.transition:void 0,preserveFollowOpacity:d&&d.shouldPreserveFollowOpacity?d.shouldPreserveFollowOpacity(o):void 0})}isLead(){const l=this.getStack();return l?l.lead===this:!0}getLead(){var o;const{layoutId:l}=this.options;return l?((o=this.getStack())==null?void 0:o.lead)||this:this}getPrevLead(){var o;const{layoutId:l}=this.options;return l?(o=this.getStack())==null?void 0:o.prevLead:void 0}getStack(){const{layoutId:l}=this.options;if(l)return this.root.sharedNodes.get(l)}promote({needsReset:l,transition:o,preserveFollowOpacity:c}={}){const d=this.getStack();d&&d.promote(this,c),l&&(this.projectionDelta=void 0,this.needsReset=!0),o&&this.setOptions({transition:o})}relegate(){const l=this.getStack();return l?l.relegate(this):!1}resetSkewAndRotation(){const{visualElement:l}=this.options;if(!l)return;let o=!1;const{latestValues:c}=l;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(o=!0),!o)return;const d={};c.z&&io("z",l,d,this.animationValues);for(let m=0;m{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(Mx),this.root.sharedNodes.clear()}}}function QA(t){t.updateLayout()}function XA(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 u=l?s.measuredBox[p]:s.layoutBox[p],h=Vs(u);u.min=r[p].min,u.max=u.min+h}):E0(i,s.layoutBox,r)&&pa(p=>{const u=l?s.measuredBox[p]:s.layoutBox[p],h=Vs(r[p]);u.max=u.min+h,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[p].max=t.relativeTarget[p].min+h)});const o=nn();Gn(o,r,s.layoutBox);const c=nn();l?Gn(c,t.applyTransform(n,!0),s.measuredBox):Gn(c,r,s.layoutBox);const d=!R0(o);let m=!1;if(!t.resumeFrom){const p=t.getClosestProjectingParent();if(p&&!p.resumeFrom){const{snapshot:u,layout:h}=p;if(u&&h){const g=hs();Wn(g,s.layoutBox,u.layoutBox);const b=hs();Wn(b,r,h.layoutBox),F0(g,b)||(m=!0),p.options.layoutRoot&&(t.relativeTarget=b,t.relativeTargetOrigin=g,t.relativeParent=p)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function JA(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 ZA(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function qA(t){t.clearSnapshot()}function Mx(t){t.clearMeasurements()}function Lx(t){t.isLayoutDirty=!1}function eT(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function Ox(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function tT(t){t.resolveTargetDelta()}function sT(t){t.calcProjection()}function aT(t){t.resetSkewAndRotation()}function rT(t){t.removeLeadSnapshot()}function $x(t,s,a){t.translate=ns(s.translate,0,a),t.scale=ns(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function Ux(t,s,a,r){t.min=ns(s.min,a.min,r),t.max=ns(s.max,a.max,r)}function nT(t,s,a,r){Ux(t.x,s.x,a.x,r),Ux(t.y,s.y,a.y,r)}function iT(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const lT={duration:.45,ease:[.4,0,.1,1]},Bx=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Vx=Bx("applewebkit/")&&!Bx("chrome/")?Math.round:ba;function zx(t){t.min=Vx(t.min),t.max=Vx(t.max)}function oT(t){zx(t.x),zx(t.y)}function E0(t,s,a){return t==="position"||t==="preserve-aspect"&&!hA(Ex(s),Ex(a),.2)}function cT(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const dT=P0({attachResizeListener:(t,s)=>si(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),lo={current:void 0},_0=P0({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!lo.current){const t=new dT({});t.mount(window),t.setOptions({layoutScroll:!0}),lo.current=t}return lo.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),mT={pan:{Feature:DA},drag:{Feature:kA,ProjectionNode:_0,MeasureLayout:T0}};function Hx(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&&es.postRender(()=>i(s,hi(s)))}class uT extends hr{mount(){const{current:s}=this.node;s&&(this.unmount=P2(s,(a,r)=>(Hx(this.node,r,"Start"),n=>Hx(this.node,n,"End"))))}unmount(){}}class xT extends hr{constructor(){super(...arguments),this.isActive=!1}onFocus(){let s=!1;try{s=this.node.current.matches(":focus-visible")}catch{s=!0}!s||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=mi(si(this.node.current,"focus",()=>this.onFocus()),si(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Gx(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&&es.postRender(()=>i(s,hi(s)))}class hT extends hr{mount(){const{current:s}=this.node;s&&(this.unmount=L2(s,(a,r)=>(Gx(this.node,r,"Start"),(n,{success:i})=>Gx(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const sc=new WeakMap,oo=new WeakMap,pT=t=>{const s=sc.get(t.target);s&&s(t)},gT=t=>{t.forEach(pT)};function fT({root:t,...s}){const a=t||document;oo.has(a)||oo.set(a,{});const r=oo.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(gT,{root:t,...s})),r[n]}function bT(t,s,a){const r=fT(s);return sc.set(t,a),r.observe(t),()=>{sc.delete(t),r.unobserve(t)}}const jT={some:0,all:1};class yT extends hr{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:a,margin:r,amount:n="some",once:i}=s,l={root:a?a.current:void 0,rootMargin:r,threshold:typeof n=="number"?n:jT[n]},o=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:p}=this.node.getProps(),u=d?m:p;u&&u(c)};return bT(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(vT(s,a))&&this.startObserver()}unmount(){}}function vT({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const NT={inView:{Feature:yT},tap:{Feature:hT},focus:{Feature:xT},hover:{Feature:uT}},wT={layout:{ProjectionNode:_0,MeasureLayout:T0}},CT={...oA,...NT,...mT,...wT},Wt=CS(CT,LS),In=[{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:_t,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:zh,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 ST({open:t,onClose:s,onSelectTemplate:a}){var d,m,p;const[r,n]=x.useState(null),[i,l]=x.useState(!1);x.useEffect(()=>{const u=at.getUserData();l((u==null?void 0:u.jobTitle)==="Dealer")},[]);const o=u=>{if(i)return;const h=In.find(g=>g.id===u);h!=null&&h.disabled||n(u)},c=()=>{r&&(a(r),s())};return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"!fixed !inset-0 !top-0 !left-0 !right-0 !bottom-0 !w-screen !h-screen !max-w-none !translate-x-0 !translate-y-0 p-0 gap-0 border-0 !rounded-none bg-gradient-to-br from-gray-50 to-white [&>button]:hidden !m-0",children:[e.jsx(mt,{className:"sr-only",children:"Select a Template"}),e.jsx(Et,{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(cl,{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:In.map((u,h)=>{const g=u.icon,b=r===u.id,f=i||u.disabled;return e.jsx(Wt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:h*.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(u.id),children:[e.jsxs(ie,{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 ${u.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(Oa,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(le,{className:"text-xl mb-2",children:u.name}),e.jsx(ye,{className:"text-sm leading-relaxed",children:u.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(Je,{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"})]}),u.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(Je,{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(ae,{variant:"secondary",className:"text-xs",children:u.category})}),e.jsx(Zt,{}),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(rt,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:u.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ts,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[u.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:[u.features.slice(0,3).map((j,y)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(Be,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:j})]},y)),u.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",u.features.length-3," more features"]})]})]})]})]})},u.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(P,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(P,{onClick:c,disabled:!r||i||((d=In.find(u=>u.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=In.find(u=>u.id===r))!=null&&m.disabled)?"bg-blue-600 hover:bg-blue-700":"bg-gray-400 cursor-not-allowed"}`,children:["Continue with Template",e.jsx(js,{className:"w-4 h-4"})]})]}),e.jsx(Cl,{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=In.find(u=>u.id===r))==null?void 0:p.name})]})})})]})})]})})}function Gr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=x.useState(100),[m,p]=x.useState(0),[u,h]=x.useState(null),[g,b]=x.useState(!1),[f,j]=x.useState(null),y=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),v=s.toLowerCase().includes("pdf"),w=y||v;x.useEffect(()=>{if(!l||!w||!a){h(null);return}return(async()=>{b(!0),j(null);try{let I=a;a.startsWith("/")&&!a.startsWith("//")&&(I=`${window.location.origin}${a}`);const T=await fetch(I,{headers:{Accept:v?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!T.ok){const D=await T.text().catch(()=>"");throw new Error(`Failed to load file: ${T.status} ${T.statusText}. ${D}`)}const M=await T.blob();if(M.size===0)throw new Error("File is empty or could not be loaded");v&&!M.type.includes("pdf")&&M.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${M.type}`);const F=window.URL.createObjectURL(M);h(F)}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)}})(),()=>{u&&(window.URL.revokeObjectURL(u),h(null))}},[l,a,w,v]);const S=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},C=()=>d(k=>Math.min(k+25,200)),E=()=>d(k=>Math.max(k-25,50)),R=()=>p(k=>(k+90)%360);return e.jsx(xt,{open:l,onOpenChange:o,children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ht,{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(vt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`• ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[y&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(P,{variant:"ghost",size:"sm",onClick:E,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(fj,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[c,"%"]}),e.jsx(P,{variant:"ghost",size:"sm",onClick:C,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(bj,{className:"h-4 w-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:R,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(Hh,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(P,{variant:"outline",size:"sm",onClick:S,className:"gap-2 h-9",children:[e.jsx(Tt,{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(ze,{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(P,{onClick:S,className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"}),"Download ",t]})]}):w&&u?e.jsxs(e.Fragment,{children:[y&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:u,alt:t,style:{transform:`scale(${c/100}) rotate(${m}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),v&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:u,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(vt,{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(P,{onClick:S,className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function pi({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Et,{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(Dt,{children:e.jsx(P,{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},kl=async t=>{const s=t?{category:t}:{};return(await be.get("/admin/configurations",{params:s})).data.data},Bs=async(t,s)=>{await be.put(`/admin/configurations/${t}`,{configValue:s})},AT=async t=>{await be.post(`/admin/configurations/${t}/reset`)},TT=async()=>{const t=await be.get("/admin/form16-config");return t.data.data??t.data},kT=async t=>{await be.put("/admin/form16-config",t)},DT=async t=>{const s=t?{year:t}:{};return(await be.get("/admin/holidays",{params:s})).data.data},RT=async t=>(await be.post("/admin/holidays",t)).data.data,FT=async(t,s)=>(await be.put(`/admin/holidays/${t}`,s)).data.data,IT=async t=>{await be.delete(`/admin/holidays/${t}`)},PT=async()=>(await be.get("/config/activity-types")).data.data,ET=async t=>{const s={activeOnly:t.toString()};return(await be.get("/admin/activity-types",{params:s})).data.data},_T=async t=>(await be.post("/admin/activity-types",t)).data.data,MT=async(t,s)=>(await be.put(`/admin/activity-types/${t}`,s)).data.data,LT=async t=>{await be.delete(`/admin/activity-types/${t}`)},OT={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 $T(t,s,a){const[r,n]=x.useState(OT),[i,l]=x.useState(null),[o,c]=x.useState(t),[d,m]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[p,u]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[h,g]=x.useState([]);return x.useEffect(()=>{(async()=>{var j;try{const y=await ma("DOCUMENT_POLICY"),v={};y.forEach(O=>{v[O.configKey]=O.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(O=>O.trim().toLowerCase());u({maxFileSizeMB:w,allowedFileTypes:C});const E=await ma("SYSTEM_SETTINGS"),R=await ma("WORKFLOW_SHARING"),k=[...E,...R],N={};k.forEach(O=>{N[O.configKey]=O.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)}})()},[]),x.useEffect(()=>{if(!t||!s)return;let f=!0;return(async()=>{try{c(!0);const j=await Is(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(I=>!I.isDeleted):[];g(S);const C=(y.priority||"").toString().toLowerCase(),E={standard:"standard",express:"express"},R=y.templateType==="TEMPLATE"?"existing-template":"custom",k=a.find(I=>I.id===R)||a[0]||null;l(k);const N=v.sort((I,B)=>(I.levelNumber||0)-(B.levelNumber||0)).map(I=>{const B=Number(I.tatHours||24),T=Math.floor(B/24),M=B%24;return{id:I.approverId||`temp-${I.levelNumber}`,name:I.approverName||I.approverEmail||"",email:I.approverEmail||"",role:I.levelName||`Level ${I.levelNumber}`,department:"",avatar:(I.approverName||I.approverEmail||"XX").substring(0,2).toUpperCase(),level:I.levelNumber||1,canClose:!1,tat:T>0?T:M,tatType:T>0?"days":"hours",userId:I.approverId}}),O=w.filter(I=>(I.participantType||I.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(I.userEmail||I.user_email||I.email):!1).map((I,B)=>{const T=I.userId||I.user_id||I.id,M=I.userName||I.user_name||I.name||"",F=I.userEmail||I.user_email||I.email||"",A=(M||F||"XX").split(" ").map(H=>H[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:T||`spectator-${s}-${B}-${Date.now()}`,userId:T,name:M||F||"Spectator",email:F,role:"Spectator",department:I.department||"",avatar:A,level:1,canClose:!1}});n(I=>({...I,template:R,title:y.title||"",description:y.description||"",priority:E[C]||"standard",approvers:N,approverCount:N.length||1,spectators:O,maxLevel:Math.max(...N.map(B=>B.level||1),1)}))}catch(j){console.error("Failed to load draft:",j)}finally{f&&c(!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:d,documentPolicy:p,existingDocuments:h,setExistingDocuments:g}}const Wx=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function UT(t,s,a){const[r,n]=x.useState(t?2:1),i=Wx.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 u=p.tatType||"hours";return u==="hours"?p.tat&&p.tat>0&&p.tat<=720:u==="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:Wx,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 BT(){const[t,s]=x.useState({open:!1,type:"error",email:"",message:""}),[a,r]=x.useState({open:!1,violations:[]}),[n,i]=x.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(u,h,g="")=>{s({open:!0,type:u,email:h,message:g})},closeValidationModal:()=>{s(u=>({...u,open:!1}))},openPolicyViolationModal:u=>{r({open:!0,violations:u})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:u=>{i({open:!0,errors:u})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function VT(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function zT(t,s,a){var n;const r=VT(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 HT(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return zT(a,n,n===s)})}function Yx(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 Kx(t,s,a,r=!1){const n=HT(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 GT(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 Qx(t,s){return{id:(await Ec(t,s||[],"SUPPORTING")).id}}async function Xx(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await k1(t,s,a||[],r):await T1(t,s)}function WT({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=x.useState(!1),[m,p]=x.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var b,f;if(c||m)return;const g=GT(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const j=Kx(t,n,r,!1);await Xx(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=Yx(t,s,n,!1),y=await Qx(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}),d(!1)}},handleSaveDraft:async()=>{var g,b;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||m)){p(!0);try{if(i&&l){const f=Kx(t,n,r,!0);await Xx(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=Yx(t,s,n,!0),j=await Qx(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 va(t,s=10,a="default"){return await be.get("/users/search",{params:{q:t,limit:s,source:a}})}async function ja(t){var a;const s=await be.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function YT(t,s){return await be.post("/admin/users/assign-role",{email:t,role:s})}async function KT(t,s){return await be.put(`/admin/users/${t}/role`,{role:s})}async function QT(t,s=1,a=10){return await be.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function XT(){return await be.get("/admin/users/role-statistics")}async function JT(t){var a;const s=await be.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function ZT(){var s,a;return((a=(s=(await be.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const ca={searchUsers:va,getUserById:JT,ensureUserExists:ja,assignRole:YT,updateUserRole:KT,getUsersByRole:QT,getRoleStatistics:XT,getAllUsers:ZT};async function qT(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 va(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 ja({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 e5(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(R),a("template",R.id),a("category",R.category),a("priority",R.priority);const k=new Date;k.setDate(k.getDate()+R.suggestedSLA),a("slaEndDate",k),R.id!=="custom"&&R.id!=="existing-template"&&h(`/create-admin-request/${R.id}`)},handleTemplateSelection:R=>{R==="claim-management"?h("/claim-management"):R==="vendor-payment"?h("/vendor-payment"):u&&u({templateType:R})},nextStep:async()=>{var R;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 O=r.approverCount||1;if(O>m.maxApprovalLevels){p([{type:"Maximum Approval Levels Exceeded",message:`The request has ${O} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:O,maxValue:m.maxApprovalLevels}]);return}}const k=((R=c==null?void 0:c.email)==null?void 0:R.toLowerCase())||"",N=await e5(r.approvers,k);if(!N.success&&N.error){d(N.error.type,N.error.email,N.error.message);return}N.validatedApprovers&&a("approvers",N.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(R,k)=>{if(k){const N=R.documentId||R.document_id||"";j({fileName:R.originalFileName||R.fileName||"Document",fileType:R.fileType||R.file_type||"application/octet-stream",fileUrl:yn(N),fileSize:Number(R.fileSize||R.file_size||0),documentId:N})}else{const N=URL.createObjectURL(R);j({fileName:R.name,fileType:R.type||"application/octet-stream",fileUrl:N,fileSize:R.size,file:R})}},closePreview:()=>{f!=null&&f.fileUrl&&(f!=null&&f.file)&&URL.revokeObjectURL(f.fileUrl),j(null)}}}const Jx=[{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:dl,estimatedTime:"Variable",commonApprovers:[],suggestedSLA:3,priority:"medium",fields:{}},{id:"existing-template",name:"Existing Template",description:"Use a pre-configured template with predefined approval workflows, timelines, and requirements for faster processing",category:"Templates",icon:Re,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let Lr=null;const Zx=()=>Lr,s5=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 Lr&&Lr.push(r),r},Dl=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 Lr=a,a},a5=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 Lr&&(Lr=Lr.map(i=>i.id===t?n:i)),n};function M0({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 r5({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:l,submitting:o,savingDraft:c,loadingDraft:d,isEditing:m}){return e.jsx("div",{className:"fixed sm:relative bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0 shadow-lg sm:shadow-none z-50","data-testid":"wizard-footer",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2 sm:gap-4 max-w-6xl mx-auto",children:[e.jsxs(P,{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(P,{variant:"outline",onClick:l,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:d||o||c,"data-testid":"wizard-footer-save-draft-button",children:c?e.jsxs(e.Fragment,{children:[e.jsx(ze,{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(P,{onClick:i,disabled:!a||d||o||c,size:"sm",className:"sm:size-lg bg-green-600 hover:bg-green-700 flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-submit-button",children:o?e.jsxs(e.Fragment,{children:[e.jsx(ze,{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(Gh,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(P,{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(js,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const qx=t=>{switch(t){case"high":return e.jsx(Fa,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(ts,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Hs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(ts,{className:"w-4 h-4 text-gray-600"})}};function n5({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=x.useState("main"),l=Cs(),o=m=>{m.id==="admin-templates-category"?i("admin"):n==="admin"?l(`/create-admin-request/${m.id}`):a(m)},c=n==="main"?[...t]:r;return e.jsxs(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(P,{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:c.length===0&&n==="admin"?e.jsxs("div",{className:"col-span-full text-center py-12 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed border-gray-200",children:[e.jsx(jj,{className:"w-12 h-12 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No admin templates available yet."})]}):c.map(m=>{var g;const u=m.id==="admin-templates-category",h=(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 ${h?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200 cursor-pointer":u?"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(ie,{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 ${h||u?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${m.id}-icon`,children:e.jsx(m.icon,{className:`w-7 h-7 ${h||u?"text-blue-600":"text-gray-600"}`})}),h&&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(Oa,{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(le,{className:"text-xl","data-testid":`template-card-${m.id}-name`,children:m.name}),!1]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ae,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),qx(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}),!u&&e.jsxs(e.Fragment,{children:[e.jsx(Zt,{}),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(rt,{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(qt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[((g=m.commonApprovers)==null?void 0:g.length)||0," approvers"]})]})]})]}),u&&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(Cl,{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(ie,{children:e.jsxs(le,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Vr,{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(se,{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(se,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[qx(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(se,{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(se,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((d=s.commonApprovers)==null?void 0:d.length)>0?s.commonApprovers.map((m,p)=>e.jsx(ae,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${p}`,children:m},`${s.id}-approver-${p}-${m}`)):e.jsx("span",{className:"text-sm text-gray-500 italic",children:"No specific approvers defined"})})]})]})]})})})]})}function 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 i5({className:t,...s}){return e.jsx(Ab,{"data-slot":"radio-group",className:Me("grid gap-3",t),...s})}function eh({className:t,...s}){return e.jsx(Tb,{"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(kb,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(xc,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function l5({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(Re,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"basic-information-title",children:"Basic Information"}),e.jsxs("p",{className:"text-gray-600","data-testid":"basic-information-description",children:["Provide the essential details for your ",(s==null?void 0:s.name)||"request","."]})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"basic-information-form",children:[e.jsxs("div",{"data-testid":"basic-information-title-field",children:[e.jsx(se,{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(se,{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(di,{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(se,{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(i5,{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(eh,{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(ol,{className:"w-4 h-4 text-red-600"}),e.jsx(se,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(ae,{variant:"destructive",className:"text-xs",children:"URGENT"})]}),e.jsx("p",{className:"text-xs text-red-700",children:"Includes calendar days in TAT - faster processing timeline"})]})]}),e.jsxs("div",{className:`flex items-center space-x-3 p-3 rounded-lg border cursor-pointer transition-all ${t.priority==="standard"?"border-blue-500 bg-blue-50":"border-gray-200 hover:bg-gray-50"}`,onClick:()=>a("priority","standard"),"data-testid":"basic-information-priority-standard-option",children:[e.jsx(eh,{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(rt,{className:"w-4 h-4 text-blue-600"}),e.jsx(se,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(ae,{variant:"secondary",className:"text-xs",children:"DEFAULT"})]}),e.jsx("p",{className:"text-xs text-gray-600",children:"Includes working days in TAT - regular processing timeline"})]})]})]})]})}),((s==null?void 0:s.fields.amount)||(s==null?void 0:s.fields.vendor)||(s==null?void 0:s.fields.timeline)||(s==null?void 0:s.fields.impact))&&e.jsxs("div",{className:"border-t pt-6","data-testid":"basic-information-additional-details",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Additional Details"}),e.jsxs("div",{className:"space-y-6",children:[(s==null?void 0:s.fields.amount)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4","data-testid":"basic-information-amount-field",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{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(se,{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(We,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"USD",children:"USD ($)"}),e.jsx(J,{value:"EUR",children:"EUR (€)"}),e.jsx(J,{value:"GBP",children:"GBP (£)"}),e.jsx(J,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(se,{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(se,{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(se,{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 L0(){const[t,s]=x.useState([]),[a,r]=x.useState(!1),n=x.useRef(null);return{searchResults:t,searchLoading:a,searchUsersDebounced:async(c,d=10)=>{if(n.current&&clearTimeout(n.current),!c||!c.startsWith("@")||c.length<2){s([]),r(!1);return}r(!0),n.current=setTimeout(async()=>{var m;try{const p=c.slice(1),h=((m=(await va(p,d)).data)==null?void 0:m.data)||[];s(h)}catch(p){console.error("User search failed:",p),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await ja({userId:c.userId,email:c.email,displayName:c.displayName,firstName:c.firstName,lastName:c.lastName,department:c.department,phone:c.phone,mobilePhone:c.mobilePhone,designation:c.designation,jobTitle:c.jobTitle,manager:c.manager,employeeId:c.employeeId,employeeNumber:c.employeeNumber,secondEmail:c.secondEmail,location:c.location})}catch(d){throw console.error("Failed to ensure user exists:",d),d}}}}function O0(){const[t,s]=x.useState({}),[a,r]=x.useState({}),n=x.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(o,c,d=10)=>{if(n.current[o]&&clearTimeout(n.current[o]),!c||!c.startsWith("@")||c.length<2){s(m=>({...m,[o]:[]})),r(m=>({...m,[o]:!1}));return}r(m=>({...m,[o]:!0})),n.current[o]=setTimeout(async()=>{var m;try{const p=c.slice(1),h=((m=(await va(p,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:h}))}catch(p){console.error(`User search failed for index ${o}:`,p),s(u=>({...u,[o]:[]}))}finally{r(p=>({...p,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function o5({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var p;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=O0();x.useEffect(()=>{const u=t.approverCount||1,h=t.approvers||[];if(h.lengthu&&s("approvers",h.slice(0,u))},[t.approverCount,s]);const d=(u,h)=>{var j,y,v,w,S;const g=[...t.approvers],f=((j=g[u])==null?void 0:j.email)!==h;if(g[u]={...g[u],email:h,level:u+1,userId:f||(y=g[u])==null?void 0:y.userId,name:f||(v=g[u])==null?void 0:v.name,department:f||(w=g[u])==null?void 0:w.department,avatar:f||(S=g[u])==null?void 0:S.avatar},s("approvers",g),!h||!h.startsWith("@")||h.length<2){c(u);return}o(u,h,10)},m=async(u,h)=>{var g,b;try{if((g=t.approvers)==null?void 0:g.some((w,S)=>{var C,E;return S!==u&&(w.userId===h.userId||((C=w.email)==null?void 0:C.toLowerCase())===((E=h.email)==null?void 0:E.toLowerCase()))})){a({type:"error",email:h.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===h.userId||((S=w.email)==null?void 0:S.toLowerCase())===((C=h.email)==null?void 0:C.toLowerCase())})){a({type:"error",email:h.email,message:"This user is already added as a spectator. A user cannot be both an approver and a spectator."});return}const y=await ja({userId:h.userId,email:h.email,displayName:h.displayName,firstName:h.firstName,lastName:h.lastName,department:h.department,phone:h.phone,mobilePhone:h.mobilePhone,designation:h.designation,jobTitle:h.jobTitle,manager:h.manager,employeeId:h.employeeId,employeeNumber:h.employeeNumber,secondEmail:h.secondEmail,location:h.location}),v=[...t.approvers];v[u]={...v[u],email:h.email,name:h.displayName||[h.firstName,h.lastName].filter(Boolean).join(" "),userId:y.userId,level:u+1},s("approvers",v),c(u)}catch(f){console.error("Failed to ensure user exists:",f),a({type:"error",email:h.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(qt,{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(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(lr,{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(se,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{const u=t.approverCount||1,h=Math.max(1,u-1);s("approverCount",h),t.approvers.length>h&&s("approvers",t.approvers.slice(0,h))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(hc,{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(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{const h=(t.approverCount||1)+1;if(h>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:h,maxValue:r.maxApprovalLevels}]);return}s("approverCount",h)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(ms,{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(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(fs,{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(ae,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-sm text-blue-700",children:"Creates and submits the request"})]})]})}),Array.from({length:t.approverCount||1},(u,h)=>{var j,y;const g=h+1,b=g===(t.approverCount||1),f=t.approvers[h]||{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(ae,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(se,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),f.email&&f.userId&&e.jsxs(ae,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Be,{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=>d(h,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[h]||(((j=i[h])==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[h]?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[h])==null?void 0:y.map(v=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(h,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(se,{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[h]={...w[h],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[h]={...w[h],tatType:v,level:g,tat:""},s("approvers",w)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(We,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"hours",children:"Hours"}),e.jsx(J,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},g)})]})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Vr,{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},(u,h)=>`Level ${h+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(rt,{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 u=((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,h=Math.ceil(u);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[h," ",h===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((u,h)=>{const g=Number(u.tat||0),f=(u.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 ",h+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[f," ",f===1?"hour":"hours"]})]})},h):null})}),(()=>{var g;const u=((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,h=Math.ceil(u/8);return u===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:[u,"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:h}),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 c5({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=x.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=L0(),p=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},u=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(""),d()}catch{a({type:"error",email:g.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const j=t.spectators.some(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}}},h=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(vt,{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(ie,{children:[e.jsxs(le,{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(vt,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(ae,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(ye,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(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 u())},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:()=>u(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(P,{size:"sm",onClick:()=>u(),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(Vr,{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(cs,{className:"h-6 w-6",children:e.jsx(ds,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>h(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(jt,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function d5({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:c,onDocumentErrors:d,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&&d&&d(y),b.target&&(b.target.value="")},u=b=>{const f=a.filter((j,y)=>y!==b);i(f)},h=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(ys,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"documents-title",children:"Documents & Attachments"}),e.jsx("p",{className:"text-gray-600","data-testid":"documents-description",children:"Upload supporting documents, files, and any additional materials for your request."})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"documents-content",children:[e.jsxs(Z,{"data-testid":"documents-upload-card",children:[e.jsxs(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Re,{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(ys,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"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(P,{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(ms,{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(ie,{children:e.jsxs(le,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ae,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(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(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.originalFileName||b.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:b.fileSize?(Number(b.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!0)&&e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>c(b,!0),"data-testid":`documents-existing-${f}-preview`,children:e.jsx(vt,{className:"h-4 w-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>h(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(ie,{children:e.jsxs(le,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ae,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(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(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(b.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!1)&&e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>c(b,!1),"data-testid":`documents-new-${f}-preview`,children:e.jsx(vt,{className:"h-4 w-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>u(f),"data-testid":`documents-new-${f}-remove`,children:e.jsx(jt,{className:"h-4 w-4"})})]})]},f))})})]})]})]})}const m5=t=>{switch(t){case"high":return e.jsx(Fa,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(ts,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Hs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(ts,{className:"w-4 h-4 text-gray-600"})}};function u5({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(Be,{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(ie,{children:e.jsxs(le,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(Gh,{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(se,{className:"text-green-900 font-semibold",children:"Request Type"}),e.jsx("p",{className:"text-green-800 mt-1",children:s==null?void 0:s.name}),e.jsx(ae,{variant:"outline",className:"mt-2 text-xs border-green-300 text-green-700",children:s==null?void 0:s.category})]}),e.jsxs("div",{"data-testid":"review-submit-overview-priority",children:[e.jsx(se,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[m5(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(se,{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(se,{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(ie,{children:e.jsxs(le,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(te,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(se,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(Ps,{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(ka,{className:"w-4 h-4 text-blue-600"}),e.jsx(se,{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(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(qt,{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(ae,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Email Address"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:(l==null?void 0:l.email)||"Not assigned"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"TAT (Turn Around Time)"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l!=null&&l.tat?`${l.tat} ${l.tatType==="days"?"day":"hour"}${l.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(Z,{"data-testid":"review-submit-participants-card",children:[e.jsx(ie,{children:e.jsxs(le,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(vt,{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(se,{className:"font-semibold text-sm",children:["Spectators (",t.spectators.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:t.spectators.map(a=>e.jsxs(ae,{variant:"outline",className:"text-xs","data-testid":`review-submit-spectator-${a.id}`,children:[a.name," (",a.email,")"]},a.id))})]})})]}),t.documents.length>0&&e.jsxs(Z,{"data-testid":"review-submit-documents-card",children:[e.jsxs(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(ys,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(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(Re,{className:"w-5 h-5 text-gray-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.name}),e.jsx("div",{className:"flex items-center gap-3 text-xs text-gray-500 mt-1",children:e.jsxs("span",{children:[(a.size/(1024*1024)).toFixed(2)," MB"]})})]})]},r))})})]}),e.jsx(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(Be,{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 x5({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(P,{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 h5({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(Cl,{mode:"wait",children:t})})})}function p5({modal:t,onClose:s}){return e.jsx(xt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Et,{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(dl,{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(Dt,{children:e.jsx(P,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function g5({modal:t,documentPolicy:s,onClose:a}){return e.jsx(xt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Et,{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(Dt,{children:e.jsx(P,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function th({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Ba(),i=Cs(),l=n.requestId||a||"",o=r&&!!l,{user:c}=us(),[d,m]=x.useState([]);x.useEffect(()=>{(async()=>{try{const me=(await Dl()).map(Ne=>({id:Ne.id,name:Ne.name,description:Ne.description,category:Ne.category,icon:Re,estimatedTime:Ne.estimatedTime,commonApprovers:Ne.approvers.map(Oe=>Oe.name),workflowApprovers:Ne.approvers,suggestedSLA:Ne.suggestedSLA,priority:Ne.priority,fields:Ne.fields||{}}));m(me)}catch(de){console.error("Failed to fetch admin templates:",de)}})()},[]);const p=x.useMemo(()=>[...Jx,...d],[d]),{formData:u,updateFormData:h,selectedTemplate:g,setSelectedTemplate:b,loadingDraft:f,systemPolicy:j,documentPolicy:y,existingDocuments:v,setExistingDocuments:w}=$T(o,l,p),{currentStep:S,totalSteps:C,stepNames:E,isStepValid:R,nextStep:k,prevStep:N}=UT(o,g,u),[O,I]=x.useState([]),[B,T]=x.useState([]),M=x.useRef(null),{validationModal:F,policyViolationModal:D,documentErrorModal:A,openValidationModal:H,closeValidationModal:$,openPolicyViolationModal:_,closePolicyViolationModal:L,openDocumentErrorModal:z,closeDocumentErrorModal:X}=BT(),{submitting:W,savingDraft:U,handleSubmit:V,handleSaveDraft:Q}=WT({formData:u,selectedTemplate:g,documents:O,documentsToDelete:B,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:ee,setShowTemplateModal:K,previewDocument:q,selectTemplate:ue,handleTemplateSelection:Le,nextStep:Ze,prevStep:De,handlePreviewDocument:_e,closePreview:Ue}=t5({selectedTemplate:g,setSelectedTemplate:b,updateFormData:h,formData:u,currentStep:S,isStepValid:R,wizardNextStep:k,wizardPrevStep:N,user:c,openValidationModal:H,systemPolicy:j,onPolicyViolation:_,onSubmit:s}),re=x.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}):De()},[S,t,i,De]),fe=x.useRef(!0),Ce=x.useRef(!1);x.useEffect(()=>{fe.current&&u.documents&&u.documents.length>0&&!Ce.current&&(I(u.documents),Ce.current=!0),fe.current=!1},[u.documents]);const Ae=x.useRef(!1),ce=x.useRef(O);x.useEffect(()=>{if(Ae.current){Ae.current=!1,ce.current=O;return}ce.current!==O&&(h("documents",O),ce.current=O)},[O]);const pe=()=>{switch(S){case 1:return e.jsx(n5,{templates:Jx,selectedTemplate:g,onSelectTemplate:ue,adminTemplates:d});case 2:return e.jsx(l5,{formData:u,selectedTemplate:g,updateFormData:h});case 3:return e.jsx(o5,{formData:u,updateFormData:h,systemPolicy:j,onValidationError:Te=>H(Te.type,Te.email,Te.message),onPolicyViolation:_});case 4:return e.jsx(c5,{formData:u,updateFormData:h,onValidationError:Te=>H(Te.type,Te.email,Te.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(d5,{documentPolicy:y,isEditing:o,documents:O,existingDocuments:v,documentsToDelete:B,onDocumentsChange:I,onExistingDocumentsChange:w,onDocumentsToDeleteChange:T,onPreviewDocument:_e,onDocumentErrors:Te=>z(Te),fileInputRef:M});case 6:return e.jsx(u5,{formData:u,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(x5,{isEditing:o,currentStep:S,totalSteps:C,stepNames:E,onBack:re}),e.jsx(M0,{currentStep:S,totalSteps:C,stepNames:E}),e.jsx(h5,{children:pe()}),e.jsx(r5,{currentStep:S,totalSteps:C,isStepValid:R(),onPrev:De,onNext:Ze,onSubmit:V,onSaveDraft:Q,submitting:W,savingDraft:U,loadingDraft:f,isEditing:o}),e.jsx(ST,{open:ee,onClose:()=>K(!1),onSelectTemplate:Le}),q&&e.jsx(Gr,{fileName:q.fileName,fileType:q.fileType,fileUrl:q.fileUrl,fileSize:q.fileSize,open:!!q,onClose:Ue,onDownload:async()=>{if(q.file){const Te=document.createElement("a");Te.href=q.fileUrl,Te.download=q.fileName,document.body.appendChild(Te),Te.click(),document.body.removeChild(Te)}else q.documentId&&await _s(q.documentId)},attachmentId:q.documentId}),e.jsx(p5,{modal:F,onClose:$}),e.jsx(g5,{modal:A,documentPolicy:y,onClose:X}),e.jsx(pi,{open:D.open,onClose:L,violations:D.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}function gi({className:t,...s}){return e.jsx(Db,{"data-slot":"tabs",className:Me("flex flex-col gap-2",t),...s})}function fi({className:t,...s}){return e.jsx(Rb,{"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(Fb,{"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(Ib,{"data-slot":"tabs-content",className:Me("flex-1 outline-none",t),...s})}function ai(t){if(!t)return!1;const s=t.request||t;return s.workflowType==="CLAIM_MANAGEMENT"||s.templateType==="claim-management"||s.template==="claim-management"||s.templateName==="Claim Management"||s.templateCode==="CLAIM_MANAGEMENT"}function gd(t,s=[],a){const[r,n]=x.useState(null),[i,l]=x.useState(!1),[o,c]=x.useState(!0),[d,m]=x.useState(null),[p,u]=x.useState(null),[h,g]=x.useState(!1),b=(S,C)=>(S||C||"NA").toString().split(" ").map(R=>R[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=x.useCallback(async()=>{var S,C,E,R,k,N,O,I,B,T,M,F,D,A,H;l(!0);try{const $=await Gs.getWorkflowDetails(t);if(!$){console.warn("[useRequestDetails] No details returned from API");return}const _=$.workflow||{},L=Array.isArray($.approvals)?$.approvals:[],z=Array.isArray($.participants)?$.participants:[],X=Array.isArray($.documents)?$.documents:[],W=$.summary||{},U=Array.isArray($.tatAlerts)?$.tatAlerts:[];U.length>0;const V=(W==null?void 0:W.currentLevel)||_.currentLevel||1,Q=L.map(de=>{const me=de.levelNumber||0,Ne=(de.status||"").toString().toUpperCase(),Oe=de.levelId||de.level_id;let st=f(de.status);me>V&&Ne!=="APPROVED"&&Ne!=="REJECTED"?st="waiting":me===V&&Ne==="PENDING"&&(st="pending");const nt=U.filter(St=>St.levelId===Oe);return{step:me,levelId:Oe,role:de.levelName||de.approverName||"Approver",status:st,approver:de.approverName||de.approverEmail,approverId:de.approverId||de.approver_id,approverEmail:de.approverEmail,tatHours:Number(de.tatHours||0),elapsedHours:Number(de.elapsedHours||0),remainingHours:Number(de.remainingHours||0),tatPercentageUsed:Number(de.tatPercentageUsed||0),actualHours:de.levelEndTime&&de.levelStartTime?Math.max(0,(new Date(de.levelEndTime).getTime()-new Date(de.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:de.comments||void 0,timestamp:de.actionDate||void 0,levelStartTime:de.levelStartTime||de.tatStartTime,tatAlerts:nt,skipReason:de.skipReason||void 0,isSkipped:Ne==="SKIPPED"||de.isSkipped||!1}}),ee=z.filter(de=>(de.participantType||de.participant_type||"").toUpperCase()==="SPECTATOR").map(de=>({name:de.userName||de.user_name||de.userEmail||de.user_email,role:"Spectator",email:de.userEmail||de.user_email,avatar:b(de.userName||de.user_name,de.userEmail||de.user_email)})),K=de=>{var Ne,Oe;if(!de)return;const me=z.find(st=>st.userId===de||st.user_id===de);return me!=null&&me.userName||me!=null&&me.user_name?me.userName||me.user_name:_.initiatorId===de?((Ne=_.initiator)==null?void 0:Ne.displayName)||((Oe=_.initiator)==null?void 0:Oe.email):de},q=X.map(de=>{const me=Number(de.fileSize||de.file_size||0),Ne=(me/(1024*1024)).toFixed(2)+" MB";return{documentId:de.documentId||de.document_id,name:de.originalFileName||de.fileName||de.file_name,fileType:de.fileType||de.file_type||"",size:Ne,sizeBytes:me,uploadedBy:K(de.uploadedBy||de.uploaded_by),uploadedAt:de.uploadedAt||de.uploaded_at}}),ue=Array.isArray($.activities)?$.activities.filter(de=>(de.type||"").toLowerCase()!=="sla_warning"):[];let Le=null;if(_.isPaused||!1)try{Le=await ku(_.requestId)}catch{}let De=null,_e=null,Ue=null,re=null,fe=[],Ce=null;if(ai(_)){try{const de=await be.get(`/dealer-claims/${_.requestId}/credit-note-wfm`),me=de.data??de;Ce=Array.isArray(me==null?void 0:me.data)?me.data:Array.isArray(me)?me:[]}catch(de){console.warn("[useRequestDetails] Error fetching credit note WFM data:",de)}try{const de=await be.get(`/dealer-claims/${_.requestId}`),me=((S=de.data)==null?void 0:S.data)||de.data;if(me){De=me.claimDetails||me.claim_details,_e=me.proposalDetails||me.proposal_details,Ue=me.completionDetails||me.completion_details,re=me.internalOrder||me.internal_order||null,fe=me.internalOrders||me.internal_orders||[];const Ne=me.budgetTracking||me.budget_tracking||null,Oe=me.invoice||null,st=me.creditNote||me.credit_note||null,nt=me.completionExpenses||me.completion_expenses||null;De&&(De.budgetTracking=Ne,De.invoice=Oe,De.creditNote=st,De.completionExpenses=nt,De.creditNoteWfmData=Ce)}else console.warn("[useRequestDetails] No claimData found in response")}catch(de){console.error("[useRequestDetails] Error fetching claim details:",{error:(de==null?void 0:de.message)||de,status:(C=de==null?void 0:de.response)==null?void 0:C.status,statusText:(E=de==null?void 0:de.response)==null?void 0:E.statusText,responseData:(R=de==null?void 0:de.response)==null?void 0:R.data,requestId:_.requestId})}}const Ae={..._,id:_.requestNumber||_.requestId,requestId:_.requestId,requestNumber:_.requestNumber,initiatorId:_.initiatorId||_.initiator_id,title:_.title,description:_.description,status:f(_.status),priority:(_.priority||"").toString().toLowerCase(),workflowType:_.workflowType||(_.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:Q,approvals:L,participants:z,documents:q,spectators:ee,summary:W,sla:(W==null?void 0:W.sla)||_.sla||null,initiator:{userId:((k=_.initiator)==null?void 0:k.userId)||((N=_.initiator)==null?void 0:N.user_id)||_.initiatorId||_.initiator_id,name:((O=_.initiator)==null?void 0:O.displayName)||((I=_.initiator)==null?void 0:I.email),role:((B=_.initiator)==null?void 0:B.designation)||void 0,department:((T=_.initiator)==null?void 0:T.department)||void 0,email:((M=_.initiator)==null?void 0:M.email)||void 0,phone:((F=_.initiator)==null?void 0:F.phone)||void 0,avatar:b((D=_.initiator)==null?void 0:D.displayName,(A=_.initiator)==null?void 0:A.email)},createdAt:_.createdAt,updatedAt:_.updatedAt,totalSteps:_.totalLevels||1,currentStepRaw:(W==null?void 0:W.currentLevel)||_.currentLevel||1,currentStep:Math.min(Math.max(1,(W==null?void 0:W.currentLevel)||_.currentLevel||1),_.totalLevels||1),auditTrail:ue,conclusionRemark:_.conclusionRemark||null,closureDate:_.closureDate||null,pauseInfo:Le||null,claimDetails:De||null,proposalDetails:_e||null,completionDetails:Ue||null,internalOrder:re||null,internalOrders:fe||[],budgetTracking:(De==null?void 0:De.budgetTracking)||null,invoice:(De==null?void 0:De.invoice)||(De==null?void 0:De.invoice)||null,creditNote:(De==null?void 0:De.creditNote)||null,creditNoteWfmData:Ce||(De==null?void 0:De.creditNoteWfmData)||null,completionExpenses:(De==null?void 0:De.completionExpenses)||null,templateType:_.templateType||_.template_type,form16Submission:$.form16Submission||null};n(Ae);const ce=(H=a==null?void 0:a.email)==null?void 0:H.toLowerCase(),pe=L.find(de=>{const me=(de.status||"").toString().toUpperCase(),Ne=(de.approverEmail||"").toLowerCase(),Oe=de.levelNumber||0;return(me==="PENDING"||me==="IN_PROGRESS"||me==="PAUSED")&&Ne===ce&&Oe===V});u(pe||null);const Te=a==null?void 0:a.userId;if(Te){const de=z.some(me=>(me.participantType||me.participant_type||"").toUpperCase()==="SPECTATOR"&&(me.userId||me.user_id)===Te);g(de)}else g(!1)}catch($){console.error("[useRequestDetails] Error refreshing details:",$),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);x.useEffect(()=>{if(!t){c(!1);return}let S=!0;return c(!0),m(null),(async()=>{var C,E,R,k,N,O,I,B,T,M,F,D,A,H;try{const $=await Gs.getWorkflowDetails(t);if(!S||!$){S&&c(!1);return}const _=$.workflow||{},L=Array.isArray($.approvals)?$.approvals:[],z=Array.isArray($.participants)?$.participants:[],X=Array.isArray($.documents)?$.documents:[],W=$.summary||{},U=Array.isArray($.tatAlerts)?$.tatAlerts:[],V=(_.priority||"").toString().toLowerCase(),Q=(W==null?void 0:W.currentLevel)||_.currentLevel||1,ee=L.map(me=>{const Ne=me.levelNumber||0,Oe=(me.status||"").toString().toUpperCase(),st=me.levelId||me.level_id;let nt=f(me.status);Oe==="PAUSED"?nt="paused":Ne>Q&&Oe!=="APPROVED"&&Oe!=="REJECTED"?nt="waiting":Ne===Q&&(Oe==="PENDING"||Oe==="IN_PROGRESS")&&(nt=Oe==="IN_PROGRESS"?"in-review":"pending");const St=U.filter(Mt=>Mt.levelId===st);return{step:Ne,levelId:st,role:me.levelName||me.approverName||"Approver",status:nt,approver:me.approverName||me.approverEmail,approverId:me.approverId||me.approver_id,approverEmail:me.approverEmail,tatHours:Number(me.tatHours||0),elapsedHours:Number(me.elapsedHours||0),remainingHours:Number(me.remainingHours||0),tatPercentageUsed:Number(me.tatPercentageUsed||0),actualHours:me.elapsedHours!==void 0&&me.elapsedHours!==null?Number(me.elapsedHours):void 0,comment:me.comments||void 0,timestamp:me.actionDate||void 0,levelStartTime:me.levelStartTime||me.tatStartTime,tatAlerts:St}}),K=z.filter(me=>(me.participantType||"").toUpperCase()==="SPECTATOR").map(me=>({name:me.userName||me.userEmail,role:"Spectator",avatar:b(me.userName,me.userEmail)})),q=me=>{var Oe,st;if(!me)return;const Ne=z.find(nt=>nt.userId===me);return Ne!=null&&Ne.userName?Ne.userName:_.initiatorId===me?((Oe=_.initiator)==null?void 0:Oe.displayName)||((st=_.initiator)==null?void 0:st.email):me},ue=X.map(me=>{const Ne=Number(me.fileSize||0),Oe=(Ne/(1024*1024)).toFixed(2)+" MB";return{documentId:me.documentId||me.document_id,name:me.originalFileName||me.fileName,fileType:me.fileType||me.file_type||"",size:Oe,sizeBytes:Ne,uploadedBy:q(me.uploadedBy),uploadedAt:me.uploadedAt}}),Le=Array.isArray($.activities)?$.activities.filter(me=>(me.type||"").toLowerCase()!=="sla_warning"):[];let Ze=null;if(_.isPaused||!1)try{Ze=await ku(_.requestId)}catch{}let _e=null,Ue=null,re=null,fe=null,Ce=[],Ae=null;if(ai(_)){try{const me=await be.get(`/dealer-claims/${_.requestId}/credit-note-wfm`),Ne=me.data??me;Ae=Array.isArray(Ne==null?void 0:Ne.data)?Ne.data:Array.isArray(Ne)?Ne:[]}catch(me){console.warn("[useRequestDetails] Error fetching credit note WFM data:",me)}try{const me=await be.get(`/dealer-claims/${_.requestId}`),Ne=((C=me.data)==null?void 0:C.data)||me.data;if(Ne){_e=Ne.claimDetails||Ne.claim_details,Ue=Ne.proposalDetails||Ne.proposal_details,re=Ne.completionDetails||Ne.completion_details,fe=Ne.internalOrder||Ne.internal_order||null,Ce=Ne.internalOrders||Ne.internal_orders||[];const Oe=Ne.budgetTracking||Ne.budget_tracking||null,st=Ne.invoice||null,nt=Ne.creditNote||Ne.credit_note||null,St=Ne.completionExpenses||Ne.completion_expenses||null;_e&&(_e.budgetTracking=Oe,_e.invoice=st,_e.creditNote=nt,_e.completionExpenses=St,_e.creditNoteWfmData=Ae)}}catch(me){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(me==null?void 0:me.message)||me,status:(E=me==null?void 0:me.response)==null?void 0:E.status,requestId:_.requestId})}}const ce={id:_.requestNumber||_.requestId,requestId:_.requestId,title:_.title,description:_.description,priority:V,status:f(_.status),workflowType:_.workflowType||(_.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:W,initiator:{name:((R=_.initiator)==null?void 0:R.displayName)||((k=_.initiator)==null?void 0:k.email),role:((N=_.initiator)==null?void 0:N.designation)||void 0,department:((O=_.initiator)==null?void 0:O.department)||void 0,email:((I=_.initiator)==null?void 0:I.email)||void 0,phone:((B=_.initiator)==null?void 0:B.phone)||void 0,avatar:b((T=_.initiator)==null?void 0:T.displayName,(M=_.initiator)==null?void 0:M.email)},createdAt:_.createdAt,updatedAt:_.updatedAt,totalSteps:_.totalLevels||1,currentStepRaw:(W==null?void 0:W.currentLevel)||_.currentLevel||1,currentStep:Math.min(Math.max(1,(W==null?void 0:W.currentLevel)||_.currentLevel||1),_.totalLevels||1),approvalFlow:ee,approvals:L,documents:ue,spectators:K,auditTrail:Le,conclusionRemark:_.conclusionRemark||null,closureDate:_.closureDate||null,pauseInfo:Ze||null,claimDetails:_e||null,proposalDetails:Ue||null,completionDetails:re||null,internalOrder:fe||null,internalOrders:Ce||[],budgetTracking:(_e==null?void 0:_e.budgetTracking)||null,invoice:(_e==null?void 0:_e.invoice)||null,creditNote:(_e==null?void 0:_e.creditNote)||null,creditNoteWfmData:Ae||(_e==null?void 0:_e.creditNoteWfmData)||null,completionExpenses:(_e==null?void 0:_e.completionExpenses)||null,templateType:_.templateType||_.template_type,form16Submission:$.form16Submission||null};n(ce);const pe=(F=a==null?void 0:a.email)==null?void 0:F.toLowerCase(),Te=L.find(me=>{const Ne=(me.status||"").toString().toUpperCase(),Oe=(me.approverEmail||"").toLowerCase(),st=me.levelNumber||0;return(Ne==="PENDING"||Ne==="IN_PROGRESS"||Ne==="PAUSED")&&Oe===pe&&st===Q});u(Te||null);const de=a==null?void 0:a.userId;if(de){const me=z.some(Ne=>(Ne.participantType||"").toUpperCase()==="SPECTATOR"&&Ne.userId===de);g(me)}else g(!1)}catch($){if(console.error("[useRequestDetails] Error loading request details:",$),S){if(((D=$==null?void 0:$.response)==null?void 0:D.status)===403){const _=((H=(A=$==null?void 0:$.response)==null?void 0:A.data)==null?void 0:H.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:_})}n(null)}}finally{S&&c(!1)}})(),()=>{S=!1}},[t,a]);const y=x.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=x.useMemo(()=>{var E,R,k;if(!y||!a)return!1;const S=(E=a==null?void 0:a.email)==null?void 0:E.toLowerCase(),C=(k=(R=y.initiator)==null?void 0:R.email)==null?void 0:k.toLowerCase();return S===C},[y,a]),w=x.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(E=>{E.approverEmail&&S.push({email:E.approverEmail.toLowerCase(),participantType:"APPROVER",name:E.approver})}),y.spectators&&Array.isArray(y.spectators)&&y.spectators.forEach(E=>{E.email&&S.push({email:E.email.toLowerCase(),participantType:"SPECTATOR",name:E.name})}),y.participants&&Array.isArray(y.participants)&&y.participants.forEach(E=>{const R=(E.userEmail||E.email||"").toLowerCase(),k=(E.participantType||E.participant_type||"").toUpperCase(),N=E.userName||E.user_name||E.name;R&&k&&!S.find(O=>O.email===R)&&S.push({email:R,participantType:k,name:N})}),S},[y]);return x.useEffect(()=>{if(!t||!r)return;const S=$r();if(!S)return;const C=E=>{((E==null?void 0:E.requestId)===r.requestId||(E==null?void 0:E.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:h,isInitiator:v,existingParticipants:w,accessDenied:d}}function $0(t,s,a,r){const[n,i]=x.useState([]),[l,o]=x.useState(0),[c,d]=x.useState([]);return x.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 Gs.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 u=$r();if(!u){console.error("[useRequestSocket] Socket not available");return}const h=r==null?void 0:r.userId,g=()=>{Eo(u,p,h)};return u.connected?g():u.on("connect",g),()=>{m&&(u.off("connect",g),mp(u,p))}})(),()=>{m=!1}},[t,r]),x.useEffect(()=>{!t||!s||(async()=>{try{const m=await mn(t),p=s.auditTrail||[],u=[...m,...p];u.sort((h,g)=>{const b=new Date(h.createdAt||h.created_at||h.timestamp||0).getTime(),f=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return b-f}),i(u)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),x.useEffect(()=>{if(!t)return;const m=$r();if(!m)return;const p=h=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await mn(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)}})()},u=h=>{const g=h.type==="breach"?"⏰":h.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const b=await Gs.getWorkflowDetails(t);b&&(Array.isArray(b.tatAlerts)&&b.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:h.message,icon:"/favicon.ico",tag:`tat-${h.requestId}-${h.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",u),()=>{m.off("noteHandler",p),m.off("worknote:new",p),m.off("tat:alert",u)}},[t,a,s]),x.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function Un(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 f5=["MALWARE_DETECTED","FILE_VALIDATION_FAILED","CONTENT_THREAT_DETECTED","SCAN_UNAVAILABLE","SCAN_ERROR"],b5={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 fd(t){var l,o,c,d;const s=(l=t==null?void 0:t.response)==null?void 0:l.data;if(!(s!=null&&s.error))return!1;const a=s.error;if(!f5.includes(a))return!1;const r=b5[a]||"Security Error",n=s.message||"File was blocked by security scan";let i="";return s.details&&((o=s.details.signatures)!=null&&o.length?i=`Virus: ${s.details.signatures.join(", ")}`:(c=s.details.errors)!=null&&c.length?i=s.details.errors[0]||"":(d=s.details.threats)!=null&&d.length&&(i=s.details.threats.map(m=>m.description).join(", "))),G.error(r,{description:i||n,duration:8e3,style:{background:"#fef2f2",border:"1px solid #fca5a5",color:"#991b1b"}}),!0}function U0(t,s){const[a,r]=x.useState(!1),[n,i]=x.useState(null),[l,o]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=x.useState({show:!1,errors:[]});x.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=h=>{const g=l.maxFileSizeMB*1024*1024;if(h.size>g)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${l.maxFileSizeMB}MB. Current size: ${(h.size/(1024*1024)).toFixed(2)}MB`};const b=h.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 h=>{var y,v;const g=h.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&&d({show:!0,errors:f}),j.length===0){h.target&&(h.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 Un(w,S,"SUPPORTING"),await s(),j.length{const h=document.createElement("input");h.type="file",h.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),h.onchange=p,h.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}const j5="modulepreload",y5=function(t){return"/"+t},sh={},co=function(s,a,r){let n=Promise.resolve();if(a&&a.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));n=Promise.allSettled(a.map(c=>{if(c=y5(c),c in sh)return;sh[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const p=document.createElement("link");if(p.rel=d?"stylesheet":j5,d||(p.as="script"),p.crossOrigin="",p.href=c,o&&p.setAttribute("nonce",o),document.head.appendChild(p),d)return new Promise((u,h)=>{p.addEventListener("load",u),p.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return n.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};function B0(t,s,a,r,n,i,l){const[o,c]=x.useState(""),[d,m]=x.useState(!1),[p,u]=x.useState(!1),[h,g]=x.useState(!1),[b,f]=x.useState(0),[j,y]=x.useState(!1),[v,w]=x.useState(!1),[S,C]=x.useState(0),E=async()=>{var I;const N=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),O=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(N||O){c(N||O),g(!!O);return}try{const{getConclusion:B}=await co(async()=>{const{getConclusion:M}=await import("./conclusionApi-CELRkQli.js");return{getConclusion:M}},__vite__mapDeps([0,1,2,3,4,5,6,7])),T=await B(t.requestId||s);T&&(T.aiGeneratedRemark||T.finalRemark)&&(c(T.finalRemark||T.aiGeneratedRemark||""),g(!!T.aiGeneratedRemark))}catch(B){((I=B==null?void 0:B.response)==null?void 0:I.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",B)}},R=async()=>{if(!v)try{m(!0),y(!1);const{generateConclusion:N}=await co(async()=>{const{generateConclusion:T}=await import("./conclusionApi-CELRkQli.js");return{generateConclusion:T}},__vite__mapDeps([0,1,2,3,4,5,6,7])),O=await N(t.requestId||s),I=b+1;if(f(I),!(O!=null&&O.aiGeneratedRemark)||O.aiGeneratedRemark.toLowerCase().includes("unable to generate")||O.aiGeneratedRemark.toLowerCase().includes("sorry")){const T=S+1;C(T),T>=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),c((O==null?void 0:O.aiGeneratedRemark)||""),g(!1);return}c(O.aiGeneratedRemark),g(!0),C(0),I>=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 O=S+1;C(O),g(!1),O>=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)}},k=async()=>{var O,I;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{u(!0);const{finalizeConclusion:B}=await co(async()=>{const{finalizeConclusion:T}=await import("./conclusionApi-CELRkQli.js");return{finalizeConclusion:T}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await B(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(B){i==null||i({success:!1,title:"Error",message:((I=(O=B.response)==null?void 0:O.data)==null?void 0:I.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{u(!1)}};return x.useEffect(()=>{var T;const N=(T=t==null?void 0:t.status)==null?void 0:T.toLowerCase();if(!((N==="approved"||N==="rejected"||N==="closed")&&a&&!o))return;const I=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),B=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);I||B?(c(I||B),g(!!B)):E()},[t==null?void 0:t.status,t==null?void 0:t.conclusionRemark,t==null?void 0:t.aiGeneratedConclusion,a,o]),{conclusionRemark:o,setConclusionRemark:c,conclusionLoading:d,conclusionSubmitting:p,aiGenerated:h,handleGenerateConclusion:R,handleFinalizeConclusion:k,generationAttempts:b,generationFailed:j,maxAttemptsReached:v}}function V0(t,s,a){const[r,n]=x.useState(!1),[i,l]=x.useState(!1),[o,c]=x.useState(!1),[d,m]=x.useState(!1),[p,u]=x.useState(!1),[h,g]=x.useState(!1),[b,f]=x.useState(null),[j,y]=x.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:p,setShowSkipApproverModal:u,showActionStatusModal:h,setShowActionStatusModal:g,skipApproverData:b,setSkipApproverData:f,actionStatus:j,setActionStatus:y,handleApproveConfirm:async R=>{var N,O;const k=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!k){alert("Approval level not found");return}await On(t,k,R||""),await new Promise(I=>setTimeout(I,500)),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(O=window==null?void 0:window.toast)==null||O.call(window,"Approved successfully")},handleRejectConfirm:async R=>{var N,O;if(!(R!=null&&R.trim())){alert("Comments & remarks are required");return}const k=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!k){alert("Approval level not found");return}await Tr(t,k,R.trim(),R.trim()),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(O=window==null?void 0:window.toast)==null||O.call(window,"Rejected successfully")},handleAddApprover:async(R,k,N)=>{var O,I;try{await Qp(t,R,k,N),await a(),c(!1),y==null||y({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${k}h TAT`}),g==null||g(!0)}catch(B){throw y==null||y({success:!1,title:"Failed to Add Approver",message:((I=(O=B==null?void 0:B.response)==null?void 0:O.data)==null?void 0:I.error)||"Failed to add approver. Please try again."}),g==null||g(!0),B}},handleSkipApprover:async R=>{var k,N;if(b)try{await N1(t,b.levelId,R),await a(),u(!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(O){throw y==null||y({success:!1,title:"Failed to Skip Approver",message:((N=(k=O==null?void 0:O.response)==null?void 0:k.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),O}},handleAddSpectator:async R=>{var k,N;try{await Xp(t,R),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(O){throw y==null||y({success:!1,title:"Failed to Add Spectator",message:((N=(k=O==null?void 0:O.response)==null?void 0:k.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),O}}}}function v5({requestId:t,request:s,onRefresh:a}){const[r,n]=x.useState(null),[i,l]=x.useState(!0),[o,c]=x.useState(null),m=!!(s==null?void 0:s.form16Submission),p=!!r&&r.status!=="withdrawn";x.useEffect(()=>{if(!t){l(!1);return}let g=!1;return(async()=>{try{const b=await Pp(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 u=async()=>{if(!(!t||!window.confirm("Cancel this Form 16 submission? The request will be marked as rejected."))){c("cancel");try{await jv(t),G.success("Submission cancelled"),a==null||a()}catch(g){G.error(g instanceof Error?g.message:"Failed to cancel submission")}finally{c(null)}}},h=async()=>{if(!(!t||!window.confirm("Mark this submission as resubmission needed? The dealer will need to resubmit Form 16."))){c("resubmit");try{await yv(t),G.success("Marked as resubmission needed"),a==null||a()}catch(g){G.error(g instanceof Error?g.message:"Failed to update")}finally{c(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(ie,{className:"pb-2",children:[e.jsxs(le,{className:"text-sm flex items-center gap-2 text-blue-800",children:[e.jsx(_t,{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(P,{variant:"outline",size:"sm",className:"w-full justify-start border-red-300 text-red-700 hover:bg-red-50",onClick:u,disabled:!!o,children:[o==="cancel"?e.jsx(ze,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(jt,{className:"w-3 h-3 mr-1"}),"Cancel submission"]}),e.jsxs(P,{variant:"outline",size:"sm",className:"w-full justify-start border-amber-300 text-amber-700 hover:bg-amber-50",onClick:h,disabled:!!o,children:[o==="resubmit"?e.jsx(ze,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(Wh,{className:"w-3 h-3 mr-1"}),"Resubmission needed"]})]})]})}const N5=t=>{const s=(t||"").toLowerCase();return s.includes("image")||s.includes("pdf")||s.includes("jpg")||s.includes("jpeg")||s.includes("png")||s.includes("gif")};function Or({document:t,onPreview:s,onDownload:a,showPreview:r=!0,testId:n="document-card"}){return e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors","data-testid":`${n}-${t.documentId}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Re,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900","data-testid":`${n}-name`,children:t.name}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${n}-metadata`,children:[t.size&&e.jsxs("span",{children:[t.size," • "]}),t.uploadedBy&&e.jsxs("span",{children:["Uploaded by ",t.uploadedBy," on "]}),bs(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&N5(t.fileType)&&s&&e.jsx(P,{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(vt,{className:"w-4 h-4"})}),a&&e.jsx(P,{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(Tt,{className:"w-4 h-4"})})]})]})}function w5({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l,isSpectator:o=!1}){var d,m,p,u;const c=((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:[c&&((m=(d=t==null?void 0:t.form16Submission)==null?void 0:d.previousDocuments)==null?void 0:m.length)>0&&e.jsxs(Z,{children:[e.jsxs(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2 text-sm sm:text-base text-amber-800",children:[e.jsx(Re,{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," ",(u=t==null?void 0:t.form16Submission)==null?void 0:u.quarter,")"]})]}),e.jsx(te,{children:e.jsx("div",{className:"space-y-4",children:(()=>{const h=new Map;for(const g of t.form16Submission.previousDocuments){const b=g.requestId||g.request_id,f=g.requestNumber||b;h.has(f)||h.set(f,[]),h.get(f).push(g)}return Array.from(h.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(Or,{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(ie,{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(le,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),c?"Current submission":"Request Documents"]}),e.jsx(ye,{className:"text-xs sm:text-sm mt-1",children:c?"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(P,{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(ys,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a?"Uploading...":t.status==="closed"?"Closed":"Upload",e.jsx("span",{className:"hidden sm:inline",children:t.status==="closed"?"":"Document"})]}),e.jsxs("p",{className:"text-xs text-gray-500 whitespace-nowrap",children:["Max ",r.maxFileSizeMB,"MB"]})]})]})}),e.jsx(te,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((h,g)=>e.jsx(Or,{document:h,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"})})]}),!c&&e.jsxs(Z,{children:[e.jsxs(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(zs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-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((h,g)=>e.jsx(Or,{document:{documentId:h.attachmentId||"",name:h.name,fileType:h.type||"",size:h.size?`${(h.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:h.size,uploadedBy:h.uploadedBy,uploadedAt:h.uploadedAt},onPreview:b=>i(b),onDownload:async b=>{const{downloadWorkNoteAttachment:f}=require("@/services/workflowApi");await f(b)},testId:"worknote-attachment"},h.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 C5=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"}}},ah=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending",icon:rt,iconColor:"text-yellow-600"};case"paused":return{color:"bg-gray-400 text-gray-100 border-gray-500",label:"paused",icon:ss,iconColor:"text-gray-600"};case"in-review":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"in-review",icon:Pt,iconColor:"text-blue-600"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:Be,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:Be,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:ss,iconColor:"text-gray-600"}}},S5=t=>{switch(t){case"approval":case"approved":return e.jsx(Be,{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(zs,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(Pt,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(ml,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Re,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(rt,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(ll,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(ss,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(Bt,{className:"w-5 h-5 text-gray-600"})}};function A5(t){const s=t==null?void 0:t.form16Submission;if(!s)return[];const a=[],r=Array.isArray(s.previousSubmissions)?s.previousSubmissions:[];for(const h of r){const g=h.requestNumber||h.requestId||"",b=h.submittedDate?new Date(h.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}),h.creditNoteNumber){const f=h.creditNoteIssueDate?new Date(h.creditNoteIssueDate).toISOString():b;a.push({type:"status_change",action:"Credit note issued",details:`Credit note ${h.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||""||"",c=(s.displayStatus||"").toLowerCase(),d=!!(s.ocrExtractedData&&typeof s.ocrExtractedData=="object"&&Object.keys(s.ocrExtractedData).length>0),m=!!s.creditNoteNumber,p=c==="balance mismatch"||l==="failed"&&!m||l==="failed"&&/mismatch|26as|value/i.test(o),u=c==="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:d?"Certificate data was extracted from the uploaded PDF.":"OCR extraction was performed on the uploaded document.",timestamp:i}),p?a.push({type:"rejection",action:"26AS matching",details:"Values of Form 16 did not match with 26AS. Please submit Form 16 with correct data.",timestamp:i}):u?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 h=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:h})}return a.sort((h,g)=>new Date(h.timestamp).getTime()-new Date(g.timestamp).getTime())}function T5({request:t}){const s=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",a=s?A5(t):[],r=t.auditTrail&&Array.isArray(t.auditTrail)?t.auditTrail:[],n=a.length>0?[...a,...r].sort((i,l)=>{const o=i.timestamp?new Date(i.timestamp).getTime():0,c=l.timestamp?new Date(l.timestamp).getTime():0;return o-c}):r;return e.jsxs(Z,{children:[e.jsxs(ie,{children:[e.jsxs(le,{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:S5(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:bs(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 z0({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsx(ht,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[a?e.jsx(Be,{className:"w-5 h-5 text-green-600"}):e.jsx(Je,{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(Be,{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(Dt,{children:e.jsx(P,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function H0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=x.useState(""),[l,o]=x.useState(!1),[c,d]=x.useState([]),[m,p]=x.useState(!1),[u,h]=x.useState(null),g=x.useRef(null),b=x.useRef(null),[f,j]=x.useState({open:!1,type:"error",email:"",message:""}),[y,v]=x.useState({open:!1,violations:[]}),[w,S]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});x.useEffect(()=>{t&&(async()=>{var O;try{const I=await ma("WORKFLOW_SHARING"),B=await ma("TAT_SETTINGS"),T=[...I,...B],M={};T.forEach(F=>{M[F.configKey]=F.configValue}),S({maxApprovalLevels:parseInt(M.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(M.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((O=M.ALLOW_ADD_SPECTATOR)==null?void 0:O.toLowerCase())==="true",maxSpectators:parseInt(M.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(I){console.error("Failed to load system policy:",I)}})()},[t]);const C=async()=>{var D,A;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 I=r.find(H=>(H.email||"").toLowerCase()===N);if(I){const H=((D=I.participantType)==null?void 0:D.toUpperCase())||"PARTICIPANT",$=I.name||N;if(H==="INITIATOR"){j({open:!0,type:"error",email:N,message:`${$} is the request initiator and cannot be added as a spectator.`});return}else if(H==="APPROVER"){j({open:!0,type:"error",email:N,message:`${$} is already an approver on this request and cannot be added as a spectator.`});return}else if(H==="SPECTATOR"){j({open:!0,type:"error",email:N,message:`${$} is already a spectator on this request.`});return}else{j({open:!0,type:"error",email:N,message:`${$} is already a participant on this request.`});return}}const B=[];w.allowSpectators||B.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const M=r.filter(H=>(H.participantType||"").toUpperCase()==="SPECTATOR").length;M>=w.maxSpectators&&B.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:M,maxValue:w.maxSpectators});const F=r.length+1;if(F>w.maxParticipants&&B.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:F,maxValue:w.maxParticipants}),B.length>0){v({open:!0,violations:B});return}if(!u||u.email.toLowerCase()!==N)try{const $=((A=(await va(N,1)).data)==null?void 0:A.data)||[];if($.length===0){j({open:!0,type:"not-found",email:N,message:""});return}const _=$[0];await ja({userId:_.userId,email:_.email,displayName:_.displayName,firstName:_.firstName,lastName:_.lastName,department:_.department,phone:_.phone,mobilePhone:_.mobilePhone,designation:_.designation,jobTitle:_.jobTitle,manager:_.manager,employeeId:_.employeeId,employeeNumber:_.employeeNumber,secondEmail:_.secondEmail,location:_.location})}catch(H){console.error("Failed to validate spectator:",H),j({open:!0,type:"error",email:N,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(N),i(""),h(null),s()}catch(H){console.error("Failed to add spectator:",H)}finally{o(!1)}},E=()=>{l||(i(""),h(null),d([]),p(!1),s())};x.useEffect(()=>{c.length>0&&b.current&&b.current.scrollTo({top:b.current.scrollHeight,behavior:"smooth"})},[c.length]),x.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const R=N=>{if(i(N),u&&u.email.toLowerCase()!==N.toLowerCase()&&h(null),g.current&&clearTimeout(g.current),!N||!N.startsWith("@")||N.length<2){d([]),p(!1);return}p(!0),g.current=setTimeout(async()=>{var O;try{const I=N.slice(1),T=((O=(await va(I,10)).data)==null?void 0:O.data)||[];d(T)}catch(I){console.error("Search failed:",I),d([])}finally{p(!1)}},300)},k=async N=>{try{await ja({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),h(N),d([]),p(!1)}catch(O){console.error("Failed to ensure user exists:",O),j({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(xt,{open:t,onOpenChange:E,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:E,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:l,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ht,{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(vt,{className:"w-5 h-5 text-purple-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:b,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a spectator to this request. They will receive notifications but cannot approve or reject."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(ul,{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=>R(N.target.value),className:"pl-10 h-11 border-gray-300",disabled:l,autoFocus:!0}),(m||c.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:m?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):c.length>0?e.jsx("ul",{className:"divide-y",children:c.map(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>k(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(N.displayName||N.email).split(" ").map(O=>O[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(P,{type:"button",variant:"outline",onClick:E,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(P,{type:"button",onClick:C,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(vt,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(xt,{open:f.open,onOpenChange:N=>j(O=>({...O,open:N})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:f.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Et,{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(dl,{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(Dt,{children:e.jsx(P,{onClick:()=>j(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(pi,{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 G0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=x.useState(""),[d,m]=x.useState(24),[p,u]=x.useState(null),[h,g]=x.useState(!1),[b,f]=x.useState([]),[j,y]=x.useState(!1),[v,w]=x.useState(null),S=x.useRef(null),C=x.useRef(null),[E,R]=x.useState({open:!1,type:"error",email:"",message:""}),k=n.filter(A=>A&&(A.status==="approved"||A.status==="rejected"||A.status==="skipped")),N=Math.max(1,k.length+1),O=Math.max(1,n.length+1),I=O>=N?Array.from({length:O-N+1},(A,H)=>N+H):[N];x.useEffect(()=>{I.length>0&&p===null&&u(I[0]||null)},[I.length,p]);const B=async()=>{var z,X;const A=o.trim().toLowerCase();if(!A){R({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A)){R({open:!0,type:"error",email:A,message:"Please enter a valid email address"});return}if(!d||d<=0){R({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(d>720){R({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!p){R({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(p0?Math.max(...n.map(W=>W.levelNumber),0):0,_=p>$?p:$+1;if(i&&_>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${p} would result in ${_} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:_,maxValue:i}]):R({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${$} level(s).`});return}const L=r.find(W=>(W.email||"").toLowerCase()===A);if(L){const W=((z=L.participantType)==null?void 0:z.toUpperCase())||"PARTICIPANT",U=L.name||A;if(W==="INITIATOR"){R({open:!0,type:"error",email:A,message:`${U} is the request initiator and cannot be added as an approver.`});return}else if(W==="APPROVER"){R({open:!0,type:"error",email:A,message:`${U} is already an approver on this request.`});return}else if(W==="SPECTATOR"){R({open:!0,type:"error",email:A,message:`${U} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{R({open:!0,type:"error",email:A,message:`${U} is already a participant on this request.`});return}}if(!v||v.email.toLowerCase()!==A)try{const U=((X=(await va(A,1)).data)==null?void 0:X.data)||[];if(U.length===0){R({open:!0,type:"not-found",email:A,message:""});return}const V=U[0];await ja({userId:V.userId,email:V.email,displayName:V.displayName,firstName:V.firstName,lastName:V.lastName,department:V.department,phone:V.phone,mobilePhone:V.mobilePhone,designation:V.designation,jobTitle:V.jobTitle,manager:V.manager,employeeId:V.employeeId,employeeNumber:V.employeeNumber,secondEmail:V.secondEmail,location:V.location})}catch(W){console.error("Failed to validate approver:",W),R({open:!0,type:"error",email:A,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(A,d,p),c(""),m(24),u(null),w(null),s()}catch(W){console.error("Failed to add approver:",W)}finally{g(!1)}},T=()=>{h||(c(""),m(24),u(null),w(null),f([]),y(!1),s())},M=A=>{const H=A.toLowerCase();return H==="approved"?e.jsx(Be,{className:"w-4 h-4 text-green-600"}):H==="rejected"?e.jsx(Ct,{className:"w-4 h-4 text-red-600"}):H==="skipped"?e.jsx(Je,{className:"w-4 h-4 text-orange-600"}):H==="in-review"||H==="pending"?e.jsx(rt,{className:"w-4 h-4 text-blue-600"}):e.jsx(rt,{className:"w-4 h-4 text-gray-400"})};x.useEffect(()=>{b.length>0&&C.current&&C.current.scrollTo({top:C.current.scrollHeight,behavior:"smooth"})},[b.length]),x.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const F=A=>{if(c(A),v&&v.email.toLowerCase()!==A.toLowerCase()&&w(null),S.current&&clearTimeout(S.current),!A||!A.startsWith("@")||A.length<2){f([]),y(!1);return}y(!0),S.current=setTimeout(async()=>{var H;try{const $=A.slice(1),L=((H=(await va($,10)).data)==null?void 0:H.data)||[];f(L)}catch($){console.error("Search failed:",$),f([])}finally{y(!1)}},300)},D=async A=>{try{await ja({userId:A.userId,email:A.email,displayName:A.displayName,firstName:A.firstName,lastName:A.lastName,department:A.department,phone:A.phone,mobilePhone:A.mobilePhone,designation:A.designation,jobTitle:A.jobTitle,manager:A.manager,employeeId:A.employeeId,employeeNumber:A.employeeNumber,secondEmail:A.secondEmail,location:A.location}),c(A.email),w(A),f([]),y(!1)}catch(H){console.error("Failed to ensure user exists:",H),R({open:!0,type:"error",email:A.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(xt,{open:t,onOpenChange:T,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:T,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:h,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ht,{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(qt,{className:"w-5 h-5 text-blue-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref: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(A=>A.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(A=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${A.status==="approved"?"bg-green-100 border border-green-200":A.status==="rejected"?"bg-red-100 border border-red-200":A.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:A.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:A.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[A.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[M(A.status),e.jsx(ae,{variant:"outline",className:`text-xs ${A.status==="approved"?"bg-green-50 text-green-700 border-green-300":A.status==="rejected"?"bg-red-50 text-red-700 border-red-300":A.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:A.status})]})]},A.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(se,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(He,{value:(p==null?void 0:p.toString())||"",onValueChange:A=>u(Number(A)),disabled:h,children:[e.jsx(We,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select level"})}),e.jsx(Ye,{children:I.map(A=>e.jsx(J,{value:A.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fs,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",A]}),A<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",A,")"]})]})},A))})]}),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(se,{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:d,onChange:A=>m(Number(A.target.value)),className:"h-11 border-gray-300 flex-1",disabled:h,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(rt,{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(ul,{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:A=>F(A.target.value),className:"pl-10 h-11 border-gray-300",disabled:h,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(A=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>D(A),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(A.displayName||A.email).split(" ").map(H=>H[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:A.displayName||[A.firstName,A.lastName].filter(Boolean).join(" ")||A.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:A.email}),A.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:A.designation})]})]})},A.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(P,{type:"button",variant:"outline",onClick:T,className:"flex-1 h-11 border-gray-300",disabled:h,children:"Cancel"}),e.jsxs(P,{type:"button",onClick:B,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:h||!o.trim()||!p||!d,children:[e.jsx(qt,{className:"w-4 h-4 mr-2"}),h?"Adding...":`Add at Level ${p||"?"}`]})]})]}),e.jsx(xt,{open:E.open,onOpenChange:A=>R(H=>({...H,open:A})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:E.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Et,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[E.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:E.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(dl,{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."]})})]}),E.type==="error"&&e.jsxs(e.Fragment,{children:[E.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:E.email}),"."]}),E.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:E.message})})]})]})})]}),e.jsx(Dt,{children:e.jsx(P,{onClick:()=>R(A=>({...A,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const k5=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"}},D5=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},R5=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 Ea(s)},F5=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",rh=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Re,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(Kh,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Re,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Re,{className:`${s} text-blue-600`}):a.includes("image")||a.includes("png")||a.includes("jpg")||a.includes("jpeg")||a.includes("gif")||a.includes("webp")?e.jsx(Di,{className:`${s} text-purple-600`}):e.jsx(ll,{className:`${s} text-gray-600`})};function W0({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:c=[],onAddApprover:d,maxApprovalLevels:m,onPolicyViolation:p}){const u=Ba(),h=t||u.requestId||"",[g,b]=x.useState(""),[f,j]=x.useState(""),[y,v]=x.useState(!1),[w,S]=x.useState([]),[C,E]=x.useState(!1),[R,k]=x.useState([]),[N,O]=x.useState(null),[I,B]=x.useState(null),[T,M]=x.useState(!1),[F,D]=x.useState(!1),[A,H]=x.useState(!1),[$,_]=x.useState({success:!0,title:"",message:""}),L=x.useRef(null),z=x.useRef(null),X=x.useRef(null),W=x.useRef(!1),[U,V]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[Q,ee]=x.useState({open:!1,errors:[]}),K=x.useMemo(()=>({id:h,title:n||"Request Details"}),[h,n]),[q,ue]=x.useState([]),Le=q.filter(ne=>ne.status==="online"),Ze=w.filter(ne=>ne.content.toLowerCase().includes(f.toLowerCase())||ne.user.name.toLowerCase().includes(f.toLowerCase())),De=x.useMemo(()=>o!==void 0?o:!N||q.length===0?!1:q.some(ne=>{const Ee=ne.userId||ne.user_id,oe=(ne.role||"").toString().toUpperCase(),Xe=(ne.participantType||ne.participant_type||"").toString().toUpperCase();return Ee===N&&(oe==="SPECTATOR"||Xe==="SPECTATOR")}),[o,N,q]);x.useEffect(()=>{},[q]),x.useEffect(()=>{!h||!N||s||(async()=>{try{const ne=await mn(h),Ee=Array.isArray(ne)?ne.map(oe=>{const Xe=oe.userId||oe.user_id;return{id:oe.noteId||oe.id||String(Math.random()),user:{name:oe.userName||"User",avatar:(oe.userName||"U").slice(0,2).toUpperCase(),role:oe.userRole||"Participant"},content:oe.message||"",timestamp:oe.createdAt||new Date().toISOString(),isCurrentUser:Xe===N,attachments:Array.isArray(oe.attachments)?oe.attachments.map(Ke=>({attachmentId:Ke.attachmentId||Ke.attachment_id,name:Ke.fileName||Ke.file_name||Ke.name,fileName:Ke.fileName||Ke.file_name||Ke.name,url:Ke.storageUrl||Ke.storage_url||Ke.url||"#",type:Ke.fileType||Ke.file_type||Ke.type||"file",fileType:Ke.fileType||Ke.file_type||Ke.type||"file",fileSize:Ke.fileSize||Ke.file_size})):void 0}}):[];S(Ee)}catch(ne){console.error("[WorkNoteChat] Failed to load messages:",ne)}})()},[h,N,s]);const _e=x.useMemo(()=>{const ne=[];return w.forEach(Ee=>{Ee.attachments&&Ee.attachments.length>0&&Ee.attachments.forEach(oe=>{ne.push({attachmentId:oe.attachmentId||oe.attachment_id,name:oe.fileName||oe.file_name||oe.name||"Untitled",fileName:oe.fileName||oe.file_name||oe.name||"Untitled",size:oe.fileSize||oe.file_size,type:oe.fileType||oe.file_type||oe.type||"file",uploadedBy:Ee.user.name,uploadedAt:Ee.timestamp,url:oe.storageUrl||oe.storage_url||oe.url||"#"})})}),ne},[w]);x.useEffect(()=>{i&&_e.length>=0&&i(_e)},[_e,i]);const Ue=x.useMemo(()=>q.map(ne=>({email:(ne.email||"").toLowerCase(),participantType:ne.role==="Initiator"?"INITIATOR":ne.role==="Approver"?"APPROVER":ne.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:ne.name})),[q]),re=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()}},fe=()=>{var ne;(ne=L.current)==null||ne.scrollIntoView({behavior:"smooth"})};x.useEffect(()=>{fe()},[w]);const Ce=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()}};x.useEffect(()=>{W.current||h&&(async()=>{try{const ne=await Is(h),Ee=Array.isArray(ne==null?void 0:ne.participants)?ne.participants:[];if(Ee.length===0)return;const oe=Ee.map(Qe=>{const it=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(ut=>ut[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ce(it.toString()),status:"offline",email:Qe.userEmail||Qe.user_email||"",permissions:["read","write","mention"],userId:qe}});W.current=!0,ue(oe);let Xe=0;const Ke=3,tt=()=>{X.current&&X.current.connected?(X.current.emit("request:online-users",{requestId:h}),Xe++,Xe()=>{h&&(W.current=!1)},[h]),x.useEffect(()=>{const ne=localStorage.getItem("userData");if(ne)try{const Ee=JSON.parse(ne),oe=(Ee==null?void 0:Ee.id)||(Ee==null?void 0:Ee.userId)||(Ee==null?void 0:Ee.user_id)||null;O(oe)}catch(Ee){console.error("[WorkNoteChat] Failed to parse userData:",Ee)}},[]),x.useEffect(()=>{(async()=>{try{const Ee=await ma("DOCUMENT_POLICY"),oe={};Ee.forEach(Qe=>{oe[Qe.configKey]=Qe.configValue});const Xe=parseInt(oe.MAX_FILE_SIZE_MB||"10"),tt=(oe.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Qe=>Qe.trim().toLowerCase());V({maxFileSizeMB:Xe,allowedFileTypes:tt})}catch(Ee){console.error("Failed to load document policy:",Ee)}})()},[]),x.useEffect(()=>{if(!N)return;let ne=h;return(async()=>{var Ee;try{const oe=await Is(h);(Ee=oe==null?void 0:oe.workflow)!=null&&Ee.requestId&&(ne=oe.workflow.requestId)}catch{}try{const oe=$r();r?ue(yt=>yt.map(It=>It.userId===N?{...It,status:"online"}:It)):(Eo(oe,ne,N),ue(yt=>yt.map(It=>It.userId===N?{...It,status:"online"}:It)));const Xe=yt=>{const pt=(yt==null?void 0:yt.note)||yt;if(!pt)return;const It=pt.noteId||pt.id;S(Ss=>{if(Ss.some(Lt=>Lt.id===It))return Ss;const as=pt.userName||pt.user_name||"User",Va=pt.userRole||pt.user_role,za=re(Va),pr=pt.userId||pt.user_id,Na={id:It||String(Date.now()),user:{name:as,avatar:as.split(" ").map(Lt=>Lt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:za},content:pt.message||"",timestamp:pt.createdAt||new Date().toISOString(),isCurrentUser:pr===N,attachments:Array.isArray(pt.attachments)?pt.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,Na]})},Ke=yt=>{ue(pt=>pt.length===0||!pt.find(as=>as.userId===yt.userId)?pt:pt.map(as=>as.userId===yt.userId?{...as,status:"online"}:as))},tt=yt=>{yt.userId!==N&&ue(pt=>pt.length===0||!pt.find(as=>as.userId===yt.userId)?pt:pt.map(as=>as.userId===yt.userId?{...as,status:"offline"}:as))},Qe=yt=>{ue(pt=>pt.length===0?pt:pt.map(Ss=>{const as=Ss.userId||"";if(as===N)return{...Ss,status:"online"};const za=yt.userIds.includes(as);return{...Ss,status:za?"online":"offline"}}))},it=()=>{ue(yt=>yt.map(It=>It.userId===N?{...It,status:"online"}:It)),r||Eo(oe,ne,N),W.current&&(oe.emit("request:online-users",{requestId:ne}),setTimeout(()=>oe.emit("request:online-users",{requestId:ne}),300),setTimeout(()=>oe.emit("request:online-users",{requestId:ne}),800))},qe=yt=>{console.error("[WorkNoteChat] ❌ Socket error:",yt)},ut=yt=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",yt),ue(pt=>pt.map(It=>It.userId===N?It:{...It,status:"offline"}))},Us=yt=>{yt.includes("presence")||yt.includes("worknote")||yt.includes("request")};oe.on("connect",it),oe.on("disconnect",ut),oe.on("error",qe),oe.on("worknote:new",Xe),oe.on("presence:join",Ke),oe.on("presence:leave",tt),oe.on("presence:online",Qe),oe.onAny(Us),X.current=oe,oe.connected&&W.current&&(oe.emit("request:online-users",{requestId:ne}),setTimeout(()=>{oe.emit("request:online-users",{requestId:ne})},300),setTimeout(()=>{oe.emit("request:online-users",{requestId:ne})},800),setTimeout(()=>{oe.emit("request:online-users",{requestId:ne})},1500));const is=()=>{oe.off("connect",it),oe.off("disconnect",ut),oe.off("error",qe),oe.off("worknote:new",Xe),oe.off("presence:join",Ke),oe.off("presence:leave",tt),oe.off("presence:online",Qe),oe.offAny(Us),r||mp(oe,ne),X.current=null};window.__wn_cleanup=is}catch{}})(),()=>{var Ee;try{(Ee=window.__wn_cleanup)==null||Ee.call(window)}catch{}}},[h,N,r]);const Ae=async()=>{if(g.trim()||R.length>0){const ne=nt(g),Ee=ne.map(Ke=>{const tt=q.find(Qe=>Qe.name.toLowerCase().includes(Ke.toLowerCase()));return tt==null?void 0:tt.userId}).filter(Boolean),oe=R.map(Ke=>({name:Ke.name,url:URL.createObjectURL(Ke),type:Ke.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:oe.length>0?oe:void 0,isCurrentUser:!0};if(a)try{await a(g,R)}catch{}else try{await Kp(h,{message:g,mentions:Ee},R);const Ke=await mn(h),tt=Array.isArray(Ke)?Ke.map(Qe=>{const it=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:it===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(Ke=>[...Ke,Xe])}b(""),k([])}};x.useEffect(()=>{if(s&&Array.isArray(s))try{const Ee=s.filter(oe=>(oe.type||"").toLowerCase()!=="sla_warning").map(oe=>{var Ke;if(oe.type||oe.activityType||oe.isSystem)return{id:oe.id||`activity-${oe.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:oe.details||oe.action||oe.content||"",timestamp:oe.timestamp||oe.createdAt||oe.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const tt=oe.userName||oe.user_name||((Ke=oe.user)==null?void 0:Ke.name)||"User",Qe=oe.userRole||oe.user_role,it=re(Qe),qe=oe.userId||oe.user_id;return{id:oe.noteId||oe.note_id||oe.id||String(Math.random()),user:{name:tt,avatar:tt.split(" ").map(ut=>ut[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:it},content:oe.message||oe.content||"",timestamp:oe.createdAt||oe.created_at||oe.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(oe.attachments)?oe.attachments.map(ut=>({attachmentId:ut.attachmentId||ut.attachment_id,name:ut.fileName||ut.file_name||ut.name,fileName:ut.fileName||ut.file_name||ut.name,url:ut.storageUrl||ut.storage_url||ut.url||"#",type:ut.fileType||ut.file_type||ut.type||"file",fileType:ut.fileType||ut.file_type||ut.type||"file",fileSize:ut.fileSize||ut.file_size})):void 0,isCurrentUser:qe===N}}}).sort((oe,Xe)=>new Date(oe.timestamp).getTime()-new Date(Xe.timestamp).getTime());S(Ee)}catch(ne){console.error("[WorkNoteChat] Error mapping messages:",ne)}else(async()=>{try{const ne=await mn(h),Ee=Array.isArray(ne)?ne.map(oe=>{const Xe=oe.userName||oe.user_name||"User",Ke=oe.userRole||oe.user_role,tt=re(Ke),Qe=oe.userId||oe.user_id;return{id:oe.noteId||oe.note_id||oe.id||String(Math.random()),user:{name:Xe,avatar:Xe.split(" ").map(it=>it[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:tt},content:oe.message||"",timestamp:oe.createdAt||oe.created_at||new Date().toISOString(),attachments:Array.isArray(oe.attachments)?oe.attachments.map(it=>({attachmentId:it.attachmentId||it.attachment_id,name:it.fileName||it.file_name||it.name,fileName:it.fileName||it.file_name||it.name,url:it.storageUrl||it.storage_url||it.url||"#",type:it.fileType||it.file_type||it.type||"file",fileType:it.fileType||it.file_type||it.type||"file",fileSize:it.fileSize||it.file_size})):void 0,isCurrentUser:Qe===N}}):[];S(Ee)}catch(ne){console.error("[WorkNoteChat] Error loading work notes:",ne)}})()},[s,h,q]);const ce=ne=>{const Ee=U.maxFileSizeMB*1024*1024;if(ne.size>Ee)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${U.maxFileSizeMB}MB. Current size: ${(ne.size/(1024*1024)).toFixed(2)}MB`};const oe=ne.name.toLowerCase(),Xe=oe.substring(oe.lastIndexOf(".")+1);return U.allowedFileTypes.includes(Xe)?{valid:!0}:{valid:!1,reason:`File type "${Xe}" is not allowed. Allowed types: ${U.allowedFileTypes.join(", ")}`}},pe=ne=>{if(!ne.target.files||ne.target.files.length===0)return;const Ee=Array.from(ne.target.files),oe=[],Xe=[];Ee.forEach(Ke=>{const tt=ce(Ke);tt.valid?Xe.push(Ke):oe.push({fileName:Ke.name,reason:tt.reason||"Unknown validation error"})}),oe.length>0&&ee({open:!0,errors:oe}),Xe.length>0&&(k(Ke=>[...Ke,...Xe]),Xe.length{k(Ee=>Ee.filter((oe,Xe)=>Xe!==ne)),z.current&&(z.current.value="")},de=ne=>{b(Ee=>Ee+ne),v(!1)},me=()=>{var ne;(ne=z.current)==null||ne.click()},Ne=async ne=>{var Ee,oe;try{await Xp(h,ne);const Xe=await Is(h),Ke=Array.isArray(Xe==null?void 0:Xe.participants)?Xe.participants:[];if(Ke.length){const tt=Ke.map(Qe=>{const it=Qe.participantType||Qe.participant_type||"participant",qe=Qe.userId||Qe.user_id||"",ut=Qe.userName||Qe.user_name||Qe.userEmail||Qe.user_email||"User",Us=Qe.userEmail||Qe.user_email||"",is=ut.split(" ").map(yt=>yt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:ut,avatar:is,role:Ce(it),status:"offline",email:Us,lastSeen:void 0,permissions:["read"],userId:qe}});ue(tt),X.current&&X.current.connected&&X.current.emit("request:online-users",{requestId:h})}M(!1),_({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),H(!0)}catch(Xe){throw console.error("Failed to add spectator:",Xe),_({success:!1,title:"Failed to Add Spectator",message:((oe=(Ee=Xe==null?void 0:Xe.response)==null?void 0:Ee.data)==null?void 0:oe.error)||"Failed to add spectator. Please try again."}),H(!0),Xe}},Oe=async(ne,Ee,oe)=>{var Xe,Ke;if(d)await d(ne,Ee,oe),D(!1);else try{await Qp(h,ne,Ee,oe);const tt=await Is(h),Qe=Array.isArray(tt==null?void 0:tt.participants)?tt.participants:[];if(Qe.length){const it=Qe.map(qe=>{const ut=qe.participantType||qe.participant_type||"participant",Us=qe.userId||qe.user_id||"",is=qe.userName||qe.user_name||qe.userEmail||qe.user_email||"User",yt=qe.userEmail||qe.user_email||"",pt=is.split(" ").map(It=>It[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:is,avatar:pt,role:Ce(ut),status:"offline",email:yt,lastSeen:void 0,permissions:["read"],userId:Us}});ue(it),X.current&&X.current.connected&&X.current.emit("request:online-users",{requestId:h})}D(!1),_({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${oe} with ${Ee}h TAT`}),H(!0)}catch(tt){throw console.error("Failed to add approver:",tt),_({success:!1,title:"Failed to Add Approver",message:((Ke=(Xe=tt==null?void 0:tt.response)==null?void 0:Xe.data)==null?void 0:Ke.error)||"Failed to add approver. Please try again."}),H(!0),tt}},st=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],nt=ne=>{const Ee=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,oe=[];let Xe;for(;(Xe=Ee.exec(ne))!==null;)if(Xe[1]){const Ke=Xe.index+Xe[0].length,tt=ne.slice(Ke),Qe=ne[Ke];(tt.startsWith("@")||!Qe||/\s|[.,!?;:]|@/.test(Qe))&&oe.push(Xe[1].trim())}return oe},St=ne=>{ne.key==="Enter"&&!ne.shiftKey&&(ne.preventDefault(),Ae())},Mt=(ne,Ee)=>{S(oe=>oe.map(Xe=>{if(Xe.id===ne){const Ke=Xe.reactions||[],tt=Ke.find(Qe=>Qe.emoji===Ee);if(tt)if(tt.users.includes("You")){if(tt.users=tt.users.filter(Qe=>Qe!=="You"),tt.users.length===0)return{...Xe,reactions:Ke.filter(Qe=>Qe.emoji!==Ee)}}else tt.users.push("You");else Ke.push({emoji:Ee,users:["You"]});return{...Xe,reactions:Ke}}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(zs,{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:K.title}),e.jsx(ae,{variant:"outline",className:"text-xs shrink-0",children:t})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:e.jsxs("div",{className:"flex -space-x-2",children:[Le.slice(0,3).map((ne,Ee)=>e.jsx(cs,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(ds,{className:"bg-blue-500 text-white text-xs font-semibold",children:ne.avatar})},Ee)),Le.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:["+",Le.length-3]})]})}),e.jsx(P,{variant:"outline",size:"sm",onClick:()=>E(!C),className:"lg:hidden",children:e.jsx(qt,{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(Jt,{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:[Ze.map(ne=>{const Ee=ne.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${ne.isSystem?"justify-center":Ee?"justify-end":""}`,children:[!ne.isSystem&&!Ee&&e.jsx(cs,{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(ds,{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:`${Ee?"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:bs(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 ${Ee?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[ne.user.name," ",Ee&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(ae,{variant:"outline",className:"text-xs flex-shrink-0",children:ne.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(rt,{className:"w-3 h-3"}),bs(ne.timestamp)]}),ne.isHighPriority&&e.jsxs(ae,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(yj,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${Ee?"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:R5(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((oe,Xe)=>{const Ke=oe.fileSize||oe.file_size,tt=oe.fileName||oe.file_name||oe.name,Qe=oe.fileType||oe.file_type||oe.type||"",it=oe.attachmentId||oe.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(rh,{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}),Ke&&e.jsx("p",{className:"text-xs text-gray-500",children:F5(Ke)})]}),it&&(()=>{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(P,{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 ut=A1(it);B({fileName:tt,fileType:Qe,fileUrl:ut,fileSize:Ke,attachmentId:it})},title:"Preview file",children:e.jsx(vt,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(P,{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(),!it){G.error("Cannot download: Attachment ID missing");return}try{await Du(it)}catch{G.error("Failed to download file")}},title:"Download file",children:e.jsx(Tt,{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((oe,Xe)=>e.jsxs("button",{onClick:()=>Mt(ne.id,oe.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${oe.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:oe.emoji}),e.jsx("span",{className:"text-xs font-medium",children:oe.users.length})]},Xe)),e.jsx(P,{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(ms,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!ne.isSystem&&Ee&&e.jsx(cs,{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(ds,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:ne.user.avatar})})]},ne.id)}),e.jsx("div",{ref:L})]})}),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:z,onChange:pe,className:"hidden",multiple:!0,accept:U.allowedFileTypes.map(ne=>`.${ne}`).join(",")}),R.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:R.map((ne,Ee)=>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(rh,{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(P,{variant:"ghost",size:"sm",onClick:()=>Te(Ee),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"})})]},Ee))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const ne=g.lastIndexOf("@"),Ee=ne>=0;if(!Ee)return null;const oe=g.slice(ne+1),Xe=oe.trim(),Ke=oe.endsWith(" "),tt=Xe.length>0,Qe=Xe.includes(" ")&&!Ke,it=Ke&&tt;if(!(Ee&&oe.length<=20&&!Qe&&!it))return null;const ut=Xe.toLowerCase(),Us=q.filter(is=>is.userId===N?!1:ut?is.name.toLowerCase().includes(ut):!0);return e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border-2 border-blue-300 rounded-lg shadow-2xl p-3 z-[100] w-full sm:max-w-md",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 mb-2",children:"💬 Mention someone"}),e.jsx("div",{className:"max-h-60 overflow-y-auto space-y-1",children:Us.length>0?Us.map((is,yt)=>e.jsxs("button",{type:"button",onClick:pt=>{pt.preventDefault(),pt.stopPropagation();const It=g.lastIndexOf("@"),Ss=g.slice(0,It);b(Ss+"@"+is.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(cs,{className:"h-10 w-10",children:e.jsx(ds,{className:`text-white text-sm font-semibold ${is.role==="Initiator"?"bg-green-600":is.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:is.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:is.name}),e.jsx("p",{className:"text-xs text-gray-600",children:is.role})]})]},yt)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:ut?`No participants found matching "${ut}"`:"No other participants available"})})]})})(),e.jsx($s,{placeholder:De?"Spectators cannot send messages":"Type your message... Use @username to mention someone",value:g,onChange:ne=>b(ne.target.value),onKeyPress:St,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:De}),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(P,{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:st.map((ne,Ee)=>e.jsx("button",{onClick:()=>de(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},Ee))})]})]}),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(P,{variant:"ghost",size:"sm",onClick:me,disabled:De,title:De?"Spectators cannot attach files":"Attach file",children:e.jsx(ll,{className:"h-4 w-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>v(!y),disabled:De,title:De?"Spectators cannot add emojis":"Add emoji",children:e.jsx(vj,{className:"h-4 w-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>b(ne=>ne+"@"),disabled:De,title:De?"Spectators cannot mention users":"Mention someone",children:e.jsx(ul,{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(P,{onClick:Ae,disabled:!g.trim()&&R.length===0||De,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:De?"Spectators cannot send messages":"Send",children:[e.jsx(Yh,{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:()=>E(!1)}),e.jsxs("div",{className:` + `),()=>{f.contains(b)&&f.removeChild(b)}},[s]),e.jsx(z2,{isPresent:s,childRef:i,sizeRef:l,children:x.cloneElement(t,{ref:c})})}const G2=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=Lc(W2),m=x.useId();let p=!0,u=x.useMemo(()=>(p=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:h=>{d.set(h,!0);for(const g of d.values())if(!g)return;r&&r()},register:h=>(d.set(h,!1),()=>d.delete(h))}),[a,d,r]);return i&&p&&(u={...u}),x.useMemo(()=>{d.forEach((h,g)=>d.set(g,!1))},[a]),x.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(H2,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(wl.Provider,{value:u,children:t})};function W2(){return new Map}function Qg(t=!0){const s=x.useContext(wl);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=x.useId();x.useEffect(()=>{if(t)return n(i)},[t]);const l=x.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const wi=t=>t.key||"";function qu(t){const s=[];return x.Children.forEach(t,a=>{x.isValidElement(a)&&s.push(a)}),s}const Cl=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",root:c})=>{const[d,m]=Qg(l),p=x.useMemo(()=>qu(t),[t]),u=l&&!d?[]:p.map(wi),h=x.useRef(!0),g=x.useRef(p),b=Lc(()=>new Map),[f,j]=x.useState(p),[y,v]=x.useState(p);rg(()=>{h.current=!1,g.current=p;for(let C=0;C{const E=wi(C),R=l&&!d?!1:p===y||u.includes(E),k=()=>{if(b.has(E))b.set(E,!0);else return;let N=!0;b.forEach(O=>{O||(N=!1)}),N&&(S==null||S(),v(g.current),l&&(m==null||m()),r&&r())};return e.jsx(G2,{isPresent:R,initial:!h.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:R?void 0:k,anchorX:o,children:C},E)})})},Xg=x.createContext({strict:!1}),ex={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"]},hn={};for(const t in ex)hn[t]={isEnabled:s=>ex[t].some(a=>!!s[a])};function Y2(t){for(const s in t)hn[s]={...hn[s],...t[s]}}const K2=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 Zi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||K2.has(t)}let Jg=t=>!Zi(t);function Q2(t){typeof t=="function"&&(Jg=s=>s.startsWith("on")?!Zi(s):t(s))}try{Q2(require("@emotion/is-prop-valid").default)}catch{}function X2(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(Jg(n)||a===!0&&Zi(n)||!s&&!Zi(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Sl=x.createContext({});function Al(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function ei(t){return typeof t=="string"||Array.isArray(t)}const ld=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],od=["initial",...ld];function Tl(t){return Al(t.animate)||od.some(s=>ei(t[s]))}function Zg(t){return!!(Tl(t)||t.variants)}function J2(t,s){if(Tl(t)){const{initial:a,animate:r}=t;return{initial:a===!1||ei(a)?a:void 0,animate:ei(r)?r:void 0}}return t.inherit!==!1?s:{}}function Z2(t){const{initial:s,animate:a}=J2(t,x.useContext(Sl));return x.useMemo(()=>({initial:s,animate:a}),[tx(s),tx(a)])}function tx(t){return Array.isArray(t)?t.join(" "):t}const ti={};function q2(t){for(const s in t)ti[s]=t[s],Wc(s)&&(ti[s].isCSSVariable=!0)}function qg(t,{layout:s,layoutId:a}){return wn.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!ti[t]||t==="opacity")}const eS={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},tS=Nn.length;function sS(t,s,a){let r="",n=!0;for(let i=0;i({style:{},transform:{},transformOrigin:{},vars:{}});function e0(t,s,a){for(const r in s)!Ls(s[r])&&!qg(r,a)&&(t[r]=s[r])}function aS({transformTemplate:t},s){return x.useMemo(()=>{const a=dd();return cd(a,s,t),Object.assign({},a.vars,a.style)},[s])}function rS(t,s){const a=t.style||{},r={};return e0(r,a,t),Object.assign(r,aS(t,s)),r}function nS(t,s){const a={},r=rS(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 iS={offset:"stroke-dashoffset",array:"stroke-dasharray"},lS={offset:"strokeDashoffset",array:"strokeDasharray"};function oS(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?iS:lS;t[i.offset]=ot.transform(-r);const l=ot.transform(s),o=ot.transform(a);t[i.array]=`${l} ${o}`}function t0(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(cd(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:p,style:u}=t;p.transform&&(u.transform=p.transform,delete p.transform),(u.transform||p.transformOrigin)&&(u.transformOrigin=p.transformOrigin??"50% 50%",delete p.transformOrigin),u.transform&&(u.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&&oS(p,n,i,l,!1)}const s0=()=>({...dd(),attrs:{}}),a0=t=>typeof t=="string"&&t.toLowerCase()==="svg";function cS(t,s,a,r){const n=x.useMemo(()=>{const i=s0();return t0(i,s,a0(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};e0(i,t.style,t),n.style={...i,...n.style}}return n}const dS=["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 md(t){return typeof t!="string"||t.includes("-")?!1:!!(dS.indexOf(t)>-1||/[A-Z]/u.test(t))}function mS(t,s,a,{latestValues:r},n,i=!1){const o=(md(t)?cS:nS)(s,r,n,t),c=X2(s,typeof t=="string",i),d=t!==x.Fragment?{...c,...o,ref:a}:{},{children:m}=s,p=x.useMemo(()=>Ls(m)?m.get():m,[m]);return x.createElement(t,{...d,children:p})}function sx(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function ud(t,s,a,r){if(typeof s=="function"){const[n,i]=sx(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]=sx(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Li(t){return Ls(t)?t.get():t}function uS({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:xS(a,r,n,t),renderState:s()}}function xS(t,s,a,r){const n={},i=r(t,{});for(const u in i)n[u]=Li(i[u]);let{initial:l,animate:o}=t;const c=Tl(t),d=Zg(t);s&&d&&!c&&t.inherit!==!1&&(l===void 0&&(l=s.initial),o===void 0&&(o=s.animate));let m=a?a.initial===!1:!1;m=m||l===!1;const p=m?o:l;if(p&&typeof p!="boolean"&&!Al(p)){const u=Array.isArray(p)?p:[p];for(let h=0;h(s,a)=>{const r=x.useContext(Sl),n=x.useContext(wl),i=()=>uS(t,s,r,n);return a?i():Lc(i)};function xd(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(Ls(r[l])||s.style&&Ls(s.style[l])||qg(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const hS=r0({scrapeMotionValuesFromProps:xd,createRenderState:dd});function n0(t,s,a){const r=xd(t,s,a);for(const n in t)if(Ls(t[n])||Ls(s[n])){const i=Nn.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const pS=r0({scrapeMotionValuesFromProps:n0,createRenderState:s0}),gS=Symbol.for("motionComponentSymbol");function sn(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function fS(t,s,a){return x.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):sn(a)&&(a.current=r))},[s])}const hd=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),bS="framerAppearId",i0="data-"+hd(bS),l0=x.createContext({});function jS(t,s,a,r,n){var b,f;const{visualElement:i}=x.useContext(Sl),l=x.useContext(Xg),o=x.useContext(wl),c=x.useContext(id).reducedMotion,d=x.useRef(null);r=r||l.renderer,!d.current&&r&&(d.current=r(t,{visualState:s,parent:i,props:a,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:c}));const m=d.current,p=x.useContext(l0);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&yS(d.current,a,n,p);const u=x.useRef(!1);x.useInsertionEffect(()=>{m&&u.current&&m.update(a,o)});const h=a[i0],g=x.useRef(!!h&&!((b=window.MotionHandoffIsComplete)!=null&&b.call(window,h))&&((f=window.MotionHasOptimisedAnimation)==null?void 0:f.call(window,h)));return rg(()=>{m&&(u.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),x.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var j;(j=window.MotionHandoffMarkAsComplete)==null||j.call(window,h)}),g.current=!1),m.enteringChildren=void 0)}),m}function yS(t,s,a,r){const{layoutId:n,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:o0(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&sn(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function o0(t){if(t)return t.options.allowProjection!==!1?t.projection:o0(t.parent)}function eo(t,{forwardMotionProps:s=!1}={},a,r){a&&Y2(a);const n=md(t)?pS:hS;function i(o,c){let d;const m={...x.useContext(id),...o,layoutId:vS(o)},{isStatic:p}=m,u=Z2(o),h=n(o,p);if(!p&&Oc){NS();const g=wS(m);d=g.MeasureLayout,u.visualElement=jS(t,h,m,r,g.ProjectionNode)}return e.jsxs(Sl.Provider,{value:u,children:[d&&u.visualElement?e.jsx(d,{visualElement:u.visualElement,...m}):null,mS(t,o,fS(h,u.visualElement,c),h,p,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=x.forwardRef(i);return l[gS]=t,l}function vS({layoutId:t}){const s=x.useContext(Mc).id;return s&&t!==void 0?s+"-"+t:t}function NS(t,s){x.useContext(Xg).strict}function wS(t){const{drag:s,layout:a}=hn;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 CS(t,s){if(typeof Proxy>"u")return eo;const a=new Map,r=(i,l)=>eo(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,eo(l,void 0,t,s)),a.get(l))})}function c0({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function SS({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function AS(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 to(t){return t===void 0||t===1}function Qo({scale:t,scaleX:s,scaleY:a}){return!to(t)||!to(s)||!to(a)}function kr(t){return Qo(t)||d0(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function d0(t){return ax(t.x)||ax(t.y)}function ax(t){return t&&t!=="0%"}function qi(t,s,a){const r=t-a,n=s*r;return a+n}function rx(t,s,a,r,n){return n!==void 0&&(t=qi(t,n,r)),qi(t,a,r)+s}function Xo(t,s=0,a=1,r,n){t.min=rx(t.min,s,a,r,n),t.max=rx(t.max,s,a,r,n)}function m0(t,{x:s,y:a}){Xo(t.x,s.translate,s.scale,s.originPoint),Xo(t.y,a.translate,a.scale,a.originPoint)}const nx=.999999999999,ix=1.0000000000001;function TS(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,l;for(let o=0;onx&&(s.x=1),s.ynx&&(s.y=1)}function an(t,s){t.min=t.min+s,t.max=t.max+s}function lx(t,s,a,r,n=.5){const i=ns(t.min,t.max,n);Xo(t,s,a,i,r)}function rn(t,s){lx(t.x,s.x,s.scaleX,s.scale,s.originX),lx(t.y,s.y,s.scaleY,s.scale,s.originY)}function u0(t,s){return c0(AS(t.getBoundingClientRect(),s))}function kS(t,s,a){const r=u0(t,a),{scroll:n}=s;return n&&(an(r.x,n.offset.x),an(r.y,n.offset.y)),r}const ox=()=>({translate:0,scale:1,origin:0,originPoint:0}),nn=()=>({x:ox(),y:ox()}),cx=()=>({min:0,max:0}),hs=()=>({x:cx(),y:cx()}),Jo={current:null},x0={current:!1};function DS(){if(x0.current=!0,!!Oc)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>Jo.current=t.matches;t.addEventListener("change",s),s()}else Jo.current=!1}const RS=new WeakMap;function FS(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,xn(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,xn(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const dx=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class IS{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=td,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 u=ta.now();this.renderScheduledAtthis.bindToMotionValue(n,r)),x0.current||DS(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Jo.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),dr(this.notifyUpdate),dr(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=wn.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&es.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 hn){const a=hn[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):hs()}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=xn(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"&&(ng(r)||lg(r))?r=parseFloat(r):!U2(r)&&mr.test(a)&&(r=Vg(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=ud(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 zc),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){rd.render(this.render)}}class h0 extends IS{constructor(){super(...arguments),this.KeyframeResolver=k2}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 p0(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 PS(t){return window.getComputedStyle(t)}class ES extends h0{constructor(){super(...arguments),this.type="html",this.renderInstance=p0}readValueFromInstance(s,a){var r;if(wn.has(a))return(r=this.projection)!=null&&r.isProjecting?Vo(a):YC(s,a);{const n=PS(s),i=(Wc(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return u0(s,a)}build(s,a,r){cd(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return xd(s,a,r)}}const g0=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 _S(t,s,a,r){p0(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(g0.has(n)?n:hd(n),s.attrs[n])}class MS extends h0{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=hs}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(wn.has(a)){const r=Bg(a);return r&&r.default||0}return a=g0.has(a)?a:hd(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return n0(s,a,r)}build(s,a,r){t0(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){_S(s,a,r,n)}mount(s){this.isSVGTag=a0(s.tagName),super.mount(s)}}const LS=(t,s)=>md(t)?new MS(s):new ES(s,{allowProjection:t!==x.Fragment});function un(t,s,a){const r=t.getProps();return ud(r,s,a!==void 0?a:r.custom,t)}const Zo=t=>Array.isArray(t);function OS(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,xn(a))}function $S(t){return Zo(t)?t[t.length-1]||0:t}function US(t,s){const a=un(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=$S(i[l]);OS(t,l,o)}}function BS(t){return!!(Ls(t)&&t.add)}function qo(t,s){const a=t.getValue("willChange");if(BS(a))return a.add(s);if(!a&&Qa.WillChange){const r=new Qa.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function f0(t){return t.props[i0]}const VS=t=>t!==null;function zS(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(VS),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const HS={type:"spring",stiffness:500,damping:25,restSpeed:10},GS=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),WS={type:"keyframes",duration:.8},YS={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},KS=(t,{keyframes:s})=>s.length>2?WS:wn.has(t)?t.startsWith("scale")?GS(s[1]):HS:YS;function QS({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:l,repeatDelay:o,from:c,elapsed:d,...m}){return!!Object.keys(m).length}const pd=(t,s,a,r={},n,i)=>l=>{const o=sd(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-_a(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-d,onUpdate:u=>{s.set(u),o.onUpdate&&o.onUpdate(u)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:t,motionValue:s,element:i?void 0:n};QS(o)||Object.assign(m,KS(t,m)),m.duration&&(m.duration=_a(m.duration)),m.repeatDelay&&(m.repeatDelay=_a(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let p=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(Yo(m),m.delay===0&&(p=!0)),(Qa.instantAnimations||Qa.skipAnimations)&&(p=!0,Yo(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,p&&!i&&s.get()!==void 0){const u=zS(m.keyframes,o);if(u!==void 0){es.update(()=>{m.onUpdate(u),m.onComplete()});return}}return o.isSync?new ed(m):new g2(m)};function XS({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function b0(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in o){const p=t.getValue(m,t.latestValues[m]??null),u=o[m];if(u===void 0||d&&XS(d,m))continue;const h={delay:a,...sd(i||{},m)},g=p.get();if(g!==void 0&&!p.isAnimating&&!Array.isArray(u)&&u===g&&!h.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const j=f0(t);if(j){const y=window.MotionHandoffAnimation(j,m,es);y!==null&&(h.startTime=y,b=!0)}}qo(t,m),p.start(pd(m,p,u,t.shouldReduceMotion&&Og.has(m)?{type:!1}:h,t,b));const f=p.animation;f&&c.push(f)}return l&&Promise.all(c).then(()=>{es.update(()=>{l&&US(t,l)})}),c}function j0(t,s,a,r=0,n=1){const i=Array.from(t).sort((d,m)=>d.sortNodePosition(m)).indexOf(s),l=t.size,o=(l-1)*r;return typeof a=="function"?a(i,l):n===1?i*r:o-i*r}function ec(t,s,a={}){var c;const r=un(t,s,a.type==="exit"?(c=t.presenceContext)==null?void 0:c.custom:void 0);let{transition:n=t.getDefaultTransition()||{}}=r||{};a.transitionOverride&&(n=a.transitionOverride);const i=r?()=>Promise.all(b0(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:p,staggerDirection:u}=n;return JS(t,s,d,m,p,u,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[d,m]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function JS(t,s,a=0,r=0,n=0,i=1,l){const o=[];for(const c of t.variantChildren)c.notify("AnimationStart",s),o.push(ec(c,s,{...l,delay:a+(typeof r=="function"?0:r)+j0(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function ZS(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>ec(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=ec(t,s,a);else{const n=typeof s=="function"?un(t,s,a.custom):s;r=Promise.all(b0(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function y0(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})=>ZS(t,a,r)))}function aA(t){let s=sA(t),a=mx(),r=!0;const n=c=>(d,m)=>{var u;const p=un(t,m,c==="exit"?(u=t.presenceContext)==null?void 0:u.custom:void 0);if(p){const{transition:h,transitionEnd:g,...b}=p;d={...d,...b,...g}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=v0(t.parent)||{},p=[],u=new Set;let h={},g=1/0;for(let f=0;fg&&w,k=!1;const N=Array.isArray(v)?v:[v];let O=N.reduce(n(j),{});S===!1&&(O={});const{prevResolvedValues:I={}}=y,B={...I,...O},T=D=>{R=!0,u.has(D)&&(k=!0,u.delete(D)),y.needsAnimating[D]=!0;const A=t.getValue(D);A&&(A.liveStyle=!1)};for(const D in B){const A=O[D],H=I[D];if(h.hasOwnProperty(D))continue;let $=!1;Zo(A)&&Zo(H)?$=!y0(A,H):$=A!==H,$?A!=null?T(D):u.add(D):A!==void 0&&u.has(D)?T(D):y.protectedKeys[D]=!0}y.prevProp=v,y.prevResolvedValues=O,y.isActive&&(h={...h,...O}),r&&t.blockInitialAnimation&&(R=!1);const M=C&&E;R&&(!M||k)&&p.push(...N.map(D=>{const A={type:j};if(typeof D=="string"&&r&&!M&&t.manuallyAnimateOnMount&&t.parent){const{parent:H}=t,$=un(H,D);if(H.enteringChildren&&$){const{delayChildren:_}=$.transition||{};A.delay=j0(H.enteringChildren,t,_)}}return{animation:D,options:A}}))}if(u.size){const f={};if(typeof d.initial!="boolean"){const j=un(t,Array.isArray(d.initial)?d.initial[0]:d.initial);j&&j.transition&&(f.transition=j.transition)}u.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&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(b=!1),r=!1,b?s(p):Promise.resolve()}function o(c,d){var p;if(a[c].isActive===d)return Promise.resolve();(p=t.variantChildren)==null||p.forEach(u=>{var h;return(h=u.animationState)==null?void 0:h.setActive(c,d)}),a[c].isActive=d;const m=l(c);for(const u in a)a[u].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=mx()}}}function rA(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!y0(s,t):!1}function Cr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function mx(){return{animate:Cr(!0),whileInView:Cr(),whileHover:Cr(),whileTap:Cr(),whileDrag:Cr(),whileFocus:Cr(),exit:Cr()}}class hr{constructor(s){this.isMounted=!1,this.node=s}update(){}}class nA extends hr{constructor(s){super(s),s.animationState||(s.animationState=aA(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Al(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 iA=0;class lA extends hr{constructor(){super(...arguments),this.id=iA++}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 oA={animation:{Feature:nA},exit:{Feature:lA}};function si(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function hi(t){return{point:{x:t.pageX,y:t.pageY}}}const cA=t=>s=>nd(s)&&t(s,hi(s));function Hn(t,s,a,r){return si(t,s,cA(a),r)}const N0=1e-4,dA=1-N0,mA=1+N0,w0=.01,uA=0-w0,xA=0+w0;function Vs(t){return t.max-t.min}function hA(t,s,a){return Math.abs(t-s)<=a}function ux(t,s,a,r=.5){t.origin=r,t.originPoint=ns(s.min,s.max,t.origin),t.scale=Vs(a)/Vs(s),t.translate=ns(a.min,a.max,t.origin)-t.originPoint,(t.scale>=dA&&t.scale<=mA||isNaN(t.scale))&&(t.scale=1),(t.translate>=uA&&t.translate<=xA||isNaN(t.translate))&&(t.translate=0)}function Gn(t,s,a,r){ux(t.x,s.x,a.x,r?r.originX:void 0),ux(t.y,s.y,a.y,r?r.originY:void 0)}function xx(t,s,a){t.min=a.min+s.min,t.max=t.min+Vs(s)}function pA(t,s,a){xx(t.x,s.x,a.x),xx(t.y,s.y,a.y)}function hx(t,s,a){t.min=s.min-a.min,t.max=t.min+Vs(s)}function Wn(t,s,a){hx(t.x,s.x,a.x),hx(t.y,s.y,a.y)}function pa(t){return[t("x"),t("y")]}const C0=({current:t})=>t?t.ownerDocument.defaultView:null,px=(t,s)=>Math.abs(t-s);function gA(t,s){const a=px(t.x,s.x),r=px(t.y,s.y);return Math.sqrt(a**2+r**2)}class S0{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 u=ao(this.lastMoveEventInfo,this.history),h=this.startEvent!==null,g=gA(u.offset,{x:0,y:0})>=this.distanceThreshold;if(!h&&!g)return;const{point:b}=u,{timestamp:f}=Fs;this.history.push({...b,timestamp:f});const{onStart:j,onMove:y}=this.handlers;h||(j&&j(this.lastMoveEvent,u),this.startEvent=this.lastMoveEvent),y&&y(this.lastMoveEvent,u)},this.handlePointerMove=(u,h)=>{this.lastMoveEvent=u,this.lastMoveEventInfo=so(h,this.transformPagePoint),es.update(this.updatePoint,!0)},this.handlePointerUp=(u,h)=>{this.end();const{onEnd:g,onSessionEnd:b,resumeAnimation:f}=this.handlers;if(this.dragSnapToOrigin&&f&&f(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const j=ao(u.type==="pointercancel"?this.lastMoveEventInfo:so(h,this.transformPagePoint),this.history);this.startEvent&&g&&g(u,j),b&&b(u,j)},!nd(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=hi(s),c=so(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=Fs;this.history=[{...d,timestamp:m}];const{onSessionStart:p}=a;p&&p(s,ao(c,this.history)),this.removeListeners=mi(Hn(this.contextWindow,"pointermove",this.handlePointerMove),Hn(this.contextWindow,"pointerup",this.handlePointerUp),Hn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),dr(this.updatePoint)}}function so(t,s){return s?{point:s(t.point)}:t}function gx(t,s){return{x:t.x-s.x,y:t.y-s.y}}function ao({point:t},s){return{point:t,delta:gx(t,A0(s)),offset:gx(t,fA(s)),velocity:bA(s,.1)}}function fA(t){return t[0]}function A0(t){return t[t.length-1]}function bA(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=A0(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>_a(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 jA(t,{min:s,max:a},r){return s!==void 0&&ta&&(t=r?ns(a,t,r.max):Math.min(t,a)),t}function fx(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 yA(t,{top:s,left:a,bottom:r,right:n}){return{x:fx(t.x,a,n),y:fx(t.y,s,r)}}function bx(t,s){let a=s.min-t.min,r=s.max-t.max;return s.max-s.minr?a=Jn(s.min,s.max-r,t.min):r>n&&(a=Jn(t.min,t.max-n,s.min)),Ka(0,1,a)}function wA(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 tc=.35;function CA(t=tc){return t===!1?t=0:t===!0&&(t=tc),{x:jx(t,"left","right"),y:jx(t,"top","bottom")}}function jx(t,s,a){return{min:yx(t,s),max:yx(t,a)}}function yx(t,s){return typeof t=="number"?t:t[s]||0}const SA=new WeakMap;class AA{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=hs(),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:u}=this.getProps();u?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(hi(p).point)},l=(p,u)=>{const{drag:h,dragPropagation:g,onDragStart:b}=this.getProps();if(h&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=I2(h),!this.openDragLock))return;this.latestPointerEvent=p,this.latestPanInfo=u,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(Ma.test(y)){const{projection:v}=this.visualElement;if(v&&v.layout){const w=v.layout.layoutBox[j];w&&(y=Vs(w)*(parseFloat(y)/100))}}this.originPoint[j]=y}),b&&es.postRender(()=>b(p,u)),qo(this.visualElement,"transform");const{animationState:f}=this.visualElement;f&&f.setActive("whileDrag",!0)},o=(p,u)=>{this.latestPointerEvent=p,this.latestPanInfo=u;const{dragPropagation:h,dragDirectionLock:g,onDirectionLock:b,onDrag:f}=this.getProps();if(!h&&!this.openDragLock)return;const{offset:j}=u;if(g&&this.currentDirection===null){this.currentDirection=TA(j),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",u.point,j),this.updateAxis("y",u.point,j),this.visualElement.render(),f&&f(p,u)},c=(p,u)=>{this.latestPointerEvent=p,this.latestPanInfo=u,this.stop(p,u),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>pa(p=>{var u;return this.getAnimationState(p)==="paused"&&((u=this.getAxisMotionValue(p).animation)==null?void 0:u.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new S0(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:C0(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&&es.postRender(()=>o(r,n))}cancel(){this.isDragging=!1;const{projection:s,animationState:a}=this.visualElement;s&&(s.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),a&&a.setActive("whileDrag",!1)}updateAxis(s,a,r){const{drag:n}=this.getProps();if(!r||!Ci(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=jA(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&&sn(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=yA(r.layoutBox,s):this.constraints=!1,this.elastic=CA(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&pa(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=wA(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!sn(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=kS(r,n.root,this.visualElement.getTransformPagePoint());let l=vA(n.layout.layoutBox,i);if(a){const o=a(SS(l));this.hasMutatedConstraints=!!o,o&&(l=c0(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=pa(m=>{if(!Ci(m,a,this.currentDirection))return;let p=c&&c[m]||{};l&&(p={min:0,max:0});const u=n?200:1e6,h=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:u,bounceDamping:h,timeConstant:750,restDelta:1,restSpeed:10,...i,...p};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return qo(this.visualElement,s),r.start(pd(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(!Ci(a,r,this.currentDirection))return;const{projection:n}=this.visualElement,i=this.getAxisMotionValue(a);if(n&&n.layout){const{min:l,max:o}=n.layout.layoutBox[a];i.set(s[a]-ns(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!sn(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 c=o.get();n[l]=NA({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),pa(l=>{if(!Ci(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(ns(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;SA.set(this.visualElement,this);const s=this.visualElement.current,a=Hn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();sn(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,i=n.addEventListener("measure",r);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),es.read(r);const l=si(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(pa(m=>{const p=this.getAxisMotionValue(m);p&&(this.originPoint[m]+=c[m].translate,p.set(p.get()+c[m].translate))}),this.visualElement.render())});return()=>{l(),a(),i(),o&&o()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:l=tc,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Ci(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function TA(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class kA extends hr{constructor(s){super(s),this.removeGroupControls=ba,this.removeListeners=ba,this.controls=new AA(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ba}unmount(){this.removeGroupControls(),this.removeListeners()}}const vx=t=>(s,a)=>{t&&es.postRender(()=>t(s,a))};class DA extends hr{constructor(){super(...arguments),this.removePointerDownListener=ba}onPointerDown(s){this.session=new S0(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:C0(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:vx(s),onStart:vx(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&es.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=Hn(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 Oi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Nx(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const Fn={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(ot.test(t))t=parseFloat(t);else return t;const a=Nx(t,s.target.x),r=Nx(t,s.target.y);return`${a}% ${r}%`}},RA={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=mr.parse(t);if(n.length>5)return r;const i=mr.createTransformer(t),l=typeof n[0]!="number"?1:0,o=a.x.scale*s.x,c=a.y.scale*s.y;n[0+l]/=o,n[1+l]/=c;const d=ns(o,c,.5);return typeof n[2+l]=="number"&&(n[2+l]/=d),typeof n[3+l]=="number"&&(n[3+l]/=d),i(n)}};let ro=!1;class FA extends x.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;q2(IA),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),ro&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Oi.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,ro=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||es.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),rd.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;ro=!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 T0(t){const[s,a]=Qg(),r=x.useContext(Mc);return e.jsx(FA,{...t,layoutGroup:r,switchLayoutGroup:x.useContext(l0),isPresent:s,safeToRemove:a})}const IA={borderRadius:{...Fn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Fn,borderTopRightRadius:Fn,borderBottomLeftRadius:Fn,borderBottomRightRadius:Fn,boxShadow:RA};function PA(t,s,a){const r=Ls(t)?t:xn(t);return r.start(pd("",r,s,a)),r.animation}const EA=(t,s)=>t.depth-s.depth;class _A{constructor(){this.children=[],this.isDirty=!1}add(s){$c(this.children,s),this.isDirty=!0}remove(s){Uc(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(EA),this.isDirty=!1,this.children.forEach(s)}}function MA(t,s){const a=ta.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(dr(r),t(i-s))};return es.setup(r,!0),()=>dr(r)}const k0=["TopLeft","TopRight","BottomLeft","BottomRight"],LA=k0.length,wx=t=>typeof t=="string"?parseFloat(t):t,Cx=t=>typeof t=="number"||ot.test(t);function OA(t,s,a,r,n,i){n?(t.opacity=ns(0,a.opacity??1,$A(r)),t.opacityExit=ns(s.opacity??1,0,UA(r))):i&&(t.opacity=ns(s.opacity??1,a.opacity??1,r));for(let l=0;lrs?1:a(Jn(t,s,r))}function Ax(t,s){t.min=s.min,t.max=s.max}function ha(t,s){Ax(t.x,s.x),Ax(t.y,s.y)}function Tx(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function kx(t,s,a,r,n){return t-=s,t=qi(t,1/a,r),n!==void 0&&(t=qi(t,1/n,r)),t}function BA(t,s=0,a=1,r=.5,n,i=t,l=t){if(Ma.test(s)&&(s=parseFloat(s),s=ns(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=ns(i.min,i.max,r);t===i&&(o-=s),t.min=kx(t.min,s,a,o,n),t.max=kx(t.max,s,a,o,n)}function Dx(t,s,[a,r,n],i,l){BA(t,s[a],s[r],s[n],s.scale,i,l)}const VA=["x","scaleX","originX"],zA=["y","scaleY","originY"];function Rx(t,s,a,r){Dx(t.x,s,VA,a?a.x:void 0,r?r.x:void 0),Dx(t.y,s,zA,a?a.y:void 0,r?r.y:void 0)}function Fx(t){return t.translate===0&&t.scale===1}function R0(t){return Fx(t.x)&&Fx(t.y)}function Ix(t,s){return t.min===s.min&&t.max===s.max}function HA(t,s){return Ix(t.x,s.x)&&Ix(t.y,s.y)}function Px(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function F0(t,s){return Px(t.x,s.x)&&Px(t.y,s.y)}function Ex(t){return Vs(t.x)/Vs(t.y)}function _x(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class GA{constructor(){this.members=[]}add(s){$c(this.members,s),s.scheduleRender()}remove(s){if(Uc(this.members,s),s===this.prevLead&&(this.prevLead=void 0),s===this.lead){const a=this.members[this.members.length-1];a&&this.promote(a)}}relegate(s){const a=this.members.findIndex(n=>s===n);if(a===0)return!1;let r;for(let n=a;n>=0;n--){const i=this.members[n];if(i.isPresent!==!1){r=i;break}}return r?(this.promote(r),!0):!1}promote(s,a){const r=this.lead;if(s!==r&&(this.prevLead=r,this.lead=s,s.show(),r)){r.instance&&r.scheduleRender(),s.scheduleRender(),s.resumeFrom=r,a&&(s.resumeFrom.preserveOpacity=!0),r.snapshot&&(s.snapshot=r.snapshot,s.snapshot.latestValues=r.animationValues||r.latestValues),s.root&&s.root.isUpdating&&(s.isLayoutDirty=!0);const{crossfade:n}=s.options;n===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(s=>{const{options:a,resumingFrom:r}=s;a.onExitComplete&&a.onExitComplete(),r&&r.options.onExitComplete&&r.options.onExitComplete()})}scheduleRender(){this.members.forEach(s=>{s.instance&&s.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function WA(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,l=(a==null?void 0:a.z)||0;if((n||i||l)&&(r=`translate3d(${n}px, ${i}px, ${l}px) `),(s.x!==1||s.y!==1)&&(r+=`scale(${1/s.x}, ${1/s.y}) `),a){const{transformPerspective:d,rotate:m,rotateX:p,rotateY:u,skewX:h,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),p&&(r+=`rotateX(${p}deg) `),u&&(r+=`rotateY(${u}deg) `),h&&(r+=`skewX(${h}deg) `),g&&(r+=`skewY(${g}deg) `)}const o=t.x.scale*s.x,c=t.y.scale*s.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const no=["","X","Y","Z"],YA=1e3;let KA=0;function io(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function I0(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=f0(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",es,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&I0(r)}function P0({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=KA++,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(JA),this.nodes.forEach(tT),this.nodes.forEach(sT),this.nodes.forEach(ZA)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=l,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let c=0;cthis.root.updateBlockedByResize=!1;es.read(()=>{p=window.innerWidth}),t(l,()=>{const h=window.innerWidth;h!==p&&(p=h,this.root.updateBlockedByResize=!0,m&&m(),m=MA(u,250),Oi.hasAnimatedSinceResize&&(Oi.hasAnimatedSinceResize=!1,this.nodes.forEach(Ox)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:p,hasRelativeLayoutChanged:u,layout:h})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||lT,{onLayoutAnimationStart:b,onLayoutAnimationComplete:f}=d.getProps(),j=!this.targetLayout||!F0(this.targetLayout,h),y=!p&&u;if(this.options.layoutRoot||this.resumeFrom||y||p&&(j||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const v={...sd(g,"layout"),onPlay:b,onComplete:f};(d.shouldReduceMotion||this.options.layoutRoot)&&(v.delay=0,v.type=!1),this.startAnimation(v),this.setAnimationOrigin(m,y)}else p||Ox(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=h})}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(),dr(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(aT),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&&I0(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&&!Vs(this.snapshot.measuredBox.x)&&!Vs(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c{const S=w/1e3;$x(p.x,l.x,S),$x(p.y,l.y,S),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Wn(u,this.layout.layoutBox,this.relativeParent.layout.layoutBox),nT(this.relativeTarget,this.relativeTargetOrigin,u,S),v&&HA(this.relativeTarget,v)&&(this.isProjectionDirty=!1),v||(v=hs()),ha(v,this.relativeTarget)),b&&(this.animationValues=m,OA(m,d,this.latestValues,S,y,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=S},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(dr(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=es.update(()=>{Oi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=xn(0)),this.currentAnimation=PA(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(YA),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:m}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&E0(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||hs();const p=Vs(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+p;const u=Vs(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+u}ha(o,c),rn(o,m),Gn(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new GA),this.sharedNodes.get(l).add(o);const d=o.options.initialPromotionConfig;o.promote({transition:d?d.transition:void 0,preserveFollowOpacity:d&&d.shouldPreserveFollowOpacity?d.shouldPreserveFollowOpacity(o):void 0})}isLead(){const l=this.getStack();return l?l.lead===this:!0}getLead(){var o;const{layoutId:l}=this.options;return l?((o=this.getStack())==null?void 0:o.lead)||this:this}getPrevLead(){var o;const{layoutId:l}=this.options;return l?(o=this.getStack())==null?void 0:o.prevLead:void 0}getStack(){const{layoutId:l}=this.options;if(l)return this.root.sharedNodes.get(l)}promote({needsReset:l,transition:o,preserveFollowOpacity:c}={}){const d=this.getStack();d&&d.promote(this,c),l&&(this.projectionDelta=void 0,this.needsReset=!0),o&&this.setOptions({transition:o})}relegate(){const l=this.getStack();return l?l.relegate(this):!1}resetSkewAndRotation(){const{visualElement:l}=this.options;if(!l)return;let o=!1;const{latestValues:c}=l;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(o=!0),!o)return;const d={};c.z&&io("z",l,d,this.animationValues);for(let m=0;m{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(Mx),this.root.sharedNodes.clear()}}}function QA(t){t.updateLayout()}function XA(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 u=l?s.measuredBox[p]:s.layoutBox[p],h=Vs(u);u.min=r[p].min,u.max=u.min+h}):E0(i,s.layoutBox,r)&&pa(p=>{const u=l?s.measuredBox[p]:s.layoutBox[p],h=Vs(r[p]);u.max=u.min+h,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[p].max=t.relativeTarget[p].min+h)});const o=nn();Gn(o,r,s.layoutBox);const c=nn();l?Gn(c,t.applyTransform(n,!0),s.measuredBox):Gn(c,r,s.layoutBox);const d=!R0(o);let m=!1;if(!t.resumeFrom){const p=t.getClosestProjectingParent();if(p&&!p.resumeFrom){const{snapshot:u,layout:h}=p;if(u&&h){const g=hs();Wn(g,s.layoutBox,u.layoutBox);const b=hs();Wn(b,r,h.layoutBox),F0(g,b)||(m=!0),p.options.layoutRoot&&(t.relativeTarget=b,t.relativeTargetOrigin=g,t.relativeParent=p)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function JA(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 ZA(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function qA(t){t.clearSnapshot()}function Mx(t){t.clearMeasurements()}function Lx(t){t.isLayoutDirty=!1}function eT(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function Ox(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function tT(t){t.resolveTargetDelta()}function sT(t){t.calcProjection()}function aT(t){t.resetSkewAndRotation()}function rT(t){t.removeLeadSnapshot()}function $x(t,s,a){t.translate=ns(s.translate,0,a),t.scale=ns(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function Ux(t,s,a,r){t.min=ns(s.min,a.min,r),t.max=ns(s.max,a.max,r)}function nT(t,s,a,r){Ux(t.x,s.x,a.x,r),Ux(t.y,s.y,a.y,r)}function iT(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const lT={duration:.45,ease:[.4,0,.1,1]},Bx=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Vx=Bx("applewebkit/")&&!Bx("chrome/")?Math.round:ba;function zx(t){t.min=Vx(t.min),t.max=Vx(t.max)}function oT(t){zx(t.x),zx(t.y)}function E0(t,s,a){return t==="position"||t==="preserve-aspect"&&!hA(Ex(s),Ex(a),.2)}function cT(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const dT=P0({attachResizeListener:(t,s)=>si(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),lo={current:void 0},_0=P0({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!lo.current){const t=new dT({});t.mount(window),t.setOptions({layoutScroll:!0}),lo.current=t}return lo.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),mT={pan:{Feature:DA},drag:{Feature:kA,ProjectionNode:_0,MeasureLayout:T0}};function Hx(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&&es.postRender(()=>i(s,hi(s)))}class uT extends hr{mount(){const{current:s}=this.node;s&&(this.unmount=P2(s,(a,r)=>(Hx(this.node,r,"Start"),n=>Hx(this.node,n,"End"))))}unmount(){}}class xT extends hr{constructor(){super(...arguments),this.isActive=!1}onFocus(){let s=!1;try{s=this.node.current.matches(":focus-visible")}catch{s=!0}!s||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=mi(si(this.node.current,"focus",()=>this.onFocus()),si(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Gx(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&&es.postRender(()=>i(s,hi(s)))}class hT extends hr{mount(){const{current:s}=this.node;s&&(this.unmount=L2(s,(a,r)=>(Gx(this.node,r,"Start"),(n,{success:i})=>Gx(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const sc=new WeakMap,oo=new WeakMap,pT=t=>{const s=sc.get(t.target);s&&s(t)},gT=t=>{t.forEach(pT)};function fT({root:t,...s}){const a=t||document;oo.has(a)||oo.set(a,{});const r=oo.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(gT,{root:t,...s})),r[n]}function bT(t,s,a){const r=fT(s);return sc.set(t,a),r.observe(t),()=>{sc.delete(t),r.unobserve(t)}}const jT={some:0,all:1};class yT extends hr{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:a,margin:r,amount:n="some",once:i}=s,l={root:a?a.current:void 0,rootMargin:r,threshold:typeof n=="number"?n:jT[n]},o=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:p}=this.node.getProps(),u=d?m:p;u&&u(c)};return bT(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(vT(s,a))&&this.startObserver()}unmount(){}}function vT({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const NT={inView:{Feature:yT},tap:{Feature:hT},focus:{Feature:xT},hover:{Feature:uT}},wT={layout:{ProjectionNode:_0,MeasureLayout:T0}},CT={...oA,...NT,...mT,...wT},Wt=CS(CT,LS),In=[{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:_t,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:zh,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 ST({open:t,onClose:s,onSelectTemplate:a}){var d,m,p;const[r,n]=x.useState(null),[i,l]=x.useState(!1);x.useEffect(()=>{const u=at.getUserData();l((u==null?void 0:u.jobTitle)==="Dealer")},[]);const o=u=>{if(i)return;const h=In.find(g=>g.id===u);h!=null&&h.disabled||n(u)},c=()=>{r&&(a(r),s())};return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"!fixed !inset-0 !top-0 !left-0 !right-0 !bottom-0 !w-screen !h-screen !max-w-none !translate-x-0 !translate-y-0 p-0 gap-0 border-0 !rounded-none bg-gradient-to-br from-gray-50 to-white [&>button]:hidden !m-0",children:[e.jsx(mt,{className:"sr-only",children:"Select a Template"}),e.jsx(Et,{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(cl,{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:In.map((u,h)=>{const g=u.icon,b=r===u.id,f=i||u.disabled;return e.jsx(Wt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:h*.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(u.id),children:[e.jsxs(ie,{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 ${u.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(Oa,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(le,{className:"text-xl mb-2",children:u.name}),e.jsx(ye,{className:"text-sm leading-relaxed",children:u.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(Je,{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"})]}),u.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(Je,{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(ae,{variant:"secondary",className:"text-xs",children:u.category})}),e.jsx(Zt,{}),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(rt,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:u.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ts,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[u.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:[u.features.slice(0,3).map((j,y)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(Be,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:j})]},y)),u.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",u.features.length-3," more features"]})]})]})]})]})},u.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(P,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(P,{onClick:c,disabled:!r||i||((d=In.find(u=>u.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=In.find(u=>u.id===r))!=null&&m.disabled)?"bg-blue-600 hover:bg-blue-700":"bg-gray-400 cursor-not-allowed"}`,children:["Continue with Template",e.jsx(js,{className:"w-4 h-4"})]})]}),e.jsx(Cl,{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=In.find(u=>u.id===r))==null?void 0:p.name})]})})})]})})]})})}function Gr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=x.useState(100),[m,p]=x.useState(0),[u,h]=x.useState(null),[g,b]=x.useState(!1),[f,j]=x.useState(null),y=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),v=s.toLowerCase().includes("pdf"),w=y||v;x.useEffect(()=>{if(!l||!w||!a){h(null);return}return(async()=>{b(!0),j(null);try{let I=a;a.startsWith("/")&&!a.startsWith("//")&&(I=`${window.location.origin}${a}`);const T=await fetch(I,{headers:{Accept:v?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!T.ok){const D=await T.text().catch(()=>"");throw new Error(`Failed to load file: ${T.status} ${T.statusText}. ${D}`)}const M=await T.blob();if(M.size===0)throw new Error("File is empty or could not be loaded");v&&!M.type.includes("pdf")&&M.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${M.type}`);const F=window.URL.createObjectURL(M);h(F)}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)}})(),()=>{u&&(window.URL.revokeObjectURL(u),h(null))}},[l,a,w,v]);const S=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},C=()=>d(k=>Math.min(k+25,200)),E=()=>d(k=>Math.max(k-25,50)),R=()=>p(k=>(k+90)%360);return e.jsx(xt,{open:l,onOpenChange:o,children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ht,{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(vt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`• ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[y&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(P,{variant:"ghost",size:"sm",onClick:E,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(fj,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[c,"%"]}),e.jsx(P,{variant:"ghost",size:"sm",onClick:C,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(bj,{className:"h-4 w-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:R,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(Hh,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(P,{variant:"outline",size:"sm",onClick:S,className:"gap-2 h-9",children:[e.jsx(Tt,{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(ze,{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(P,{onClick:S,className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"}),"Download ",t]})]}):w&&u?e.jsxs(e.Fragment,{children:[y&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:u,alt:t,style:{transform:`scale(${c/100}) rotate(${m}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),v&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:u,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(vt,{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(P,{onClick:S,className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function pi({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Et,{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(Dt,{children:e.jsx(P,{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},kl=async t=>{const s=t?{category:t}:{};return(await be.get("/admin/configurations",{params:s})).data.data},Bs=async(t,s)=>{await be.put(`/admin/configurations/${t}`,{configValue:s})},AT=async t=>{await be.post(`/admin/configurations/${t}/reset`)},TT=async()=>{const t=await be.get("/admin/form16-config");return t.data.data??t.data},kT=async t=>{await be.put("/admin/form16-config",t)},DT=async t=>{const s=t?{year:t}:{};return(await be.get("/admin/holidays",{params:s})).data.data},RT=async t=>(await be.post("/admin/holidays",t)).data.data,FT=async(t,s)=>(await be.put(`/admin/holidays/${t}`,s)).data.data,IT=async t=>{await be.delete(`/admin/holidays/${t}`)},PT=async()=>(await be.get("/config/activity-types")).data.data,ET=async t=>{const s={activeOnly:t.toString()};return(await be.get("/admin/activity-types",{params:s})).data.data},_T=async t=>(await be.post("/admin/activity-types",t)).data.data,MT=async(t,s)=>(await be.put(`/admin/activity-types/${t}`,s)).data.data,LT=async t=>{await be.delete(`/admin/activity-types/${t}`)},OT={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 $T(t,s,a){const[r,n]=x.useState(OT),[i,l]=x.useState(null),[o,c]=x.useState(t),[d,m]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[p,u]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[h,g]=x.useState([]);return x.useEffect(()=>{(async()=>{var j;try{const y=await ma("DOCUMENT_POLICY"),v={};y.forEach(O=>{v[O.configKey]=O.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(O=>O.trim().toLowerCase());u({maxFileSizeMB:w,allowedFileTypes:C});const E=await ma("SYSTEM_SETTINGS"),R=await ma("WORKFLOW_SHARING"),k=[...E,...R],N={};k.forEach(O=>{N[O.configKey]=O.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)}})()},[]),x.useEffect(()=>{if(!t||!s)return;let f=!0;return(async()=>{try{c(!0);const j=await Is(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(I=>!I.isDeleted):[];g(S);const C=(y.priority||"").toString().toLowerCase(),E={standard:"standard",express:"express"},R=y.templateType==="TEMPLATE"?"existing-template":"custom",k=a.find(I=>I.id===R)||a[0]||null;l(k);const N=v.sort((I,B)=>(I.levelNumber||0)-(B.levelNumber||0)).map(I=>{const B=Number(I.tatHours||24),T=Math.floor(B/24),M=B%24;return{id:I.approverId||`temp-${I.levelNumber}`,name:I.approverName||I.approverEmail||"",email:I.approverEmail||"",role:I.levelName||`Level ${I.levelNumber}`,department:"",avatar:(I.approverName||I.approverEmail||"XX").substring(0,2).toUpperCase(),level:I.levelNumber||1,canClose:!1,tat:T>0?T:M,tatType:T>0?"days":"hours",userId:I.approverId}}),O=w.filter(I=>(I.participantType||I.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(I.userEmail||I.user_email||I.email):!1).map((I,B)=>{const T=I.userId||I.user_id||I.id,M=I.userName||I.user_name||I.name||"",F=I.userEmail||I.user_email||I.email||"",A=(M||F||"XX").split(" ").map(H=>H[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:T||`spectator-${s}-${B}-${Date.now()}`,userId:T,name:M||F||"Spectator",email:F,role:"Spectator",department:I.department||"",avatar:A,level:1,canClose:!1}});n(I=>({...I,template:R,title:y.title||"",description:y.description||"",priority:E[C]||"standard",approvers:N,approverCount:N.length||1,spectators:O,maxLevel:Math.max(...N.map(B=>B.level||1),1)}))}catch(j){console.error("Failed to load draft:",j)}finally{f&&c(!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:d,documentPolicy:p,existingDocuments:h,setExistingDocuments:g}}const Wx=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function UT(t,s,a){const[r,n]=x.useState(t?2:1),i=Wx.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 u=p.tatType||"hours";return u==="hours"?p.tat&&p.tat>0&&p.tat<=720:u==="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:Wx,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 BT(){const[t,s]=x.useState({open:!1,type:"error",email:"",message:""}),[a,r]=x.useState({open:!1,violations:[]}),[n,i]=x.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(u,h,g="")=>{s({open:!0,type:u,email:h,message:g})},closeValidationModal:()=>{s(u=>({...u,open:!1}))},openPolicyViolationModal:u=>{r({open:!0,violations:u})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:u=>{i({open:!0,errors:u})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function VT(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function zT(t,s,a){var n;const r=VT(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 HT(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return zT(a,n,n===s)})}function Yx(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 Kx(t,s,a,r=!1){const n=HT(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 GT(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 Qx(t,s){return{id:(await Ec(t,s||[],"SUPPORTING")).id}}async function Xx(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await k1(t,s,a||[],r):await T1(t,s)}function WT({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=x.useState(!1),[m,p]=x.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var b,f;if(c||m)return;const g=GT(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const j=Kx(t,n,r,!1);await Xx(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=Yx(t,s,n,!1),y=await Qx(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}),d(!1)}},handleSaveDraft:async()=>{var g,b;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||m)){p(!0);try{if(i&&l){const f=Kx(t,n,r,!0);await Xx(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=Yx(t,s,n,!0),j=await Qx(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 va(t,s=10,a="default"){return await be.get("/users/search",{params:{q:t,limit:s,source:a}})}async function ja(t){var a;const s=await be.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function YT(t,s){return await be.post("/admin/users/assign-role",{email:t,role:s})}async function KT(t,s){return await be.put(`/admin/users/${t}/role`,{role:s})}async function QT(t,s=1,a=10){return await be.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function XT(){return await be.get("/admin/users/role-statistics")}async function JT(t){var a;const s=await be.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function ZT(){var s,a;return((a=(s=(await be.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const ca={searchUsers:va,getUserById:JT,ensureUserExists:ja,assignRole:YT,updateUserRole:KT,getUsersByRole:QT,getRoleStatistics:XT,getAllUsers:ZT};async function qT(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 va(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 ja({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 e5(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(R),a("template",R.id),a("category",R.category),a("priority",R.priority);const k=new Date;k.setDate(k.getDate()+R.suggestedSLA),a("slaEndDate",k),R.id!=="custom"&&R.id!=="existing-template"&&h(`/create-admin-request/${R.id}`)},handleTemplateSelection:R=>{R==="claim-management"?h("/claim-management"):R==="vendor-payment"?h("/vendor-payment"):u&&u({templateType:R})},nextStep:async()=>{var R;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 O=r.approverCount||1;if(O>m.maxApprovalLevels){p([{type:"Maximum Approval Levels Exceeded",message:`The request has ${O} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:O,maxValue:m.maxApprovalLevels}]);return}}const k=((R=c==null?void 0:c.email)==null?void 0:R.toLowerCase())||"",N=await e5(r.approvers,k);if(!N.success&&N.error){d(N.error.type,N.error.email,N.error.message);return}N.validatedApprovers&&a("approvers",N.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(R,k)=>{if(k){const N=R.documentId||R.document_id||"";j({fileName:R.originalFileName||R.fileName||"Document",fileType:R.fileType||R.file_type||"application/octet-stream",fileUrl:yn(N),fileSize:Number(R.fileSize||R.file_size||0),documentId:N})}else{const N=URL.createObjectURL(R);j({fileName:R.name,fileType:R.type||"application/octet-stream",fileUrl:N,fileSize:R.size,file:R})}},closePreview:()=>{f!=null&&f.fileUrl&&(f!=null&&f.file)&&URL.revokeObjectURL(f.fileUrl),j(null)}}}const Jx=[{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:dl,estimatedTime:"Variable",commonApprovers:[],suggestedSLA:3,priority:"medium",fields:{}},{id:"existing-template",name:"Existing Template",description:"Use a pre-configured template with predefined approval workflows, timelines, and requirements for faster processing",category:"Templates",icon:Re,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let Lr=null;const Zx=()=>Lr,s5=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 Lr&&Lr.push(r),r},Dl=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 Lr=a,a},a5=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 Lr&&(Lr=Lr.map(i=>i.id===t?n:i)),n};function M0({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 r5({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:l,submitting:o,savingDraft:c,loadingDraft:d,isEditing:m}){return e.jsx("div",{className:"fixed sm:relative bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0 shadow-lg sm:shadow-none z-50","data-testid":"wizard-footer",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2 sm:gap-4 max-w-6xl mx-auto",children:[e.jsxs(P,{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(P,{variant:"outline",onClick:l,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:d||o||c,"data-testid":"wizard-footer-save-draft-button",children:c?e.jsxs(e.Fragment,{children:[e.jsx(ze,{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(P,{onClick:i,disabled:!a||d||o||c,size:"sm",className:"sm:size-lg bg-green-600 hover:bg-green-700 flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-submit-button",children:o?e.jsxs(e.Fragment,{children:[e.jsx(ze,{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(Gh,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(P,{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(js,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const qx=t=>{switch(t){case"high":return e.jsx(Fa,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(ts,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Hs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(ts,{className:"w-4 h-4 text-gray-600"})}};function n5({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=x.useState("main"),l=Cs(),o=m=>{m.id==="admin-templates-category"?i("admin"):n==="admin"?l(`/create-admin-request/${m.id}`):a(m)},c=n==="main"?[...t]:r;return e.jsxs(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(P,{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:c.length===0&&n==="admin"?e.jsxs("div",{className:"col-span-full text-center py-12 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed border-gray-200",children:[e.jsx(jj,{className:"w-12 h-12 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No admin templates available yet."})]}):c.map(m=>{var g;const u=m.id==="admin-templates-category",h=(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 ${h?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200 cursor-pointer":u?"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(ie,{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 ${h||u?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${m.id}-icon`,children:e.jsx(m.icon,{className:`w-7 h-7 ${h||u?"text-blue-600":"text-gray-600"}`})}),h&&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(Oa,{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(le,{className:"text-xl","data-testid":`template-card-${m.id}-name`,children:m.name}),!1]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ae,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),qx(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}),!u&&e.jsxs(e.Fragment,{children:[e.jsx(Zt,{}),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(rt,{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(qt,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[((g=m.commonApprovers)==null?void 0:g.length)||0," approvers"]})]})]})]}),u&&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(Cl,{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(ie,{children:e.jsxs(le,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Vr,{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(se,{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(se,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[qx(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(se,{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(se,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((d=s.commonApprovers)==null?void 0:d.length)>0?s.commonApprovers.map((m,p)=>e.jsx(ae,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${p}`,children:m},`${s.id}-approver-${p}-${m}`)):e.jsx("span",{className:"text-sm text-gray-500 italic",children:"No specific approvers defined"})})]})]})]})})})]})}function 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 i5({className:t,...s}){return e.jsx(Ab,{"data-slot":"radio-group",className:Me("grid gap-3",t),...s})}function eh({className:t,...s}){return e.jsx(Tb,{"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(kb,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(xc,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function l5({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(Re,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"basic-information-title",children:"Basic Information"}),e.jsxs("p",{className:"text-gray-600","data-testid":"basic-information-description",children:["Provide the essential details for your ",(s==null?void 0:s.name)||"request","."]})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"basic-information-form",children:[e.jsxs("div",{"data-testid":"basic-information-title-field",children:[e.jsx(se,{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(se,{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(di,{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(se,{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(i5,{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(eh,{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(ol,{className:"w-4 h-4 text-red-600"}),e.jsx(se,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(ae,{variant:"destructive",className:"text-xs",children:"URGENT"})]}),e.jsx("p",{className:"text-xs text-red-700",children:"Includes calendar days in TAT - faster processing timeline"})]})]}),e.jsxs("div",{className:`flex items-center space-x-3 p-3 rounded-lg border cursor-pointer transition-all ${t.priority==="standard"?"border-blue-500 bg-blue-50":"border-gray-200 hover:bg-gray-50"}`,onClick:()=>a("priority","standard"),"data-testid":"basic-information-priority-standard-option",children:[e.jsx(eh,{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(rt,{className:"w-4 h-4 text-blue-600"}),e.jsx(se,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(ae,{variant:"secondary",className:"text-xs",children:"DEFAULT"})]}),e.jsx("p",{className:"text-xs text-gray-600",children:"Includes working days in TAT - regular processing timeline"})]})]})]})]})}),((s==null?void 0:s.fields.amount)||(s==null?void 0:s.fields.vendor)||(s==null?void 0:s.fields.timeline)||(s==null?void 0:s.fields.impact))&&e.jsxs("div",{className:"border-t pt-6","data-testid":"basic-information-additional-details",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Additional Details"}),e.jsxs("div",{className:"space-y-6",children:[(s==null?void 0:s.fields.amount)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4","data-testid":"basic-information-amount-field",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{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(se,{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(We,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"USD",children:"USD ($)"}),e.jsx(J,{value:"EUR",children:"EUR (€)"}),e.jsx(J,{value:"GBP",children:"GBP (£)"}),e.jsx(J,{value:"INR",children:"INR (₹)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(se,{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(se,{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(se,{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 L0(){const[t,s]=x.useState([]),[a,r]=x.useState(!1),n=x.useRef(null);return{searchResults:t,searchLoading:a,searchUsersDebounced:async(c,d=10)=>{if(n.current&&clearTimeout(n.current),!c||!c.startsWith("@")||c.length<2){s([]),r(!1);return}r(!0),n.current=setTimeout(async()=>{var m;try{const p=c.slice(1),h=((m=(await va(p,d)).data)==null?void 0:m.data)||[];s(h)}catch(p){console.error("User search failed:",p),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await ja({userId:c.userId,email:c.email,displayName:c.displayName,firstName:c.firstName,lastName:c.lastName,department:c.department,phone:c.phone,mobilePhone:c.mobilePhone,designation:c.designation,jobTitle:c.jobTitle,manager:c.manager,employeeId:c.employeeId,employeeNumber:c.employeeNumber,secondEmail:c.secondEmail,location:c.location})}catch(d){throw console.error("Failed to ensure user exists:",d),d}}}}function O0(){const[t,s]=x.useState({}),[a,r]=x.useState({}),n=x.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(o,c,d=10)=>{if(n.current[o]&&clearTimeout(n.current[o]),!c||!c.startsWith("@")||c.length<2){s(m=>({...m,[o]:[]})),r(m=>({...m,[o]:!1}));return}r(m=>({...m,[o]:!0})),n.current[o]=setTimeout(async()=>{var m;try{const p=c.slice(1),h=((m=(await va(p,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:h}))}catch(p){console.error(`User search failed for index ${o}:`,p),s(u=>({...u,[o]:[]}))}finally{r(p=>({...p,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function o5({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var p;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=O0();x.useEffect(()=>{const u=t.approverCount||1,h=t.approvers||[];if(h.lengthu&&s("approvers",h.slice(0,u))},[t.approverCount,s]);const d=(u,h)=>{var j,y,v,w,S;const g=[...t.approvers],f=((j=g[u])==null?void 0:j.email)!==h;if(g[u]={...g[u],email:h,level:u+1,userId:f||(y=g[u])==null?void 0:y.userId,name:f||(v=g[u])==null?void 0:v.name,department:f||(w=g[u])==null?void 0:w.department,avatar:f||(S=g[u])==null?void 0:S.avatar},s("approvers",g),!h||!h.startsWith("@")||h.length<2){c(u);return}o(u,h,10)},m=async(u,h)=>{var g,b;try{if((g=t.approvers)==null?void 0:g.some((w,S)=>{var C,E;return S!==u&&(w.userId===h.userId||((C=w.email)==null?void 0:C.toLowerCase())===((E=h.email)==null?void 0:E.toLowerCase()))})){a({type:"error",email:h.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===h.userId||((S=w.email)==null?void 0:S.toLowerCase())===((C=h.email)==null?void 0:C.toLowerCase())})){a({type:"error",email:h.email,message:"This user is already added as a spectator. A user cannot be both an approver and a spectator."});return}const y=await ja({userId:h.userId,email:h.email,displayName:h.displayName,firstName:h.firstName,lastName:h.lastName,department:h.department,phone:h.phone,mobilePhone:h.mobilePhone,designation:h.designation,jobTitle:h.jobTitle,manager:h.manager,employeeId:h.employeeId,employeeNumber:h.employeeNumber,secondEmail:h.secondEmail,location:h.location}),v=[...t.approvers];v[u]={...v[u],email:h.email,name:h.displayName||[h.firstName,h.lastName].filter(Boolean).join(" "),userId:y.userId,level:u+1},s("approvers",v),c(u)}catch(f){console.error("Failed to ensure user exists:",f),a({type:"error",email:h.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(qt,{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(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(lr,{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(se,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{const u=t.approverCount||1,h=Math.max(1,u-1);s("approverCount",h),t.approvers.length>h&&s("approvers",t.approvers.slice(0,h))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(hc,{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(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{const h=(t.approverCount||1)+1;if(h>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:h,maxValue:r.maxApprovalLevels}]);return}s("approverCount",h)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(ms,{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(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(fs,{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(ae,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-sm text-blue-700",children:"Creates and submits the request"})]})]})}),Array.from({length:t.approverCount||1},(u,h)=>{var j,y;const g=h+1,b=g===(t.approverCount||1),f=t.approvers[h]||{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(ae,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(se,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),f.email&&f.userId&&e.jsxs(ae,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(Be,{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=>d(h,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[h]||(((j=i[h])==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[h]?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[h])==null?void 0:y.map(v=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(h,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(se,{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[h]={...w[h],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[h]={...w[h],tatType:v,level:g,tat:""},s("approvers",w)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(We,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"hours",children:"Hours"}),e.jsx(J,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},g)})]})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Vr,{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},(u,h)=>`Level ${h+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(rt,{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 u=((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,h=Math.ceil(u);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[h," ",h===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((u,h)=>{const g=Number(u.tat||0),f=(u.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 ",h+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[f," ",f===1?"hour":"hours"]})]})},h):null})}),(()=>{var g;const u=((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,h=Math.ceil(u/8);return u===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:[u,"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:h}),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 c5({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=x.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=L0(),p=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},u=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(""),d()}catch{a({type:"error",email:g.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const j=t.spectators.some(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}}},h=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(vt,{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(ie,{children:[e.jsxs(le,{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(vt,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(ae,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx(ye,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(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 u())},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:()=>u(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(P,{size:"sm",onClick:()=>u(),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(Vr,{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(cs,{className:"h-6 w-6",children:e.jsx(ds,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>h(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(jt,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function d5({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:c,onDocumentErrors:d,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&&d&&d(y),b.target&&(b.target.value="")},u=b=>{const f=a.filter((j,y)=>y!==b);i(f)},h=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(ys,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"documents-title",children:"Documents & Attachments"}),e.jsx("p",{className:"text-gray-600","data-testid":"documents-description",children:"Upload supporting documents, files, and any additional materials for your request."})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"documents-content",children:[e.jsxs(Z,{"data-testid":"documents-upload-card",children:[e.jsxs(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Re,{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(ys,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"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(P,{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(ms,{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(ie,{children:e.jsxs(le,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ae,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(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(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.originalFileName||b.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:b.fileSize?(Number(b.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!0)&&e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>c(b,!0),"data-testid":`documents-existing-${f}-preview`,children:e.jsx(vt,{className:"h-4 w-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>h(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(ie,{children:e.jsxs(le,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ae,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(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(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(b.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!1)&&e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>c(b,!1),"data-testid":`documents-new-${f}-preview`,children:e.jsx(vt,{className:"h-4 w-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>u(f),"data-testid":`documents-new-${f}-remove`,children:e.jsx(jt,{className:"h-4 w-4"})})]})]},f))})})]})]})]})}const m5=t=>{switch(t){case"high":return e.jsx(Fa,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(ts,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(Hs,{className:"w-4 h-4 text-green-600"});default:return e.jsx(ts,{className:"w-4 h-4 text-gray-600"})}};function u5({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(Be,{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(ie,{children:e.jsxs(le,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(Gh,{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(se,{className:"text-green-900 font-semibold",children:"Request Type"}),e.jsx("p",{className:"text-green-800 mt-1",children:s==null?void 0:s.name}),e.jsx(ae,{variant:"outline",className:"mt-2 text-xs border-green-300 text-green-700",children:s==null?void 0:s.category})]}),e.jsxs("div",{"data-testid":"review-submit-overview-priority",children:[e.jsx(se,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[m5(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(se,{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(se,{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(ie,{children:e.jsxs(le,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(te,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(se,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(Ps,{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(ka,{className:"w-4 h-4 text-blue-600"}),e.jsx(se,{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(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(qt,{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(ae,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Email Address"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:(l==null?void 0:l.email)||"Not assigned"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"TAT (Turn Around Time)"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l!=null&&l.tat?`${l.tat} ${l.tatType==="days"?"day":"hour"}${l.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(Z,{"data-testid":"review-submit-participants-card",children:[e.jsx(ie,{children:e.jsxs(le,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(vt,{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(se,{className:"font-semibold text-sm",children:["Spectators (",t.spectators.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:t.spectators.map(a=>e.jsxs(ae,{variant:"outline",className:"text-xs","data-testid":`review-submit-spectator-${a.id}`,children:[a.name," (",a.email,")"]},a.id))})]})})]}),t.documents.length>0&&e.jsxs(Z,{"data-testid":"review-submit-documents-card",children:[e.jsxs(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(ys,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs(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(Re,{className:"w-5 h-5 text-gray-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.name}),e.jsx("div",{className:"flex items-center gap-3 text-xs text-gray-500 mt-1",children:e.jsxs("span",{children:[(a.size/(1024*1024)).toFixed(2)," MB"]})})]})]},r))})})]}),e.jsx(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(Be,{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 x5({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(P,{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 h5({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(Cl,{mode:"wait",children:t})})})}function p5({modal:t,onClose:s}){return e.jsx(xt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Et,{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(dl,{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(Dt,{children:e.jsx(P,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function g5({modal:t,documentPolicy:s,onClose:a}){return e.jsx(xt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Et,{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(Dt,{children:e.jsx(P,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function th({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Ba(),i=Cs(),l=n.requestId||a||"",o=r&&!!l,{user:c}=us(),[d,m]=x.useState([]);x.useEffect(()=>{(async()=>{try{const me=(await Dl()).map(Ne=>({id:Ne.id,name:Ne.name,description:Ne.description,category:Ne.category,icon:Re,estimatedTime:Ne.estimatedTime,commonApprovers:Ne.approvers.map(Oe=>Oe.name),workflowApprovers:Ne.approvers,suggestedSLA:Ne.suggestedSLA,priority:Ne.priority,fields:Ne.fields||{}}));m(me)}catch(de){console.error("Failed to fetch admin templates:",de)}})()},[]);const p=x.useMemo(()=>[...Jx,...d],[d]),{formData:u,updateFormData:h,selectedTemplate:g,setSelectedTemplate:b,loadingDraft:f,systemPolicy:j,documentPolicy:y,existingDocuments:v,setExistingDocuments:w}=$T(o,l,p),{currentStep:S,totalSteps:C,stepNames:E,isStepValid:R,nextStep:k,prevStep:N}=UT(o,g,u),[O,I]=x.useState([]),[B,T]=x.useState([]),M=x.useRef(null),{validationModal:F,policyViolationModal:D,documentErrorModal:A,openValidationModal:H,closeValidationModal:$,openPolicyViolationModal:_,closePolicyViolationModal:L,openDocumentErrorModal:z,closeDocumentErrorModal:X}=BT(),{submitting:W,savingDraft:U,handleSubmit:V,handleSaveDraft:Q}=WT({formData:u,selectedTemplate:g,documents:O,documentsToDelete:B,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:ee,setShowTemplateModal:K,previewDocument:q,selectTemplate:ue,handleTemplateSelection:Le,nextStep:Ze,prevStep:De,handlePreviewDocument:_e,closePreview:Ue}=t5({selectedTemplate:g,setSelectedTemplate:b,updateFormData:h,formData:u,currentStep:S,isStepValid:R,wizardNextStep:k,wizardPrevStep:N,user:c,openValidationModal:H,systemPolicy:j,onPolicyViolation:_,onSubmit:s}),re=x.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}):De()},[S,t,i,De]),fe=x.useRef(!0),Ce=x.useRef(!1);x.useEffect(()=>{fe.current&&u.documents&&u.documents.length>0&&!Ce.current&&(I(u.documents),Ce.current=!0),fe.current=!1},[u.documents]);const Ae=x.useRef(!1),ce=x.useRef(O);x.useEffect(()=>{if(Ae.current){Ae.current=!1,ce.current=O;return}ce.current!==O&&(h("documents",O),ce.current=O)},[O]);const pe=()=>{switch(S){case 1:return e.jsx(n5,{templates:Jx,selectedTemplate:g,onSelectTemplate:ue,adminTemplates:d});case 2:return e.jsx(l5,{formData:u,selectedTemplate:g,updateFormData:h});case 3:return e.jsx(o5,{formData:u,updateFormData:h,systemPolicy:j,onValidationError:Te=>H(Te.type,Te.email,Te.message),onPolicyViolation:_});case 4:return e.jsx(c5,{formData:u,updateFormData:h,onValidationError:Te=>H(Te.type,Te.email,Te.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(d5,{documentPolicy:y,isEditing:o,documents:O,existingDocuments:v,documentsToDelete:B,onDocumentsChange:I,onExistingDocumentsChange:w,onDocumentsToDeleteChange:T,onPreviewDocument:_e,onDocumentErrors:Te=>z(Te),fileInputRef:M});case 6:return e.jsx(u5,{formData:u,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(x5,{isEditing:o,currentStep:S,totalSteps:C,stepNames:E,onBack:re}),e.jsx(M0,{currentStep:S,totalSteps:C,stepNames:E}),e.jsx(h5,{children:pe()}),e.jsx(r5,{currentStep:S,totalSteps:C,isStepValid:R(),onPrev:De,onNext:Ze,onSubmit:V,onSaveDraft:Q,submitting:W,savingDraft:U,loadingDraft:f,isEditing:o}),e.jsx(ST,{open:ee,onClose:()=>K(!1),onSelectTemplate:Le}),q&&e.jsx(Gr,{fileName:q.fileName,fileType:q.fileType,fileUrl:q.fileUrl,fileSize:q.fileSize,open:!!q,onClose:Ue,onDownload:async()=>{if(q.file){const Te=document.createElement("a");Te.href=q.fileUrl,Te.download=q.fileName,document.body.appendChild(Te),Te.click(),document.body.removeChild(Te)}else q.documentId&&await _s(q.documentId)},attachmentId:q.documentId}),e.jsx(p5,{modal:F,onClose:$}),e.jsx(g5,{modal:A,documentPolicy:y,onClose:X}),e.jsx(pi,{open:D.open,onClose:L,violations:D.violations,policyDetails:{maxApprovalLevels:j.maxApprovalLevels,maxParticipants:j.maxParticipants,allowSpectators:j.allowSpectators,maxSpectators:j.maxSpectators}})]})}function gi({className:t,...s}){return e.jsx(Db,{"data-slot":"tabs",className:Me("flex flex-col gap-2",t),...s})}function fi({className:t,...s}){return e.jsx(Rb,{"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(Fb,{"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(Ib,{"data-slot":"tabs-content",className:Me("flex-1 outline-none",t),...s})}function ai(t){if(!t)return!1;const s=t.request||t;return s.workflowType==="CLAIM_MANAGEMENT"||s.templateType==="claim-management"||s.template==="claim-management"||s.templateName==="Claim Management"||s.templateCode==="CLAIM_MANAGEMENT"}function gd(t,s=[],a){const[r,n]=x.useState(null),[i,l]=x.useState(!1),[o,c]=x.useState(!0),[d,m]=x.useState(null),[p,u]=x.useState(null),[h,g]=x.useState(!1),b=(S,C)=>(S||C||"NA").toString().split(" ").map(R=>R[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=x.useCallback(async()=>{var S,C,E,R,k,N,O,I,B,T,M,F,D,A,H;l(!0);try{const $=await Gs.getWorkflowDetails(t);if(!$){console.warn("[useRequestDetails] No details returned from API");return}const _=$.workflow||{},L=Array.isArray($.approvals)?$.approvals:[],z=Array.isArray($.participants)?$.participants:[],X=Array.isArray($.documents)?$.documents:[],W=$.summary||{},U=Array.isArray($.tatAlerts)?$.tatAlerts:[];U.length>0;const V=(W==null?void 0:W.currentLevel)||_.currentLevel||1,Q=L.map(de=>{const me=de.levelNumber||0,Ne=(de.status||"").toString().toUpperCase(),Oe=de.levelId||de.level_id;let st=f(de.status);me>V&&Ne!=="APPROVED"&&Ne!=="REJECTED"?st="waiting":me===V&&Ne==="PENDING"&&(st="pending");const nt=U.filter(St=>St.levelId===Oe);return{step:me,levelId:Oe,role:de.levelName||de.approverName||"Approver",status:st,approver:de.approverName||de.approverEmail,approverId:de.approverId||de.approver_id,approverEmail:de.approverEmail,tatHours:Number(de.tatHours||0),elapsedHours:Number(de.elapsedHours||0),remainingHours:Number(de.remainingHours||0),tatPercentageUsed:Number(de.tatPercentageUsed||0),actualHours:de.levelEndTime&&de.levelStartTime?Math.max(0,(new Date(de.levelEndTime).getTime()-new Date(de.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:de.comments||void 0,timestamp:de.actionDate||void 0,levelStartTime:de.levelStartTime||de.tatStartTime,tatAlerts:nt,skipReason:de.skipReason||void 0,isSkipped:Ne==="SKIPPED"||de.isSkipped||!1}}),ee=z.filter(de=>(de.participantType||de.participant_type||"").toUpperCase()==="SPECTATOR").map(de=>({name:de.userName||de.user_name||de.userEmail||de.user_email,role:"Spectator",email:de.userEmail||de.user_email,avatar:b(de.userName||de.user_name,de.userEmail||de.user_email)})),K=de=>{var Ne,Oe;if(!de)return;const me=z.find(st=>st.userId===de||st.user_id===de);return me!=null&&me.userName||me!=null&&me.user_name?me.userName||me.user_name:_.initiatorId===de?((Ne=_.initiator)==null?void 0:Ne.displayName)||((Oe=_.initiator)==null?void 0:Oe.email):de},q=X.map(de=>{const me=Number(de.fileSize||de.file_size||0),Ne=(me/(1024*1024)).toFixed(2)+" MB";return{documentId:de.documentId||de.document_id,name:de.originalFileName||de.fileName||de.file_name,fileType:de.fileType||de.file_type||"",size:Ne,sizeBytes:me,uploadedBy:K(de.uploadedBy||de.uploaded_by),uploadedAt:de.uploadedAt||de.uploaded_at}}),ue=Array.isArray($.activities)?$.activities.filter(de=>(de.type||"").toLowerCase()!=="sla_warning"):[];let Le=null;if(_.isPaused||!1)try{Le=await ku(_.requestId)}catch{}let De=null,_e=null,Ue=null,re=null,fe=[],Ce=null;if(ai(_)){try{const de=await be.get(`/dealer-claims/${_.requestId}/credit-note-wfm`),me=de.data??de;Ce=Array.isArray(me==null?void 0:me.data)?me.data:Array.isArray(me)?me:[]}catch(de){console.warn("[useRequestDetails] Error fetching credit note WFM data:",de)}try{const de=await be.get(`/dealer-claims/${_.requestId}`),me=((S=de.data)==null?void 0:S.data)||de.data;if(me){De=me.claimDetails||me.claim_details,_e=me.proposalDetails||me.proposal_details,Ue=me.completionDetails||me.completion_details,re=me.internalOrder||me.internal_order||null,fe=me.internalOrders||me.internal_orders||[];const Ne=me.budgetTracking||me.budget_tracking||null,Oe=me.invoice||null,st=me.creditNote||me.credit_note||null,nt=me.completionExpenses||me.completion_expenses||null;De&&(De.budgetTracking=Ne,De.invoice=Oe,De.creditNote=st,De.completionExpenses=nt,De.creditNoteWfmData=Ce)}else console.warn("[useRequestDetails] No claimData found in response")}catch(de){console.error("[useRequestDetails] Error fetching claim details:",{error:(de==null?void 0:de.message)||de,status:(C=de==null?void 0:de.response)==null?void 0:C.status,statusText:(E=de==null?void 0:de.response)==null?void 0:E.statusText,responseData:(R=de==null?void 0:de.response)==null?void 0:R.data,requestId:_.requestId})}}const Ae={..._,id:_.requestNumber||_.requestId,requestId:_.requestId,requestNumber:_.requestNumber,initiatorId:_.initiatorId||_.initiator_id,title:_.title,description:_.description,status:f(_.status),priority:(_.priority||"").toString().toLowerCase(),workflowType:_.workflowType||(_.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:Q,approvals:L,participants:z,documents:q,spectators:ee,summary:W,sla:(W==null?void 0:W.sla)||_.sla||null,initiator:{userId:((k=_.initiator)==null?void 0:k.userId)||((N=_.initiator)==null?void 0:N.user_id)||_.initiatorId||_.initiator_id,name:((O=_.initiator)==null?void 0:O.displayName)||((I=_.initiator)==null?void 0:I.email),role:((B=_.initiator)==null?void 0:B.designation)||void 0,department:((T=_.initiator)==null?void 0:T.department)||void 0,email:((M=_.initiator)==null?void 0:M.email)||void 0,phone:((F=_.initiator)==null?void 0:F.phone)||void 0,avatar:b((D=_.initiator)==null?void 0:D.displayName,(A=_.initiator)==null?void 0:A.email)},createdAt:_.createdAt,updatedAt:_.updatedAt,totalSteps:_.totalLevels||1,currentStepRaw:(W==null?void 0:W.currentLevel)||_.currentLevel||1,currentStep:Math.min(Math.max(1,(W==null?void 0:W.currentLevel)||_.currentLevel||1),_.totalLevels||1),auditTrail:ue,conclusionRemark:_.conclusionRemark||null,closureDate:_.closureDate||null,pauseInfo:Le||null,claimDetails:De||null,proposalDetails:_e||null,completionDetails:Ue||null,internalOrder:re||null,internalOrders:fe||[],budgetTracking:(De==null?void 0:De.budgetTracking)||null,invoice:(De==null?void 0:De.invoice)||(De==null?void 0:De.invoice)||null,creditNote:(De==null?void 0:De.creditNote)||null,creditNoteWfmData:Ce||(De==null?void 0:De.creditNoteWfmData)||null,completionExpenses:(De==null?void 0:De.completionExpenses)||null,templateType:_.templateType||_.template_type,form16Submission:$.form16Submission||null};n(Ae);const ce=(H=a==null?void 0:a.email)==null?void 0:H.toLowerCase(),pe=L.find(de=>{const me=(de.status||"").toString().toUpperCase(),Ne=(de.approverEmail||"").toLowerCase(),Oe=de.levelNumber||0;return(me==="PENDING"||me==="IN_PROGRESS"||me==="PAUSED")&&Ne===ce&&Oe===V});u(pe||null);const Te=a==null?void 0:a.userId;if(Te){const de=z.some(me=>(me.participantType||me.participant_type||"").toUpperCase()==="SPECTATOR"&&(me.userId||me.user_id)===Te);g(de)}else g(!1)}catch($){console.error("[useRequestDetails] Error refreshing details:",$),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);x.useEffect(()=>{if(!t){c(!1);return}let S=!0;return c(!0),m(null),(async()=>{var C,E,R,k,N,O,I,B,T,M,F,D,A,H;try{const $=await Gs.getWorkflowDetails(t);if(!S||!$){S&&c(!1);return}const _=$.workflow||{},L=Array.isArray($.approvals)?$.approvals:[],z=Array.isArray($.participants)?$.participants:[],X=Array.isArray($.documents)?$.documents:[],W=$.summary||{},U=Array.isArray($.tatAlerts)?$.tatAlerts:[],V=(_.priority||"").toString().toLowerCase(),Q=(W==null?void 0:W.currentLevel)||_.currentLevel||1,ee=L.map(me=>{const Ne=me.levelNumber||0,Oe=(me.status||"").toString().toUpperCase(),st=me.levelId||me.level_id;let nt=f(me.status);Oe==="PAUSED"?nt="paused":Ne>Q&&Oe!=="APPROVED"&&Oe!=="REJECTED"?nt="waiting":Ne===Q&&(Oe==="PENDING"||Oe==="IN_PROGRESS")&&(nt=Oe==="IN_PROGRESS"?"in-review":"pending");const St=U.filter(Mt=>Mt.levelId===st);return{step:Ne,levelId:st,role:me.levelName||me.approverName||"Approver",status:nt,approver:me.approverName||me.approverEmail,approverId:me.approverId||me.approver_id,approverEmail:me.approverEmail,tatHours:Number(me.tatHours||0),elapsedHours:Number(me.elapsedHours||0),remainingHours:Number(me.remainingHours||0),tatPercentageUsed:Number(me.tatPercentageUsed||0),actualHours:me.elapsedHours!==void 0&&me.elapsedHours!==null?Number(me.elapsedHours):void 0,comment:me.comments||void 0,timestamp:me.actionDate||void 0,levelStartTime:me.levelStartTime||me.tatStartTime,tatAlerts:St}}),K=z.filter(me=>(me.participantType||"").toUpperCase()==="SPECTATOR").map(me=>({name:me.userName||me.userEmail,role:"Spectator",avatar:b(me.userName,me.userEmail)})),q=me=>{var Oe,st;if(!me)return;const Ne=z.find(nt=>nt.userId===me);return Ne!=null&&Ne.userName?Ne.userName:_.initiatorId===me?((Oe=_.initiator)==null?void 0:Oe.displayName)||((st=_.initiator)==null?void 0:st.email):me},ue=X.map(me=>{const Ne=Number(me.fileSize||0),Oe=(Ne/(1024*1024)).toFixed(2)+" MB";return{documentId:me.documentId||me.document_id,name:me.originalFileName||me.fileName,fileType:me.fileType||me.file_type||"",size:Oe,sizeBytes:Ne,uploadedBy:q(me.uploadedBy),uploadedAt:me.uploadedAt}}),Le=Array.isArray($.activities)?$.activities.filter(me=>(me.type||"").toLowerCase()!=="sla_warning"):[];let Ze=null;if(_.isPaused||!1)try{Ze=await ku(_.requestId)}catch{}let _e=null,Ue=null,re=null,fe=null,Ce=[],Ae=null;if(ai(_)){try{const me=await be.get(`/dealer-claims/${_.requestId}/credit-note-wfm`),Ne=me.data??me;Ae=Array.isArray(Ne==null?void 0:Ne.data)?Ne.data:Array.isArray(Ne)?Ne:[]}catch(me){console.warn("[useRequestDetails] Error fetching credit note WFM data:",me)}try{const me=await be.get(`/dealer-claims/${_.requestId}`),Ne=((C=me.data)==null?void 0:C.data)||me.data;if(Ne){_e=Ne.claimDetails||Ne.claim_details,Ue=Ne.proposalDetails||Ne.proposal_details,re=Ne.completionDetails||Ne.completion_details,fe=Ne.internalOrder||Ne.internal_order||null,Ce=Ne.internalOrders||Ne.internal_orders||[];const Oe=Ne.budgetTracking||Ne.budget_tracking||null,st=Ne.invoice||null,nt=Ne.creditNote||Ne.credit_note||null,St=Ne.completionExpenses||Ne.completion_expenses||null;_e&&(_e.budgetTracking=Oe,_e.invoice=st,_e.creditNote=nt,_e.completionExpenses=St,_e.creditNoteWfmData=Ae)}}catch(me){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(me==null?void 0:me.message)||me,status:(E=me==null?void 0:me.response)==null?void 0:E.status,requestId:_.requestId})}}const ce={id:_.requestNumber||_.requestId,requestId:_.requestId,title:_.title,description:_.description,priority:V,status:f(_.status),workflowType:_.workflowType||(_.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:W,initiator:{name:((R=_.initiator)==null?void 0:R.displayName)||((k=_.initiator)==null?void 0:k.email),role:((N=_.initiator)==null?void 0:N.designation)||void 0,department:((O=_.initiator)==null?void 0:O.department)||void 0,email:((I=_.initiator)==null?void 0:I.email)||void 0,phone:((B=_.initiator)==null?void 0:B.phone)||void 0,avatar:b((T=_.initiator)==null?void 0:T.displayName,(M=_.initiator)==null?void 0:M.email)},createdAt:_.createdAt,updatedAt:_.updatedAt,totalSteps:_.totalLevels||1,currentStepRaw:(W==null?void 0:W.currentLevel)||_.currentLevel||1,currentStep:Math.min(Math.max(1,(W==null?void 0:W.currentLevel)||_.currentLevel||1),_.totalLevels||1),approvalFlow:ee,approvals:L,documents:ue,spectators:K,auditTrail:Le,conclusionRemark:_.conclusionRemark||null,closureDate:_.closureDate||null,pauseInfo:Ze||null,claimDetails:_e||null,proposalDetails:Ue||null,completionDetails:re||null,internalOrder:fe||null,internalOrders:Ce||[],budgetTracking:(_e==null?void 0:_e.budgetTracking)||null,invoice:(_e==null?void 0:_e.invoice)||null,creditNote:(_e==null?void 0:_e.creditNote)||null,creditNoteWfmData:Ae||(_e==null?void 0:_e.creditNoteWfmData)||null,completionExpenses:(_e==null?void 0:_e.completionExpenses)||null,templateType:_.templateType||_.template_type,form16Submission:$.form16Submission||null};n(ce);const pe=(F=a==null?void 0:a.email)==null?void 0:F.toLowerCase(),Te=L.find(me=>{const Ne=(me.status||"").toString().toUpperCase(),Oe=(me.approverEmail||"").toLowerCase(),st=me.levelNumber||0;return(Ne==="PENDING"||Ne==="IN_PROGRESS"||Ne==="PAUSED")&&Oe===pe&&st===Q});u(Te||null);const de=a==null?void 0:a.userId;if(de){const me=z.some(Ne=>(Ne.participantType||"").toUpperCase()==="SPECTATOR"&&Ne.userId===de);g(me)}else g(!1)}catch($){if(console.error("[useRequestDetails] Error loading request details:",$),S){if(((D=$==null?void 0:$.response)==null?void 0:D.status)===403){const _=((H=(A=$==null?void 0:$.response)==null?void 0:A.data)==null?void 0:H.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:_})}n(null)}}finally{S&&c(!1)}})(),()=>{S=!1}},[t,a]);const y=x.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=x.useMemo(()=>{var E,R,k;if(!y||!a)return!1;const S=(E=a==null?void 0:a.email)==null?void 0:E.toLowerCase(),C=(k=(R=y.initiator)==null?void 0:R.email)==null?void 0:k.toLowerCase();return S===C},[y,a]),w=x.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(E=>{E.approverEmail&&S.push({email:E.approverEmail.toLowerCase(),participantType:"APPROVER",name:E.approver})}),y.spectators&&Array.isArray(y.spectators)&&y.spectators.forEach(E=>{E.email&&S.push({email:E.email.toLowerCase(),participantType:"SPECTATOR",name:E.name})}),y.participants&&Array.isArray(y.participants)&&y.participants.forEach(E=>{const R=(E.userEmail||E.email||"").toLowerCase(),k=(E.participantType||E.participant_type||"").toUpperCase(),N=E.userName||E.user_name||E.name;R&&k&&!S.find(O=>O.email===R)&&S.push({email:R,participantType:k,name:N})}),S},[y]);return x.useEffect(()=>{if(!t||!r)return;const S=$r();if(!S)return;const C=E=>{((E==null?void 0:E.requestId)===r.requestId||(E==null?void 0:E.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:h,isInitiator:v,existingParticipants:w,accessDenied:d}}function $0(t,s,a,r){const[n,i]=x.useState([]),[l,o]=x.useState(0),[c,d]=x.useState([]);return x.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 Gs.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 u=$r();if(!u){console.error("[useRequestSocket] Socket not available");return}const h=r==null?void 0:r.userId,g=()=>{Eo(u,p,h)};return u.connected?g():u.on("connect",g),()=>{m&&(u.off("connect",g),mp(u,p))}})(),()=>{m=!1}},[t,r]),x.useEffect(()=>{!t||!s||(async()=>{try{const m=await mn(t),p=s.auditTrail||[],u=[...m,...p];u.sort((h,g)=>{const b=new Date(h.createdAt||h.created_at||h.timestamp||0).getTime(),f=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return b-f}),i(u)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),x.useEffect(()=>{if(!t)return;const m=$r();if(!m)return;const p=h=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await mn(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)}})()},u=h=>{const g=h.type==="breach"?"⏰":h.type==="threshold2"?"⚠️":"⏳";(async()=>{try{const b=await Gs.getWorkflowDetails(t);b&&(Array.isArray(b.tatAlerts)&&b.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:h.message,icon:"/favicon.ico",tag:`tat-${h.requestId}-${h.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",u),()=>{m.off("noteHandler",p),m.off("worknote:new",p),m.off("tat:alert",u)}},[t,a,s]),x.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function Un(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 f5=["MALWARE_DETECTED","FILE_VALIDATION_FAILED","CONTENT_THREAT_DETECTED","SCAN_UNAVAILABLE","SCAN_ERROR"],b5={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 fd(t){var l,o,c,d;const s=(l=t==null?void 0:t.response)==null?void 0:l.data;if(!(s!=null&&s.error))return!1;const a=s.error;if(!f5.includes(a))return!1;const r=b5[a]||"Security Error",n=s.message||"File was blocked by security scan";let i="";return s.details&&((o=s.details.signatures)!=null&&o.length?i=`Virus: ${s.details.signatures.join(", ")}`:(c=s.details.errors)!=null&&c.length?i=s.details.errors[0]||"":(d=s.details.threats)!=null&&d.length&&(i=s.details.threats.map(m=>m.description).join(", "))),G.error(r,{description:i||n,duration:8e3,style:{background:"#fef2f2",border:"1px solid #fca5a5",color:"#991b1b"}}),!0}function U0(t,s){const[a,r]=x.useState(!1),[n,i]=x.useState(null),[l,o]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=x.useState({show:!1,errors:[]});x.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=h=>{const g=l.maxFileSizeMB*1024*1024;if(h.size>g)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${l.maxFileSizeMB}MB. Current size: ${(h.size/(1024*1024)).toFixed(2)}MB`};const b=h.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 h=>{var y,v;const g=h.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&&d({show:!0,errors:f}),j.length===0){h.target&&(h.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 Un(w,S,"SUPPORTING"),await s(),j.length{const h=document.createElement("input");h.type="file",h.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),h.onchange=p,h.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}const j5="modulepreload",y5=function(t){return"/"+t},sh={},co=function(s,a,r){let n=Promise.resolve();if(a&&a.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));n=Promise.allSettled(a.map(c=>{if(c=y5(c),c in sh)return;sh[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const p=document.createElement("link");if(p.rel=d?"stylesheet":j5,d||(p.as="script"),p.crossOrigin="",p.href=c,o&&p.setAttribute("nonce",o),document.head.appendChild(p),d)return new Promise((u,h)=>{p.addEventListener("load",u),p.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return n.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};function B0(t,s,a,r,n,i,l){const[o,c]=x.useState(""),[d,m]=x.useState(!1),[p,u]=x.useState(!1),[h,g]=x.useState(!1),[b,f]=x.useState(0),[j,y]=x.useState(!1),[v,w]=x.useState(!1),[S,C]=x.useState(0),E=async()=>{var I;const N=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),O=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(N||O){c(N||O),g(!!O);return}try{const{getConclusion:B}=await co(async()=>{const{getConclusion:M}=await import("./conclusionApi-ZgWYxicR.js");return{getConclusion:M}},__vite__mapDeps([0,1,2,3,4,5,6,7])),T=await B(t.requestId||s);T&&(T.aiGeneratedRemark||T.finalRemark)&&(c(T.finalRemark||T.aiGeneratedRemark||""),g(!!T.aiGeneratedRemark))}catch(B){((I=B==null?void 0:B.response)==null?void 0:I.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",B)}},R=async()=>{if(!v)try{m(!0),y(!1);const{generateConclusion:N}=await co(async()=>{const{generateConclusion:T}=await import("./conclusionApi-ZgWYxicR.js");return{generateConclusion:T}},__vite__mapDeps([0,1,2,3,4,5,6,7])),O=await N(t.requestId||s),I=b+1;if(f(I),!(O!=null&&O.aiGeneratedRemark)||O.aiGeneratedRemark.toLowerCase().includes("unable to generate")||O.aiGeneratedRemark.toLowerCase().includes("sorry")){const T=S+1;C(T),T>=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),c((O==null?void 0:O.aiGeneratedRemark)||""),g(!1);return}c(O.aiGeneratedRemark),g(!0),C(0),I>=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 O=S+1;C(O),g(!1),O>=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)}},k=async()=>{var O,I;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{u(!0);const{finalizeConclusion:B}=await co(async()=>{const{finalizeConclusion:T}=await import("./conclusionApi-ZgWYxicR.js");return{finalizeConclusion:T}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await B(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(B){i==null||i({success:!1,title:"Error",message:((I=(O=B.response)==null?void 0:O.data)==null?void 0:I.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{u(!1)}};return x.useEffect(()=>{var T;const N=(T=t==null?void 0:t.status)==null?void 0:T.toLowerCase();if(!((N==="approved"||N==="rejected"||N==="closed")&&a&&!o))return;const I=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),B=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);I||B?(c(I||B),g(!!B)):E()},[t==null?void 0:t.status,t==null?void 0:t.conclusionRemark,t==null?void 0:t.aiGeneratedConclusion,a,o]),{conclusionRemark:o,setConclusionRemark:c,conclusionLoading:d,conclusionSubmitting:p,aiGenerated:h,handleGenerateConclusion:R,handleFinalizeConclusion:k,generationAttempts:b,generationFailed:j,maxAttemptsReached:v}}function V0(t,s,a){const[r,n]=x.useState(!1),[i,l]=x.useState(!1),[o,c]=x.useState(!1),[d,m]=x.useState(!1),[p,u]=x.useState(!1),[h,g]=x.useState(!1),[b,f]=x.useState(null),[j,y]=x.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:p,setShowSkipApproverModal:u,showActionStatusModal:h,setShowActionStatusModal:g,skipApproverData:b,setSkipApproverData:f,actionStatus:j,setActionStatus:y,handleApproveConfirm:async R=>{var N,O;const k=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!k){alert("Approval level not found");return}await On(t,k,R||""),await new Promise(I=>setTimeout(I,500)),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(O=window==null?void 0:window.toast)==null||O.call(window,"Approved successfully")},handleRejectConfirm:async R=>{var N,O;if(!(R!=null&&R.trim())){alert("Comments & remarks are required");return}const k=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!k){alert("Approval level not found");return}await Tr(t,k,R.trim(),R.trim()),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(O=window==null?void 0:window.toast)==null||O.call(window,"Rejected successfully")},handleAddApprover:async(R,k,N)=>{var O,I;try{await Qp(t,R,k,N),await a(),c(!1),y==null||y({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${k}h TAT`}),g==null||g(!0)}catch(B){throw y==null||y({success:!1,title:"Failed to Add Approver",message:((I=(O=B==null?void 0:B.response)==null?void 0:O.data)==null?void 0:I.error)||"Failed to add approver. Please try again."}),g==null||g(!0),B}},handleSkipApprover:async R=>{var k,N;if(b)try{await N1(t,b.levelId,R),await a(),u(!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(O){throw y==null||y({success:!1,title:"Failed to Skip Approver",message:((N=(k=O==null?void 0:O.response)==null?void 0:k.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),O}},handleAddSpectator:async R=>{var k,N;try{await Xp(t,R),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(O){throw y==null||y({success:!1,title:"Failed to Add Spectator",message:((N=(k=O==null?void 0:O.response)==null?void 0:k.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),O}}}}function v5({requestId:t,request:s,onRefresh:a}){const[r,n]=x.useState(null),[i,l]=x.useState(!0),[o,c]=x.useState(null),m=!!(s==null?void 0:s.form16Submission),p=!!r&&r.status!=="withdrawn";x.useEffect(()=>{if(!t){l(!1);return}let g=!1;return(async()=>{try{const b=await Pp(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 u=async()=>{if(!(!t||!window.confirm("Cancel this Form 16 submission? The request will be marked as rejected."))){c("cancel");try{await jv(t),G.success("Submission cancelled"),a==null||a()}catch(g){G.error(g instanceof Error?g.message:"Failed to cancel submission")}finally{c(null)}}},h=async()=>{if(!(!t||!window.confirm("Mark this submission as resubmission needed? The dealer will need to resubmit Form 16."))){c("resubmit");try{await yv(t),G.success("Marked as resubmission needed"),a==null||a()}catch(g){G.error(g instanceof Error?g.message:"Failed to update")}finally{c(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(ie,{className:"pb-2",children:[e.jsxs(le,{className:"text-sm flex items-center gap-2 text-blue-800",children:[e.jsx(_t,{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(P,{variant:"outline",size:"sm",className:"w-full justify-start border-red-300 text-red-700 hover:bg-red-50",onClick:u,disabled:!!o,children:[o==="cancel"?e.jsx(ze,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(jt,{className:"w-3 h-3 mr-1"}),"Cancel submission"]}),e.jsxs(P,{variant:"outline",size:"sm",className:"w-full justify-start border-amber-300 text-amber-700 hover:bg-amber-50",onClick:h,disabled:!!o,children:[o==="resubmit"?e.jsx(ze,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(Wh,{className:"w-3 h-3 mr-1"}),"Resubmission needed"]})]})]})}const N5=t=>{const s=(t||"").toLowerCase();return s.includes("image")||s.includes("pdf")||s.includes("jpg")||s.includes("jpeg")||s.includes("png")||s.includes("gif")};function Or({document:t,onPreview:s,onDownload:a,showPreview:r=!0,testId:n="document-card"}){return e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors","data-testid":`${n}-${t.documentId}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Re,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900","data-testid":`${n}-name`,children:t.name}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${n}-metadata`,children:[t.size&&e.jsxs("span",{children:[t.size," • "]}),t.uploadedBy&&e.jsxs("span",{children:["Uploaded by ",t.uploadedBy," on "]}),bs(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&N5(t.fileType)&&s&&e.jsx(P,{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(vt,{className:"w-4 h-4"})}),a&&e.jsx(P,{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(Tt,{className:"w-4 h-4"})})]})]})}function w5({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l,isSpectator:o=!1}){var d,m,p,u;const c=((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:[c&&((m=(d=t==null?void 0:t.form16Submission)==null?void 0:d.previousDocuments)==null?void 0:m.length)>0&&e.jsxs(Z,{children:[e.jsxs(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2 text-sm sm:text-base text-amber-800",children:[e.jsx(Re,{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," ",(u=t==null?void 0:t.form16Submission)==null?void 0:u.quarter,")"]})]}),e.jsx(te,{children:e.jsx("div",{className:"space-y-4",children:(()=>{const h=new Map;for(const g of t.form16Submission.previousDocuments){const b=g.requestId||g.request_id,f=g.requestNumber||b;h.has(f)||h.set(f,[]),h.get(f).push(g)}return Array.from(h.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(Or,{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(ie,{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(le,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),c?"Current submission":"Request Documents"]}),e.jsx(ye,{className:"text-xs sm:text-sm mt-1",children:c?"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(P,{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(ys,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a?"Uploading...":t.status==="closed"?"Closed":"Upload",e.jsx("span",{className:"hidden sm:inline",children:t.status==="closed"?"":"Document"})]}),e.jsxs("p",{className:"text-xs text-gray-500 whitespace-nowrap",children:["Max ",r.maxFileSizeMB,"MB"]})]})]})}),e.jsx(te,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((h,g)=>e.jsx(Or,{document:h,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"})})]}),!c&&e.jsxs(Z,{children:[e.jsxs(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(zs,{className:"w-4 h-4 sm:w-5 sm:h-5 text-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((h,g)=>e.jsx(Or,{document:{documentId:h.attachmentId||"",name:h.name,fileType:h.type||"",size:h.size?`${(h.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:h.size,uploadedBy:h.uploadedBy,uploadedAt:h.uploadedAt},onPreview:b=>i(b),onDownload:async b=>{const{downloadWorkNoteAttachment:f}=require("@/services/workflowApi");await f(b)},testId:"worknote-attachment"},h.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 C5=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"}}},ah=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending",icon:rt,iconColor:"text-yellow-600"};case"paused":return{color:"bg-gray-400 text-gray-100 border-gray-500",label:"paused",icon:ss,iconColor:"text-gray-600"};case"in-review":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"in-review",icon:Pt,iconColor:"text-blue-600"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved",icon:Be,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:Be,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:ss,iconColor:"text-gray-600"}}},S5=t=>{switch(t){case"approval":case"approved":return e.jsx(Be,{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(zs,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx(Pt,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(ml,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Re,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(rt,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(ll,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(ss,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(Bt,{className:"w-5 h-5 text-gray-600"})}};function A5(t){const s=t==null?void 0:t.form16Submission;if(!s)return[];const a=[],r=Array.isArray(s.previousSubmissions)?s.previousSubmissions:[];for(const h of r){const g=h.requestNumber||h.requestId||"",b=h.submittedDate?new Date(h.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}),h.creditNoteNumber){const f=h.creditNoteIssueDate?new Date(h.creditNoteIssueDate).toISOString():b;a.push({type:"status_change",action:"Credit note issued",details:`Credit note ${h.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||""||"",c=(s.displayStatus||"").toLowerCase(),d=!!(s.ocrExtractedData&&typeof s.ocrExtractedData=="object"&&Object.keys(s.ocrExtractedData).length>0),m=!!s.creditNoteNumber,p=c==="balance mismatch"||l==="failed"&&!m||l==="failed"&&/mismatch|26as|value/i.test(o),u=c==="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:d?"Certificate data was extracted from the uploaded PDF.":"OCR extraction was performed on the uploaded document.",timestamp:i}),p?a.push({type:"rejection",action:"26AS matching",details:"Values of Form 16 did not match with 26AS. Please submit Form 16 with correct data.",timestamp:i}):u?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 h=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:h})}return a.sort((h,g)=>new Date(h.timestamp).getTime()-new Date(g.timestamp).getTime())}function T5({request:t}){const s=((t==null?void 0:t.templateType)||(t==null?void 0:t.template_type)||"").toString().toUpperCase()==="FORM_16",a=s?A5(t):[],r=t.auditTrail&&Array.isArray(t.auditTrail)?t.auditTrail:[],n=a.length>0?[...a,...r].sort((i,l)=>{const o=i.timestamp?new Date(i.timestamp).getTime():0,c=l.timestamp?new Date(l.timestamp).getTime():0;return o-c}):r;return e.jsxs(Z,{children:[e.jsxs(ie,{children:[e.jsxs(le,{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:S5(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:bs(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 z0({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsx(ht,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[a?e.jsx(Be,{className:"w-5 h-5 text-green-600"}):e.jsx(Je,{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(Be,{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(Dt,{children:e.jsx(P,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function H0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=x.useState(""),[l,o]=x.useState(!1),[c,d]=x.useState([]),[m,p]=x.useState(!1),[u,h]=x.useState(null),g=x.useRef(null),b=x.useRef(null),[f,j]=x.useState({open:!1,type:"error",email:"",message:""}),[y,v]=x.useState({open:!1,violations:[]}),[w,S]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});x.useEffect(()=>{t&&(async()=>{var O;try{const I=await ma("WORKFLOW_SHARING"),B=await ma("TAT_SETTINGS"),T=[...I,...B],M={};T.forEach(F=>{M[F.configKey]=F.configValue}),S({maxApprovalLevels:parseInt(M.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(M.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((O=M.ALLOW_ADD_SPECTATOR)==null?void 0:O.toLowerCase())==="true",maxSpectators:parseInt(M.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(I){console.error("Failed to load system policy:",I)}})()},[t]);const C=async()=>{var D,A;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 I=r.find(H=>(H.email||"").toLowerCase()===N);if(I){const H=((D=I.participantType)==null?void 0:D.toUpperCase())||"PARTICIPANT",$=I.name||N;if(H==="INITIATOR"){j({open:!0,type:"error",email:N,message:`${$} is the request initiator and cannot be added as a spectator.`});return}else if(H==="APPROVER"){j({open:!0,type:"error",email:N,message:`${$} is already an approver on this request and cannot be added as a spectator.`});return}else if(H==="SPECTATOR"){j({open:!0,type:"error",email:N,message:`${$} is already a spectator on this request.`});return}else{j({open:!0,type:"error",email:N,message:`${$} is already a participant on this request.`});return}}const B=[];w.allowSpectators||B.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const M=r.filter(H=>(H.participantType||"").toUpperCase()==="SPECTATOR").length;M>=w.maxSpectators&&B.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:M,maxValue:w.maxSpectators});const F=r.length+1;if(F>w.maxParticipants&&B.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:F,maxValue:w.maxParticipants}),B.length>0){v({open:!0,violations:B});return}if(!u||u.email.toLowerCase()!==N)try{const $=((A=(await va(N,1)).data)==null?void 0:A.data)||[];if($.length===0){j({open:!0,type:"not-found",email:N,message:""});return}const _=$[0];await ja({userId:_.userId,email:_.email,displayName:_.displayName,firstName:_.firstName,lastName:_.lastName,department:_.department,phone:_.phone,mobilePhone:_.mobilePhone,designation:_.designation,jobTitle:_.jobTitle,manager:_.manager,employeeId:_.employeeId,employeeNumber:_.employeeNumber,secondEmail:_.secondEmail,location:_.location})}catch(H){console.error("Failed to validate spectator:",H),j({open:!0,type:"error",email:N,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(N),i(""),h(null),s()}catch(H){console.error("Failed to add spectator:",H)}finally{o(!1)}},E=()=>{l||(i(""),h(null),d([]),p(!1),s())};x.useEffect(()=>{c.length>0&&b.current&&b.current.scrollTo({top:b.current.scrollHeight,behavior:"smooth"})},[c.length]),x.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const R=N=>{if(i(N),u&&u.email.toLowerCase()!==N.toLowerCase()&&h(null),g.current&&clearTimeout(g.current),!N||!N.startsWith("@")||N.length<2){d([]),p(!1);return}p(!0),g.current=setTimeout(async()=>{var O;try{const I=N.slice(1),T=((O=(await va(I,10)).data)==null?void 0:O.data)||[];d(T)}catch(I){console.error("Search failed:",I),d([])}finally{p(!1)}},300)},k=async N=>{try{await ja({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),h(N),d([]),p(!1)}catch(O){console.error("Failed to ensure user exists:",O),j({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(xt,{open:t,onOpenChange:E,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:E,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:l,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ht,{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(vt,{className:"w-5 h-5 text-purple-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:b,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a spectator to this request. They will receive notifications but cannot approve or reject."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(ul,{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=>R(N.target.value),className:"pl-10 h-11 border-gray-300",disabled:l,autoFocus:!0}),(m||c.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:m?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):c.length>0?e.jsx("ul",{className:"divide-y",children:c.map(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>k(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(N.displayName||N.email).split(" ").map(O=>O[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(P,{type:"button",variant:"outline",onClick:E,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(P,{type:"button",onClick:C,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(vt,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(xt,{open:f.open,onOpenChange:N=>j(O=>({...O,open:N})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:f.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Et,{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(dl,{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(Dt,{children:e.jsx(P,{onClick:()=>j(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(pi,{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 G0({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=x.useState(""),[d,m]=x.useState(24),[p,u]=x.useState(null),[h,g]=x.useState(!1),[b,f]=x.useState([]),[j,y]=x.useState(!1),[v,w]=x.useState(null),S=x.useRef(null),C=x.useRef(null),[E,R]=x.useState({open:!1,type:"error",email:"",message:""}),k=n.filter(A=>A&&(A.status==="approved"||A.status==="rejected"||A.status==="skipped")),N=Math.max(1,k.length+1),O=Math.max(1,n.length+1),I=O>=N?Array.from({length:O-N+1},(A,H)=>N+H):[N];x.useEffect(()=>{I.length>0&&p===null&&u(I[0]||null)},[I.length,p]);const B=async()=>{var z,X;const A=o.trim().toLowerCase();if(!A){R({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A)){R({open:!0,type:"error",email:A,message:"Please enter a valid email address"});return}if(!d||d<=0){R({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(d>720){R({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!p){R({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(p0?Math.max(...n.map(W=>W.levelNumber),0):0,_=p>$?p:$+1;if(i&&_>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${p} would result in ${_} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:_,maxValue:i}]):R({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${$} level(s).`});return}const L=r.find(W=>(W.email||"").toLowerCase()===A);if(L){const W=((z=L.participantType)==null?void 0:z.toUpperCase())||"PARTICIPANT",U=L.name||A;if(W==="INITIATOR"){R({open:!0,type:"error",email:A,message:`${U} is the request initiator and cannot be added as an approver.`});return}else if(W==="APPROVER"){R({open:!0,type:"error",email:A,message:`${U} is already an approver on this request.`});return}else if(W==="SPECTATOR"){R({open:!0,type:"error",email:A,message:`${U} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{R({open:!0,type:"error",email:A,message:`${U} is already a participant on this request.`});return}}if(!v||v.email.toLowerCase()!==A)try{const U=((X=(await va(A,1)).data)==null?void 0:X.data)||[];if(U.length===0){R({open:!0,type:"not-found",email:A,message:""});return}const V=U[0];await ja({userId:V.userId,email:V.email,displayName:V.displayName,firstName:V.firstName,lastName:V.lastName,department:V.department,phone:V.phone,mobilePhone:V.mobilePhone,designation:V.designation,jobTitle:V.jobTitle,manager:V.manager,employeeId:V.employeeId,employeeNumber:V.employeeNumber,secondEmail:V.secondEmail,location:V.location})}catch(W){console.error("Failed to validate approver:",W),R({open:!0,type:"error",email:A,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(A,d,p),c(""),m(24),u(null),w(null),s()}catch(W){console.error("Failed to add approver:",W)}finally{g(!1)}},T=()=>{h||(c(""),m(24),u(null),w(null),f([]),y(!1),s())},M=A=>{const H=A.toLowerCase();return H==="approved"?e.jsx(Be,{className:"w-4 h-4 text-green-600"}):H==="rejected"?e.jsx(Ct,{className:"w-4 h-4 text-red-600"}):H==="skipped"?e.jsx(Je,{className:"w-4 h-4 text-orange-600"}):H==="in-review"||H==="pending"?e.jsx(rt,{className:"w-4 h-4 text-blue-600"}):e.jsx(rt,{className:"w-4 h-4 text-gray-400"})};x.useEffect(()=>{b.length>0&&C.current&&C.current.scrollTo({top:C.current.scrollHeight,behavior:"smooth"})},[b.length]),x.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const F=A=>{if(c(A),v&&v.email.toLowerCase()!==A.toLowerCase()&&w(null),S.current&&clearTimeout(S.current),!A||!A.startsWith("@")||A.length<2){f([]),y(!1);return}y(!0),S.current=setTimeout(async()=>{var H;try{const $=A.slice(1),L=((H=(await va($,10)).data)==null?void 0:H.data)||[];f(L)}catch($){console.error("Search failed:",$),f([])}finally{y(!1)}},300)},D=async A=>{try{await ja({userId:A.userId,email:A.email,displayName:A.displayName,firstName:A.firstName,lastName:A.lastName,department:A.department,phone:A.phone,mobilePhone:A.mobilePhone,designation:A.designation,jobTitle:A.jobTitle,manager:A.manager,employeeId:A.employeeId,employeeNumber:A.employeeNumber,secondEmail:A.secondEmail,location:A.location}),c(A.email),w(A),f([]),y(!1)}catch(H){console.error("Failed to ensure user exists:",H),R({open:!0,type:"error",email:A.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(xt,{open:t,onOpenChange:T,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:T,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:h,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ht,{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(qt,{className:"w-5 h-5 text-blue-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref: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(A=>A.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(A=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${A.status==="approved"?"bg-green-100 border border-green-200":A.status==="rejected"?"bg-red-100 border border-red-200":A.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:A.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:A.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[A.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[M(A.status),e.jsx(ae,{variant:"outline",className:`text-xs ${A.status==="approved"?"bg-green-50 text-green-700 border-green-300":A.status==="rejected"?"bg-red-50 text-red-700 border-red-300":A.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:A.status})]})]},A.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(se,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(He,{value:(p==null?void 0:p.toString())||"",onValueChange:A=>u(Number(A)),disabled:h,children:[e.jsx(We,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select level"})}),e.jsx(Ye,{children:I.map(A=>e.jsx(J,{value:A.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fs,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",A]}),A<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",A,")"]})]})},A))})]}),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(se,{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:d,onChange:A=>m(Number(A.target.value)),className:"h-11 border-gray-300 flex-1",disabled:h,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(rt,{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(ul,{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:A=>F(A.target.value),className:"pl-10 h-11 border-gray-300",disabled:h,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(A=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>D(A),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(A.displayName||A.email).split(" ").map(H=>H[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:A.displayName||[A.firstName,A.lastName].filter(Boolean).join(" ")||A.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:A.email}),A.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:A.designation})]})]})},A.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(P,{type:"button",variant:"outline",onClick:T,className:"flex-1 h-11 border-gray-300",disabled:h,children:"Cancel"}),e.jsxs(P,{type:"button",onClick:B,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:h||!o.trim()||!p||!d,children:[e.jsx(qt,{className:"w-4 h-4 mr-2"}),h?"Adding...":`Add at Level ${p||"?"}`]})]})]}),e.jsx(xt,{open:E.open,onOpenChange:A=>R(H=>({...H,open:A})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(ht,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:E.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Et,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[E.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:E.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(dl,{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."]})})]}),E.type==="error"&&e.jsxs(e.Fragment,{children:[E.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:E.email}),"."]}),E.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:E.message})})]})]})})]}),e.jsx(Dt,{children:e.jsx(P,{onClick:()=>R(A=>({...A,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const k5=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"}},D5=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},R5=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 Ea(s)},F5=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",rh=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Re,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(Kh,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Re,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Re,{className:`${s} text-blue-600`}):a.includes("image")||a.includes("png")||a.includes("jpg")||a.includes("jpeg")||a.includes("gif")||a.includes("webp")?e.jsx(Di,{className:`${s} text-purple-600`}):e.jsx(ll,{className:`${s} text-gray-600`})};function W0({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:c=[],onAddApprover:d,maxApprovalLevels:m,onPolicyViolation:p}){const u=Ba(),h=t||u.requestId||"",[g,b]=x.useState(""),[f,j]=x.useState(""),[y,v]=x.useState(!1),[w,S]=x.useState([]),[C,E]=x.useState(!1),[R,k]=x.useState([]),[N,O]=x.useState(null),[I,B]=x.useState(null),[T,M]=x.useState(!1),[F,D]=x.useState(!1),[A,H]=x.useState(!1),[$,_]=x.useState({success:!0,title:"",message:""}),L=x.useRef(null),z=x.useRef(null),X=x.useRef(null),W=x.useRef(!1),[U,V]=x.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[Q,ee]=x.useState({open:!1,errors:[]}),K=x.useMemo(()=>({id:h,title:n||"Request Details"}),[h,n]),[q,ue]=x.useState([]),Le=q.filter(ne=>ne.status==="online"),Ze=w.filter(ne=>ne.content.toLowerCase().includes(f.toLowerCase())||ne.user.name.toLowerCase().includes(f.toLowerCase())),De=x.useMemo(()=>o!==void 0?o:!N||q.length===0?!1:q.some(ne=>{const Ee=ne.userId||ne.user_id,oe=(ne.role||"").toString().toUpperCase(),Xe=(ne.participantType||ne.participant_type||"").toString().toUpperCase();return Ee===N&&(oe==="SPECTATOR"||Xe==="SPECTATOR")}),[o,N,q]);x.useEffect(()=>{},[q]),x.useEffect(()=>{!h||!N||s||(async()=>{try{const ne=await mn(h),Ee=Array.isArray(ne)?ne.map(oe=>{const Xe=oe.userId||oe.user_id;return{id:oe.noteId||oe.id||String(Math.random()),user:{name:oe.userName||"User",avatar:(oe.userName||"U").slice(0,2).toUpperCase(),role:oe.userRole||"Participant"},content:oe.message||"",timestamp:oe.createdAt||new Date().toISOString(),isCurrentUser:Xe===N,attachments:Array.isArray(oe.attachments)?oe.attachments.map(Ke=>({attachmentId:Ke.attachmentId||Ke.attachment_id,name:Ke.fileName||Ke.file_name||Ke.name,fileName:Ke.fileName||Ke.file_name||Ke.name,url:Ke.storageUrl||Ke.storage_url||Ke.url||"#",type:Ke.fileType||Ke.file_type||Ke.type||"file",fileType:Ke.fileType||Ke.file_type||Ke.type||"file",fileSize:Ke.fileSize||Ke.file_size})):void 0}}):[];S(Ee)}catch(ne){console.error("[WorkNoteChat] Failed to load messages:",ne)}})()},[h,N,s]);const _e=x.useMemo(()=>{const ne=[];return w.forEach(Ee=>{Ee.attachments&&Ee.attachments.length>0&&Ee.attachments.forEach(oe=>{ne.push({attachmentId:oe.attachmentId||oe.attachment_id,name:oe.fileName||oe.file_name||oe.name||"Untitled",fileName:oe.fileName||oe.file_name||oe.name||"Untitled",size:oe.fileSize||oe.file_size,type:oe.fileType||oe.file_type||oe.type||"file",uploadedBy:Ee.user.name,uploadedAt:Ee.timestamp,url:oe.storageUrl||oe.storage_url||oe.url||"#"})})}),ne},[w]);x.useEffect(()=>{i&&_e.length>=0&&i(_e)},[_e,i]);const Ue=x.useMemo(()=>q.map(ne=>({email:(ne.email||"").toLowerCase(),participantType:ne.role==="Initiator"?"INITIATOR":ne.role==="Approver"?"APPROVER":ne.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:ne.name})),[q]),re=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()}},fe=()=>{var ne;(ne=L.current)==null||ne.scrollIntoView({behavior:"smooth"})};x.useEffect(()=>{fe()},[w]);const Ce=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()}};x.useEffect(()=>{W.current||h&&(async()=>{try{const ne=await Is(h),Ee=Array.isArray(ne==null?void 0:ne.participants)?ne.participants:[];if(Ee.length===0)return;const oe=Ee.map(Qe=>{const it=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(ut=>ut[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ce(it.toString()),status:"offline",email:Qe.userEmail||Qe.user_email||"",permissions:["read","write","mention"],userId:qe}});W.current=!0,ue(oe);let Xe=0;const Ke=3,tt=()=>{X.current&&X.current.connected?(X.current.emit("request:online-users",{requestId:h}),Xe++,Xe()=>{h&&(W.current=!1)},[h]),x.useEffect(()=>{const ne=localStorage.getItem("userData");if(ne)try{const Ee=JSON.parse(ne),oe=(Ee==null?void 0:Ee.id)||(Ee==null?void 0:Ee.userId)||(Ee==null?void 0:Ee.user_id)||null;O(oe)}catch(Ee){console.error("[WorkNoteChat] Failed to parse userData:",Ee)}},[]),x.useEffect(()=>{(async()=>{try{const Ee=await ma("DOCUMENT_POLICY"),oe={};Ee.forEach(Qe=>{oe[Qe.configKey]=Qe.configValue});const Xe=parseInt(oe.MAX_FILE_SIZE_MB||"10"),tt=(oe.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Qe=>Qe.trim().toLowerCase());V({maxFileSizeMB:Xe,allowedFileTypes:tt})}catch(Ee){console.error("Failed to load document policy:",Ee)}})()},[]),x.useEffect(()=>{if(!N)return;let ne=h;return(async()=>{var Ee;try{const oe=await Is(h);(Ee=oe==null?void 0:oe.workflow)!=null&&Ee.requestId&&(ne=oe.workflow.requestId)}catch{}try{const oe=$r();r?ue(yt=>yt.map(It=>It.userId===N?{...It,status:"online"}:It)):(Eo(oe,ne,N),ue(yt=>yt.map(It=>It.userId===N?{...It,status:"online"}:It)));const Xe=yt=>{const pt=(yt==null?void 0:yt.note)||yt;if(!pt)return;const It=pt.noteId||pt.id;S(Ss=>{if(Ss.some(Lt=>Lt.id===It))return Ss;const as=pt.userName||pt.user_name||"User",Va=pt.userRole||pt.user_role,za=re(Va),pr=pt.userId||pt.user_id,Na={id:It||String(Date.now()),user:{name:as,avatar:as.split(" ").map(Lt=>Lt[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:za},content:pt.message||"",timestamp:pt.createdAt||new Date().toISOString(),isCurrentUser:pr===N,attachments:Array.isArray(pt.attachments)?pt.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,Na]})},Ke=yt=>{ue(pt=>pt.length===0||!pt.find(as=>as.userId===yt.userId)?pt:pt.map(as=>as.userId===yt.userId?{...as,status:"online"}:as))},tt=yt=>{yt.userId!==N&&ue(pt=>pt.length===0||!pt.find(as=>as.userId===yt.userId)?pt:pt.map(as=>as.userId===yt.userId?{...as,status:"offline"}:as))},Qe=yt=>{ue(pt=>pt.length===0?pt:pt.map(Ss=>{const as=Ss.userId||"";if(as===N)return{...Ss,status:"online"};const za=yt.userIds.includes(as);return{...Ss,status:za?"online":"offline"}}))},it=()=>{ue(yt=>yt.map(It=>It.userId===N?{...It,status:"online"}:It)),r||Eo(oe,ne,N),W.current&&(oe.emit("request:online-users",{requestId:ne}),setTimeout(()=>oe.emit("request:online-users",{requestId:ne}),300),setTimeout(()=>oe.emit("request:online-users",{requestId:ne}),800))},qe=yt=>{console.error("[WorkNoteChat] ❌ Socket error:",yt)},ut=yt=>{console.warn("[WorkNoteChat] ⚠️ Socket disconnected:",yt),ue(pt=>pt.map(It=>It.userId===N?It:{...It,status:"offline"}))},Us=yt=>{yt.includes("presence")||yt.includes("worknote")||yt.includes("request")};oe.on("connect",it),oe.on("disconnect",ut),oe.on("error",qe),oe.on("worknote:new",Xe),oe.on("presence:join",Ke),oe.on("presence:leave",tt),oe.on("presence:online",Qe),oe.onAny(Us),X.current=oe,oe.connected&&W.current&&(oe.emit("request:online-users",{requestId:ne}),setTimeout(()=>{oe.emit("request:online-users",{requestId:ne})},300),setTimeout(()=>{oe.emit("request:online-users",{requestId:ne})},800),setTimeout(()=>{oe.emit("request:online-users",{requestId:ne})},1500));const is=()=>{oe.off("connect",it),oe.off("disconnect",ut),oe.off("error",qe),oe.off("worknote:new",Xe),oe.off("presence:join",Ke),oe.off("presence:leave",tt),oe.off("presence:online",Qe),oe.offAny(Us),r||mp(oe,ne),X.current=null};window.__wn_cleanup=is}catch{}})(),()=>{var Ee;try{(Ee=window.__wn_cleanup)==null||Ee.call(window)}catch{}}},[h,N,r]);const Ae=async()=>{if(g.trim()||R.length>0){const ne=nt(g),Ee=ne.map(Ke=>{const tt=q.find(Qe=>Qe.name.toLowerCase().includes(Ke.toLowerCase()));return tt==null?void 0:tt.userId}).filter(Boolean),oe=R.map(Ke=>({name:Ke.name,url:URL.createObjectURL(Ke),type:Ke.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:oe.length>0?oe:void 0,isCurrentUser:!0};if(a)try{await a(g,R)}catch{}else try{await Kp(h,{message:g,mentions:Ee},R);const Ke=await mn(h),tt=Array.isArray(Ke)?Ke.map(Qe=>{const it=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:it===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(Ke=>[...Ke,Xe])}b(""),k([])}};x.useEffect(()=>{if(s&&Array.isArray(s))try{const Ee=s.filter(oe=>(oe.type||"").toLowerCase()!=="sla_warning").map(oe=>{var Ke;if(oe.type||oe.activityType||oe.isSystem)return{id:oe.id||`activity-${oe.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:oe.details||oe.action||oe.content||"",timestamp:oe.timestamp||oe.createdAt||oe.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const tt=oe.userName||oe.user_name||((Ke=oe.user)==null?void 0:Ke.name)||"User",Qe=oe.userRole||oe.user_role,it=re(Qe),qe=oe.userId||oe.user_id;return{id:oe.noteId||oe.note_id||oe.id||String(Math.random()),user:{name:tt,avatar:tt.split(" ").map(ut=>ut[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:it},content:oe.message||oe.content||"",timestamp:oe.createdAt||oe.created_at||oe.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(oe.attachments)?oe.attachments.map(ut=>({attachmentId:ut.attachmentId||ut.attachment_id,name:ut.fileName||ut.file_name||ut.name,fileName:ut.fileName||ut.file_name||ut.name,url:ut.storageUrl||ut.storage_url||ut.url||"#",type:ut.fileType||ut.file_type||ut.type||"file",fileType:ut.fileType||ut.file_type||ut.type||"file",fileSize:ut.fileSize||ut.file_size})):void 0,isCurrentUser:qe===N}}}).sort((oe,Xe)=>new Date(oe.timestamp).getTime()-new Date(Xe.timestamp).getTime());S(Ee)}catch(ne){console.error("[WorkNoteChat] Error mapping messages:",ne)}else(async()=>{try{const ne=await mn(h),Ee=Array.isArray(ne)?ne.map(oe=>{const Xe=oe.userName||oe.user_name||"User",Ke=oe.userRole||oe.user_role,tt=re(Ke),Qe=oe.userId||oe.user_id;return{id:oe.noteId||oe.note_id||oe.id||String(Math.random()),user:{name:Xe,avatar:Xe.split(" ").map(it=>it[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:tt},content:oe.message||"",timestamp:oe.createdAt||oe.created_at||new Date().toISOString(),attachments:Array.isArray(oe.attachments)?oe.attachments.map(it=>({attachmentId:it.attachmentId||it.attachment_id,name:it.fileName||it.file_name||it.name,fileName:it.fileName||it.file_name||it.name,url:it.storageUrl||it.storage_url||it.url||"#",type:it.fileType||it.file_type||it.type||"file",fileType:it.fileType||it.file_type||it.type||"file",fileSize:it.fileSize||it.file_size})):void 0,isCurrentUser:Qe===N}}):[];S(Ee)}catch(ne){console.error("[WorkNoteChat] Error loading work notes:",ne)}})()},[s,h,q]);const ce=ne=>{const Ee=U.maxFileSizeMB*1024*1024;if(ne.size>Ee)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${U.maxFileSizeMB}MB. Current size: ${(ne.size/(1024*1024)).toFixed(2)}MB`};const oe=ne.name.toLowerCase(),Xe=oe.substring(oe.lastIndexOf(".")+1);return U.allowedFileTypes.includes(Xe)?{valid:!0}:{valid:!1,reason:`File type "${Xe}" is not allowed. Allowed types: ${U.allowedFileTypes.join(", ")}`}},pe=ne=>{if(!ne.target.files||ne.target.files.length===0)return;const Ee=Array.from(ne.target.files),oe=[],Xe=[];Ee.forEach(Ke=>{const tt=ce(Ke);tt.valid?Xe.push(Ke):oe.push({fileName:Ke.name,reason:tt.reason||"Unknown validation error"})}),oe.length>0&&ee({open:!0,errors:oe}),Xe.length>0&&(k(Ke=>[...Ke,...Xe]),Xe.length{k(Ee=>Ee.filter((oe,Xe)=>Xe!==ne)),z.current&&(z.current.value="")},de=ne=>{b(Ee=>Ee+ne),v(!1)},me=()=>{var ne;(ne=z.current)==null||ne.click()},Ne=async ne=>{var Ee,oe;try{await Xp(h,ne);const Xe=await Is(h),Ke=Array.isArray(Xe==null?void 0:Xe.participants)?Xe.participants:[];if(Ke.length){const tt=Ke.map(Qe=>{const it=Qe.participantType||Qe.participant_type||"participant",qe=Qe.userId||Qe.user_id||"",ut=Qe.userName||Qe.user_name||Qe.userEmail||Qe.user_email||"User",Us=Qe.userEmail||Qe.user_email||"",is=ut.split(" ").map(yt=>yt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:ut,avatar:is,role:Ce(it),status:"offline",email:Us,lastSeen:void 0,permissions:["read"],userId:qe}});ue(tt),X.current&&X.current.connected&&X.current.emit("request:online-users",{requestId:h})}M(!1),_({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),H(!0)}catch(Xe){throw console.error("Failed to add spectator:",Xe),_({success:!1,title:"Failed to Add Spectator",message:((oe=(Ee=Xe==null?void 0:Xe.response)==null?void 0:Ee.data)==null?void 0:oe.error)||"Failed to add spectator. Please try again."}),H(!0),Xe}},Oe=async(ne,Ee,oe)=>{var Xe,Ke;if(d)await d(ne,Ee,oe),D(!1);else try{await Qp(h,ne,Ee,oe);const tt=await Is(h),Qe=Array.isArray(tt==null?void 0:tt.participants)?tt.participants:[];if(Qe.length){const it=Qe.map(qe=>{const ut=qe.participantType||qe.participant_type||"participant",Us=qe.userId||qe.user_id||"",is=qe.userName||qe.user_name||qe.userEmail||qe.user_email||"User",yt=qe.userEmail||qe.user_email||"",pt=is.split(" ").map(It=>It[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:is,avatar:pt,role:Ce(ut),status:"offline",email:yt,lastSeen:void 0,permissions:["read"],userId:Us}});ue(it),X.current&&X.current.connected&&X.current.emit("request:online-users",{requestId:h})}D(!1),_({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${oe} with ${Ee}h TAT`}),H(!0)}catch(tt){throw console.error("Failed to add approver:",tt),_({success:!1,title:"Failed to Add Approver",message:((Ke=(Xe=tt==null?void 0:tt.response)==null?void 0:Xe.data)==null?void 0:Ke.error)||"Failed to add approver. Please try again."}),H(!0),tt}},st=["😊","😂","🤣","😁","😃","😄","😅","😆","😉","😌","😍","🥰","😘","😗","😙","😚","🙂","🤗","🤩","🤔","🤨","😐","😑","😶","🙄","😏","😒","🙃","😬","🤐","😴","😪","😵","🤯","🤪","😜","😝","😛","🤤","😋","😎","🤓","🧐","😕","😟","🙁","☹️","😮","😯","😲","😳","🥺","😦","😧","😨","😰","😥","😢","😭","😱","😖","😣","😞","😓","😩","😫","🥱","😤","😡","😠","🤬","😈","👿","💀","☠️","💩","🤡","👹","👺","👻","👋","🤚","🖐️","✋","🖖","👌","🤌","🤏","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","🖕","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","💪","🦾","🦿","🦵","🦶","👂","🦻","👃","🧠","❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔","❣️","💕","💞","💓","💗","💖","💘","💝","💟","❤️‍🔥","💼","📊","📈","📉","💻","⌨️","🖥️","🖨️","🖱️","💾","💿","📱","☎️","📞","📟","📠","📧","✉️","📨","📩","📮","📪","📫","📬","📭","📄","📃","📑","📝","✏️","✒️","🖊️","🖋️","📏","📐","📌","📍","🗂️","📁","📂","✅","✔️","☑️","🎯","🎖️","🏆","🥇","🥈","🥉","⭐","🌟","✨","💫","🔥","💥","⚡","💯","🎉","🎊","🎈","⚠️","🚫","❌","⛔","🚷","🚯","🚱","🚳","🔞","📵","❗","❓","❕","❔","‼️","⁉️","💢","💬","💭","🗯️","⏰","⏱️","⏲️","⏳","⌛","📅","📆","🗓️","📇","🕐","🕑","🕒","🕓","🕔","🕕","🕖","🕗","🕘","🕙","🕚","🚀","🎯","🎲","🎰","🧩","🔍","🔎","🔑","🗝️","🔒","🔓","🔐","🔏","🔔","🔕","📣","📢","💡","🔦","🏮","➕","➖","✖️","➗","♾️","‼️","⁉️","❓","❔","❕","🔄","🔃","🔂","▶️","⏸️","⏯️","⏹️","⏺️","⏭️","⏮️","⏩","⏪","⏫","⏬","◀️","🔼","🔽","➡️","⬅️","⬆️","⬇️","↗️","↘️","↙️","↖️","↕️","↔️","↪️","↩️","⤴️"],nt=ne=>{const Ee=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,oe=[];let Xe;for(;(Xe=Ee.exec(ne))!==null;)if(Xe[1]){const Ke=Xe.index+Xe[0].length,tt=ne.slice(Ke),Qe=ne[Ke];(tt.startsWith("@")||!Qe||/\s|[.,!?;:]|@/.test(Qe))&&oe.push(Xe[1].trim())}return oe},St=ne=>{ne.key==="Enter"&&!ne.shiftKey&&(ne.preventDefault(),Ae())},Mt=(ne,Ee)=>{S(oe=>oe.map(Xe=>{if(Xe.id===ne){const Ke=Xe.reactions||[],tt=Ke.find(Qe=>Qe.emoji===Ee);if(tt)if(tt.users.includes("You")){if(tt.users=tt.users.filter(Qe=>Qe!=="You"),tt.users.length===0)return{...Xe,reactions:Ke.filter(Qe=>Qe.emoji!==Ee)}}else tt.users.push("You");else Ke.push({emoji:Ee,users:["You"]});return{...Xe,reactions:Ke}}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(zs,{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:K.title}),e.jsx(ae,{variant:"outline",className:"text-xs shrink-0",children:t})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:e.jsxs("div",{className:"flex -space-x-2",children:[Le.slice(0,3).map((ne,Ee)=>e.jsx(cs,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(ds,{className:"bg-blue-500 text-white text-xs font-semibold",children:ne.avatar})},Ee)),Le.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:["+",Le.length-3]})]})}),e.jsx(P,{variant:"outline",size:"sm",onClick:()=>E(!C),className:"lg:hidden",children:e.jsx(qt,{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(Jt,{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:[Ze.map(ne=>{const Ee=ne.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${ne.isSystem?"justify-center":Ee?"justify-end":""}`,children:[!ne.isSystem&&!Ee&&e.jsx(cs,{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(ds,{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:`${Ee?"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:bs(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 ${Ee?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[ne.user.name," ",Ee&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(ae,{variant:"outline",className:"text-xs flex-shrink-0",children:ne.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(rt,{className:"w-3 h-3"}),bs(ne.timestamp)]}),ne.isHighPriority&&e.jsxs(ae,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(yj,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${Ee?"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:R5(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((oe,Xe)=>{const Ke=oe.fileSize||oe.file_size,tt=oe.fileName||oe.file_name||oe.name,Qe=oe.fileType||oe.file_type||oe.type||"",it=oe.attachmentId||oe.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(rh,{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}),Ke&&e.jsx("p",{className:"text-xs text-gray-500",children:F5(Ke)})]}),it&&(()=>{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(P,{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 ut=A1(it);B({fileName:tt,fileType:Qe,fileUrl:ut,fileSize:Ke,attachmentId:it})},title:"Preview file",children:e.jsx(vt,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(P,{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(),!it){G.error("Cannot download: Attachment ID missing");return}try{await Du(it)}catch{G.error("Failed to download file")}},title:"Download file",children:e.jsx(Tt,{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((oe,Xe)=>e.jsxs("button",{onClick:()=>Mt(ne.id,oe.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${oe.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:oe.emoji}),e.jsx("span",{className:"text-xs font-medium",children:oe.users.length})]},Xe)),e.jsx(P,{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(ms,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!ne.isSystem&&Ee&&e.jsx(cs,{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(ds,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:ne.user.avatar})})]},ne.id)}),e.jsx("div",{ref:L})]})}),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:z,onChange:pe,className:"hidden",multiple:!0,accept:U.allowedFileTypes.map(ne=>`.${ne}`).join(",")}),R.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:R.map((ne,Ee)=>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(rh,{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(P,{variant:"ghost",size:"sm",onClick:()=>Te(Ee),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"})})]},Ee))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const ne=g.lastIndexOf("@"),Ee=ne>=0;if(!Ee)return null;const oe=g.slice(ne+1),Xe=oe.trim(),Ke=oe.endsWith(" "),tt=Xe.length>0,Qe=Xe.includes(" ")&&!Ke,it=Ke&&tt;if(!(Ee&&oe.length<=20&&!Qe&&!it))return null;const ut=Xe.toLowerCase(),Us=q.filter(is=>is.userId===N?!1:ut?is.name.toLowerCase().includes(ut):!0);return e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border-2 border-blue-300 rounded-lg shadow-2xl p-3 z-[100] w-full sm:max-w-md",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 mb-2",children:"💬 Mention someone"}),e.jsx("div",{className:"max-h-60 overflow-y-auto space-y-1",children:Us.length>0?Us.map((is,yt)=>e.jsxs("button",{type:"button",onClick:pt=>{pt.preventDefault(),pt.stopPropagation();const It=g.lastIndexOf("@"),Ss=g.slice(0,It);b(Ss+"@"+is.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(cs,{className:"h-10 w-10",children:e.jsx(ds,{className:`text-white text-sm font-semibold ${is.role==="Initiator"?"bg-green-600":is.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:is.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:is.name}),e.jsx("p",{className:"text-xs text-gray-600",children:is.role})]})]},yt)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:ut?`No participants found matching "${ut}"`:"No other participants available"})})]})})(),e.jsx($s,{placeholder:De?"Spectators cannot send messages":"Type your message... Use @username to mention someone",value:g,onChange:ne=>b(ne.target.value),onKeyPress:St,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:De}),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(P,{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:st.map((ne,Ee)=>e.jsx("button",{onClick:()=>de(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},Ee))})]})]}),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(P,{variant:"ghost",size:"sm",onClick:me,disabled:De,title:De?"Spectators cannot attach files":"Attach file",children:e.jsx(ll,{className:"h-4 w-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>v(!y),disabled:De,title:De?"Spectators cannot add emojis":"Add emoji",children:e.jsx(vj,{className:"h-4 w-4"})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>b(ne=>ne+"@"),disabled:De,title:De?"Spectators cannot mention users":"Mention someone",children:e.jsx(ul,{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(P,{onClick:Ae,disabled:!g.trim()&&R.length===0||De,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:De?"Spectators cannot send messages":"Send",children:[e.jsx(Yh,{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:()=>E(!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(P,{variant:"ghost",size:"sm",onClick:()=>E(!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:q.map((ne,Ee)=>{const oe=ne.userId===N;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(cs,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(ds,{className:`text-white font-semibold text-sm ${ne.role==="Initiator"?"bg-green-600":oe?"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 ${k5(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," ",oe&&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:D5(ne.status)})]}),ne.lastSeen&&ne.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:ne.lastSeen})]})]},Ee)})})]}),!De&&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(P,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>D(!0),children:[e.jsx(ml,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(P,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>M(!0),children:[e.jsx(vt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),I&&e.jsx(Gr,{fileName:I.fileName,fileType:I.fileType,fileUrl:I.fileUrl,fileSize:I.fileSize,attachmentId:I.attachmentId,onDownload:Du,open:!!I,onClose:()=>B(null)}),!De&&e.jsx(H0,{open:T,onClose:()=>M(!1),onConfirm:Ne,requestIdDisplay:h,requestTitle:K.title,existingParticipants:Ue}),!De&&l&&e.jsx(G0,{open:F,onClose:()=>D(!1),onConfirm:Oe,requestIdDisplay:h,requestTitle:K.title,existingParticipants:Ue,currentLevels:c,maxApprovalLevels:m,onPolicyViolation:p}),e.jsx(xt,{open:Q.open,onOpenChange:ne=>ee(Ee=>({...Ee,open:ne})),children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Et,{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:Q.errors.map((ne,Ee)=>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})]},Ee))}),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: ",U.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",U.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Dt,{children:e.jsx(P,{onClick:()=>ee({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(z0,{open:A,onClose:()=>H(!1),success:$.success,title:$.title,message:$.message})]})}function I5({requestId:t,requestTitle:s,mergedMessages:a,setWorkNoteAttachments:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d}){return e.jsx("div",{className:"h-[calc(100vh-300px)] min-h-[600px]",children:e.jsx(W0,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d})})}function P5({summary:t,loading:s,onShare:a,isInitiator:r}){const n=o=>{const c=o.toLowerCase();return c==="approved"?e.jsx(Be,{className:"h-4 w-4 text-green-600"}):c==="rejected"?e.jsx(Ct,{className:"h-4 w-4 text-red-600"}):c==="pending"||c==="in progress"?e.jsx(rt,{className:"h-4 w-4 text-orange-600"}):e.jsx(Re,{className:"h-4 w-4 text-gray-600"})},i=o=>{const c=o.toLowerCase();return c==="approved"?"bg-green-100 text-green-700 border-green-300":c==="rejected"?"bg-red-100 text-red-700 border-red-300":c==="pending"||c==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},l=(o,c)=>o&&o.trim()&&o.trim().toUpperCase()!=="N/A"?o:c&&c.trim()&&c.trim().toUpperCase()!=="N/A"?c:"N/A";return s?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ze,{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(P,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(pn,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(ae,{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(Ps,{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,c)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsx("h4",{className:"text-md font-semibold text-gray-800 mb-3",children: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(Ps,{content:o.remarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]},c))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children: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(ae,{variant:"outline",className:"text-xs",children:"AI Generated"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),t.closingRemarks?e.jsx(Ps,{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(Re,{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 E5({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(nr,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(Be,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(Ct,{className:"h-4 w-4 text-red-600"}):e.jsx(rt,{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",c=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"},d=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(nr,{className:`h-4 w-4 ${c.icon}`}):e.jsx(rt,{className:`h-4 w-4 ${c.icon}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:a?"SLA Progress (Paused)":"SLA Progress"})]}),e.jsxs(ae,{className:`text-xs ${c.badge}`,"data-testid":`${r}-badge`,children:[i,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(na,{value:i,className:"h-3 mb-2",indicatorClassName:c.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 ${d==="breached"||d==="critical"?c.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: ",Ra(t.deadline,!0)," • ",i,"% elapsed"]}),d==="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(ss,{className:"h-3.5 w-3.5"}),"Approaching Deadline"]}),d==="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(Gi,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function _5({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var g,b;const c=C5((t==null?void 0:t.priority)||"standard"),d=((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)),u=m&&String(m).toLowerCase()==="duplicate",h=d&&m?{color:p?"bg-red-100 !text-red-800 border-red-200":m==="Completed"?"bg-green-100 !text-green-800 border-green-200":u?"bg-amber-100 !text-amber-800 border-amber-200":"bg-gray-100 !text-gray-700 border-gray-200",icon:ah((t==null?void 0:t.status)||"pending").icon,label:m}:ah((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(P,{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(Re,{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(ae,{className:`${c.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"priority-badge",children:c.label}),e.jsx(ae,{className:`${h.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:h.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",E="bg-purple-100 !text-purple-600 border-purple-200";return v?(C="Form 16",E="bg-emerald-100 !text-emerald-700 border-emerald-200"):S?(C="Dealer Claim",E="bg-blue-100 !text-blue-700 border-blue-200"):w?(C="Claim Management",E="bg-blue-100 !text-blue-700 border-blue-200"):y==="TEMPLATE"&&(C="Template"),e.jsx(ae,{className:`${E} 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(P,{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(pn,{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(P,{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(Pt,{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(E5,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function bd(t){return(await be.get(`/summaries/${t}`)).data.data}async function M5(t,s){return(await be.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function L5(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 Y0(t){await be.patch(`/summaries/shared/${t}/view`)}async function K0(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 O5(t){return(await be.get(`/summaries/${t}/recipients`)).data.data||[]}function $5({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(ie,{children:e.jsxs(le,{className:"flex items-center gap-2 text-base",children:[e.jsx(gt,{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(pc,{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(ka,{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(_t,{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(Ps,{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:bs(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:bs(r)})]})]})]})]})}function U5({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(ie,{children:e.jsxs(le,{className:"flex items-center gap-2 text-base",children:[e.jsx(xl,{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(ya,{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(ri,{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(pc,{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 B5({dmsDetails:t,claimAmount:s,estimatedBudgetBreakdown:a,closedExpensesBreakdown:r,visibility:n,onEditClaimAmount:i,className:l}){const o=u=>u==null||Number.isNaN(u)?"₹0.00":`₹${u.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,c=u=>{if(!u)return"";try{return et(new Date(u),"MMM d, yyyy, h:mm a")}catch{return u||""}},d=u=>!u||u.length===0?0:u.reduce((h,g)=>h+(g.totalAmt??g.amount+(g.gstAmt??0)),0),m=!!(t!=null&&t.eInvoiceNumber||t!=null&&t.ackNo||t!=null&&t.eInvoiceDate||t!=null&&t.dmsNumber||t!=null&&t.ackDate||t!=null&&t.irn||t!=null&&t.signedInvoiceUrl);return n.showDMSDetails&&t||(t==null?void 0:t.creditNoteWfmData)&&t.creditNoteWfmData.length>0||n.showClaimAmount&&s&&s.amount!==void 0&&s.amount!==null||a&&a.length>0||r&&r.length>0?e.jsxs(Z,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${l}`,children:[e.jsxs(ie,{children:[e.jsxs(le,{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:[n.showDMSDetails&&t&&m&&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(se,{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"E-Invoice Details"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-2",children:[(t.eInvoiceNumber||t.ackNo)&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Invoice Number"}),e.jsx("p",{className:"font-bold text-sm text-purple-700",children:t.eInvoiceNumber||t.ackNo})]}),t.eInvoiceDate&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Invoice Date"}),e.jsx("p",{className:"font-semibold text-xs text-gray-700",children:c(t.eInvoiceDate)})]}),t.dmsNumber&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"DMS Number"}),e.jsx("p",{className:"font-semibold text-xs text-gray-700",children:t.dmsNumber})]}),t.ackDate&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Ack Date"}),e.jsx("p",{className:"font-semibold text-xs text-gray-700",children:c(t.ackDate)})]}),t.ackNo&&t.eInvoiceNumber&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Ack No"}),e.jsx("p",{className:"font-semibold text-xs text-gray-700",children:t.ackNo})]})]}),t.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:t.irn})]}),t.signedInvoiceUrl&&e.jsxs(P,{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(t.signedInvoiceUrl,"_blank"),children:[e.jsx(_t,{className:"w-3.5 h-3.5"}),"View E-Invoice"]}),t.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:t.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 ",t.createdByName||"System"]}),e.jsx("p",{className:"text-[10px] text-gray-500",children:c(t.createdAt)})]})]}),(t==null?void 0:t.creditNoteWfmData)&&t.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(_t,{className:"w-4 h-4 text-pink-600"}),e.jsx(se,{className:"text-xs font-semibold text-pink-900 uppercase tracking-wide",children:"Credit Note Details"})]}),e.jsx("div",{className:"space-y-2",children:t.creditNoteWfmData.map((u,h)=>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.5 text-pink-900",children:[e.jsxs("span",{className:"font-semibold break-words flex-1 pr-2 uppercase",children:["CN No: ",u.DOC_NO||"N/A"]}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-sm text-white font-medium self-start whitespace-nowrap ${u.MSG_TYP==="E"?"bg-red-500":"bg-green-500"}`,children:u.MSG_TYP==="E"?"Error":u.MSG_TYP==="S"?"Success":u.MSG_TYP||"Processed"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1 mb-1.5 text-gray-600",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Txn No:"}),e.jsx("span",{className:"font-medium",children:u.TRNS_UNIQ_NO||"N/A"})]}),u.TDS_AMT!==void 0&&u.TDS_AMT!==null&&u.TDS_AMT!==""&&(Number.isNaN(Number(u.TDS_AMT))||Number(u.TDS_AMT)!==0)&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"TDS:"}),e.jsx("span",{className:"font-medium text-red-600",children:Number.isNaN(Number(u.TDS_AMT))?String(u.TDS_AMT):o(Number(u.TDS_AMT))})]}),u.CREDITED_TOTAL_AMT!==void 0&&u.CREDITED_TOTAL_AMT!==null&&u.CREDITED_TOTAL_AMT!==""&&(Number.isNaN(Number(u.CREDITED_TOTAL_AMT))||Number(u.CREDITED_TOTAL_AMT)!==0)&&e.jsxs("div",{className:"flex justify-between col-span-2 pt-1 border-t border-pink-100",children:[e.jsx("span",{className:"font-semibold",children:"Credit Amount:"}),e.jsx("span",{className:"font-bold text-pink-700",children:Number.isNaN(Number(u.CREDITED_TOTAL_AMT))?String(u.CREDITED_TOTAL_AMT):o(Number(u.CREDITED_TOTAL_AMT))})]})]}),u.MESSAGE&&e.jsx("div",{className:"text-gray-700 italic border-l-2 border-pink-200 pl-1.5 mt-1 leading-tight",children:u.MESSAGE})]},h))})]}),n.showClaimAmount&&s&&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(ka,{className:"w-4 h-4 text-green-600"}),e.jsx(se,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),n.canEditClaimAmount&&i&&e.jsxs(P,{variant:"outline",size:"sm",onClick:i,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(Qn,{className:"w-3 h-3 mr-1 text-green-700"}),"Edit"]})]}),e.jsx("p",{className:"text-2xl font-bold text-green-700",children:o(s.amount)}),s.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 ",s.lastUpdatedBy]}),s.lastUpdatedAt&&e.jsx("p",{className:"text-xs text-gray-500",children:c(s.lastUpdatedAt)})]})]}),a&&a.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(_t,{className:"w-4 h-4 text-amber-600"}),e.jsx(se,{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:[a.map((u,h)=>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:u.description,children:u.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:o(u.totalAmt??u.amount+(u.gstAmt??0))})]},h)),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:o(d(a))})]})]})]}),r&&r.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(_t,{className:"w-4 h-4 text-indigo-600"}),e.jsx(se,{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:[r.map((u,h)=>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:u.description,children:u.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:o(u.totalAmt??u.amount+(u.gstAmt??0))})]},h)),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:o(d(r))})]})]})]})]})]}):null}function V5({proposalDetails:t,className:s}){const r=(()=>{const o=t.totalEstimatedBudget??t.estimatedBudgetTotal;return o??(t.costBreakup&&t.costBreakup.length>0?t.costBreakup.reduce((d,m)=>{const p=m.amount||0,u=m.gstAmt||0,h=m.totalAmt||Number(p)+Number(u);return d+(Number.isNaN(h)?0:h)},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(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2 text-base",children:[e.jsx(_t,{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,c)=>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))})]},c)),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(gt,{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 z5({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(ie,{children:e.jsx(le,{className:"text-base",children:"Request Initiator"})}),e.jsx(te,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(cs,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(ds,{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(ya,{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(ri,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function Q0(t,s){var a,r,n,i,l;try{if(!ai(t))return null;const o=t.claimDetails||{},c=t.proposalDetails||{},d=t.completionDetails||{},m=t.internalOrder||t.internal_order||{},p=t.budgetTracking||t.budget_tracking||{},u=t.invoice||{},h=t.creditNote||t.credit_note||{},g=t.completionExpenses||t.completion_expenses||[],b=o.periodStartDate||o.period_start_date,f=o.periodEndDate||o.period_end_date,j=o.activityName||o.activity_name||"",y=o.activityType||o.activity_type||"",v=o.location||"",w=p.proposalEstimatedBudget??p.proposal_estimated_budget??p.initialEstimatedBudget??p.initial_estimated_budget??o.estimatedBudget??o.estimated_budget,S=(p==null?void 0:p.closedExpenses)??(p==null?void 0:p.closed_expenses)??(d==null?void 0:d.totalClosedExpenses)??(d==null?void 0:d.total_closed_expenses)??(o==null?void 0:o.closedExpenses)??(o==null?void 0:o.closed_expenses),C=S!=null?Number(S):void 0,E=Array.isArray(g)&&g.length>0?g.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})):(d==null?void 0:d.closedExpenses)||(d==null?void 0:d.closed_expenses)||(d==null?void 0:d.closedExpensesBreakdown)||[],R={activityName:j,activityType:y,defaultGstRate:o.defaultGstRate||18,requestedDate:o.activityDate||o.activity_date||t.createdAt,location:v,period:b&&f?{startDate:b,endDate:f}:void 0,estimatedBudget:w,closedExpenses:C,closedExpensesBreakdown:E,description:t.description||""},k={dealerCode:(o==null?void 0:o.dealerCode)||(o==null?void 0:o.dealer_code)||(o==null?void 0:o.DealerCode)||"",dealerName:(o==null?void 0:o.dealerName)||(o==null?void 0:o.dealer_name)||(o==null?void 0:o.DealerName)||"",email:(o==null?void 0:o.dealerEmail)||(o==null?void 0:o.dealer_email)||(o==null?void 0:o.DealerEmail)||"",phone:(o==null?void 0:o.dealerPhone)||(o==null?void 0:o.dealer_phone)||(o==null?void 0:o.DealerPhone)||"",address:(o==null?void 0:o.dealerAddress)||(o==null?void 0:o.dealer_address)||(o==null?void 0:o.DealerAddress)||""};(!k.dealerCode||!k.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!o,dealerCode:k.dealerCode,dealerName:k.dealerName,rawClaimDetails:o,availableKeys:o?Object.keys(o):[]});const N=(c==null?void 0:c.expectedCompletionDate)||(c==null?void 0:c.expected_completion_date),I=!!(c&&Object.keys(c).length>0&&(Array.isArray(c.costItems||c.cost_items)&&(c.costItems||c.cost_items).length>0||Array.isArray(c.costBreakup||c.cost_breakup)&&(c.costBreakup||c.cost_breakup).length>0||c.proposalDocumentUrl||c.proposal_document_url||c.totalEstimatedBudget||c.total_estimated_budget||c.expectedCompletionDate||c.expected_completion_date||c.submittedAt||c.submitted_at))?{proposalDocumentUrl:c.proposalDocumentUrl||c.proposal_document_url,costBreakup:Array.isArray(c.costItems||c.cost_items)?(c.costItems||c.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(c.costBreakup||c.cost_breakup)?(c.costBreakup||c.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:c.totalEstimatedBudget||c.total_estimated_budget||0,timelineMode:c.timelineMode||c.timeline_mode,expectedCompletionDate:N,timelineForClosure:N,expectedCompletionDays:c.expectedCompletionDays||c.expected_completion_days,dealerComments:c.dealerComments||c.dealer_comments,submittedAt:c.submittedAt||c.submitted_at||c.submittedOn,submittedOn:c.submittedAt||c.submitted_at||c.submittedOn}:void 0,B={ioNumber:m.ioNumber||m.io_number||o.ioNumber||o.io_number,ioRemark:m.ioRemark||m.io_remark||"",availableBalance:m.ioAvailableBalance||m.io_available_balance||o.ioAvailableBalance||o.io_available_balance,blockedAmount:m.ioBlockedAmount||m.io_blocked_amount||o.ioBlockedAmount||o.io_blocked_amount,remainingBalance:m.ioRemainingBalance||m.io_remaining_balance||o.ioRemainingBalance||o.io_remaining_balance,organizedBy:((a=m.organizer)==null?void 0:a.displayName)||((r=m.organizer)==null?void 0:r.name)||m.organizedBy||"",organizedAt:m.organizedAt||m.organized_at||""},T=t.invoice||t.claimInvoice||t.claim_invoice||((n=t.claimRequest)==null?void 0:n.invoice)||((i=t.request)==null?void 0:i.invoice)||u||{},M=o||{},F={eInvoiceNumber:T.invoiceNumber||T.invoice_number||M.eInvoiceNumber||M.e_invoice_number||T.dmsNumber||T.dms_number,eInvoiceDate:T.invoiceDate||T.invoice_date||M.eInvoiceDate||M.e_invoice_date,dmsNumber:T.dmsNumber||T.dms_number||M.dmsNumber||M.dms_number,creditNoteNumber:h.creditNoteNumber||h.credit_note_number||M.creditNoteNumber||M.credit_note_number,creditNoteDate:h.creditNoteDate||h.credit_note_date||M.creditNoteDate||M.credit_note_date,creditNoteAmount:h.creditNoteAmount!==void 0&&h.creditNoteAmount!==null?Number(h.creditNoteAmount):h.credit_note_amount!==void 0&&h.credit_note_amount!==null?Number(h.credit_note_amount):M.creditNoteAmount!==void 0&&M.creditNoteAmount!==null?Number(M.creditNoteAmount):M.credit_note_amount!==void 0&&M.credit_note_amount!==null?Number(M.credit_note_amount):void 0,irn:T.irn||M.irn,ackNo:T.ackNo||T.ack_no||M.ackNo||M.ack_no,ackDate:T.ackDate||T.ack_date||M.ackDate||M.ack_date,signedInvoiceUrl:T.signedInvoiceUrl||T.signed_invoice_url||M.signedInvoiceUrl||M.signed_invoice_url,taxBreakdown:T.taxBreakdown||M.taxBreakdown,creditNoteWfmData:(((l=t.creditNote)==null?void 0:l.items)||t.creditNoteWfmData||o.creditNoteWfmData||[]).map(A=>{var H;return{...A,DOC_NO:A.creditNoteNumber||((H=t.creditNote)==null?void 0:H.creditNoteNumber)||A.DOC_NO,TRNS_UNIQ_NO:A.transactionNo||A.TRNS_UNIQ_NO,MESSAGE:A.description||A.MESSAGE,TDS_AMT:A.tdsAmount||A.TDS_AMT,CREDITED_TOTAL_AMT:A.creditAmount||A.amount||A.CREDITED_TOTAL_AMT}})},D={estimated:R.estimatedBudget||0,closed:R.closedExpenses||0};return{activityInfo:R,dealerInfo:k,proposalDetails:I,ioDetails:Object.keys(B).some(A=>B[A])?B:void 0,dmsDetails:Object.keys(F).some(A=>F[A])?F:void 0,claimAmount:D}}catch(o){return console.error("[claimDataMapper] Error mapping claim data:",o),null}}function X0(t,s){var a,r,n,i,l,o,c,d;try{const m=v=>(v||"").toString().trim().toLowerCase(),p=Array.isArray(t.participants)?t.participants:[],u=p.find(v=>{var w;return v.userId===s||v.user_id===s||((w=v.user)==null?void 0:w.userId)===s}),h=m((u==null?void 0:u.userEmail)||(u==null?void 0:u.user_email)||(u==null?void 0:u.email)||((a=u==null?void 0:u.user)==null?void 0:a.email)||(t.initiatorId===s?(r=t.initiator)==null?void 0:r.email:"")),g=m(((n=t==null?void 0:t.claimDetails)==null?void 0:n.dealerEmail)||((i=t==null?void 0:t.claimDetails)==null?void 0:i.dealer_email)||(t==null?void 0:t.dealerEmail)||((l=t==null?void 0:t.dealer)==null?void 0:l.email));if(g&&h&&h===g)return"DEALER";if(t.initiatorId===s||t.initiator_id===s||((o=t.initiator)==null?void 0:o.userId)===s||((c=t.initiator)==null?void 0:c.user_id)===s||((d=t.requestedBy)==null?void 0:d.userId)===s)return"INITIATOR";if(p.find(v=>{var w,S;return(v.userId===s||v.user_id===s||((w=v.user)==null?void 0:w.userId)===s||((S=v.user)==null?void 0:S.user_id)===s)&&(v.participantType||v.participant_type||v.type||"").toString().toUpperCase()==="DEALER"}))return"DEALER";const f=t.approvalLevels||[];return f.find(v=>{var w;return v.levelNumber===3&&(v.approverId===s||((w=v.approver)==null?void 0:w.userId)===s)})?"DEPARTMENT_LEAD":f.find(v=>{var w;return(v.approverId===s||((w=v.approver)==null?void 0:w.userId)===s)&&v.status==="PENDING"})?"APPROVER":"SPECTATOR"}catch(m){return console.error("[claimDataMapper] Error determining user role:",m),"SPECTATOR"}}function J0(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:!0,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:!0,showProposalDetails:!0,showIODetails:!1,showDMSDetails:!0,showClaimAmount:!1,canEditClaimAmount:!1}}}function H5({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:l,onReject:o,onPause:c,onResume:d,onRetrigger:m,summaryId:p,refreshTrigger:u,pausedByUserId:h,currentUserId:g,apiRequest:b,onEditClaimAmount:f,hideApproveReject:j=!1}){var D,A,H,$,_;const{user:y}=us(),[v,w]=x.useState([]),[S,C]=x.useState(!1),[E,R]=x.useState(!1),k=(t==null?void 0:t.status)==="closed",N=((D=t==null?void 0:t.pauseInfo)==null?void 0:D.isPaused)||!1,O=h||((H=(A=t==null?void 0:t.pauseInfo)==null?void 0:A.pausedBy)==null?void 0:H.userId),I=g||(y==null?void 0:y.userId)||"",B=!N&&!k&&(r||s),T=N&&d&&(r||s),M=N&&s&&O&&O!==I&&m;x.useEffect(()=>{if(!N||!r||!(t!=null&&t.requestId)){R(!1);return}(async()=>{var z;try{const U=(((z=(await ir.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:z.notifications)||[]).some(V=>V.requestId===t.requestId&&V.notificationType==="pause_retrigger_request");R(U)}catch(X){console.error("Failed to check retrigger notifications:",X),R(!1)}})()},[N,r,t==null?void 0:t.requestId,u]),x.useEffect(()=>{(async()=>{if(!k||!p||!s){w([]);return}try{C(!0);const z=await O5(p);w(z)}catch(z){console.error("Failed to fetch shared recipients:",z),w([])}finally{C(!1)}})()},[k,p,s,u]);const F=x.useMemo(()=>{if(!b||!ai(b))return null;const L=Q0(b);if(!L)return null;const z=X0(b,I),X=J0(z);return{claimRequest:L,visibility:X}},[b,I]);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(ie,{className:"pb-2",children:e.jsx(le,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(te,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(P,{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(ml,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(P,{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(vt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),B&&c&&e.jsxs(P,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:c,"data-testid":"pause-workflow-button",children:[e.jsx(or,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),T&&e.jsxs(P,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-green-700 border-green-300 hover:bg-green-50 hover:text-green-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:d,"data-testid":"resume-workflow-button",children:[e.jsx(Hi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),M&&e.jsxs(P,{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(Je,{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(P,{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(Be,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Approve Request"]}),e.jsxs(P,{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:O===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&&e.jsx(Je,{className:"w-3.5 h-3.5"}),E?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:E?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&O!==I&&E?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(Je,{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&&O!==I?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&&O&&O!==I?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:M?'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(ie,{className:"pb-2",children:e.jsx(le,{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((L,z)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${z}`,children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:L.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:L.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:L.role})]})]},z)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),k&&s&&e.jsxs(Z,{"data-testid":"shared-recipients-card",children:[e.jsx(ie,{className:"pb-2",children:e.jsxs(le,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(pn,{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((L,z)=>{const X=(L.displayName||"NA").split(" ").map(W=>W[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${z}`,children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{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:L.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:L.email}),L.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},L.userId||z)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),F&&e.jsx(B5,{ioDetails:F.claimRequest.ioDetails,dmsDetails:F.claimRequest.dmsDetails,claimAmount:{amount:F.claimRequest.claimAmount.closed||F.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:($=F.claimRequest.proposalDetails)==null?void 0:$.costBreakup,closedExpensesBreakdown:(_=F.claimRequest.activityInfo)==null?void 0:_.closedExpensesBreakdown,visibility:F.visibility,onEditClaimAmount:f})]})}function G5({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=x.useState(r),[d,m]=x.useState(!1),p=(o==null?void 0:o.length)||0,u=x.useMemo(()=>o.slice(0,500),[o]),h=async()=>{try{m(!0),await a(u),s()}finally{m(!1)}};return e.jsx(xt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(dt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ht,{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(Be,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(mt,{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(ae,{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($s,{value:u,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter your approval comments and any conditions or notes...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(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(Be,{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(Dt,{className:"mt-4",children:[e.jsx(P,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(P,{onClick:h,disabled:d,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),d?"Approving...":"Approve Request"]})]})]})})}function W5({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=x.useState(r),[d,m]=x.useState(!1),p=(o==null?void 0:o.length)||0,u=x.useMemo(()=>o.slice(0,500),[o]),h=async()=>{if(!u.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(u),s()}finally{m(!1)}};return e.jsx(xt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(dt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ht,{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(mt,{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(ae,{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($s,{value:u,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter detailed reasons for rejection and any suggestions for improvement...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(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(Je,{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(Dt,{className:"mt-4",children:[e.jsx(P,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(P,{variant:"destructive",onClick:h,disabled:d,children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function Y5({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:l}){const[o,c]=x.useState(""),[d,m]=x.useState(!1),p=async()=>{if(o.trim())try{m(!0),await a(o.trim()),c(""),s()}catch(h){console.error("Failed to skip approver:",h)}finally{m(!1)}},u=()=>{d||(c(""),s())};return e.jsx(xt,{open:t,onOpenChange:u,children:e.jsxs(dt,{className:"sm:max-w-md max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:u,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:d,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ht,{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(Je,{className:"w-5 h-5 text-orange-600"})}),e.jsx(mt,{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(Je,{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(se,{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(se,{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(se,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx($s,{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:h=>c(h.target.value),className:"min-h-[100px] border-2 border-gray-300 focus:border-orange-500",disabled:d,autoFocus:!0}),e.jsx("p",{className:"text-xs text-gray-500",children:"This reason will be recorded in the activity log and all participants will be notified."})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(P,{type:"button",variant:"outline",onClick:u,className:"flex-1 h-11 border-gray-300",disabled:d,children:"Cancel"}),e.jsxs(P,{type:"button",onClick:p,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:d||!o.trim(),children:[e.jsx(Je,{className:"w-4 h-4 mr-2"}),d?"Skipping...":"Skip Approver"]})]})]})})}function K5({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:l,documentError:o,request:c,skipApproverData:d,actionStatus:m,existingParticipants:p,currentLevels:u,maxApprovalLevels:h,onPolicyViolation:g,setShowApproveModal:b,setShowRejectModal:f,setShowAddApproverModal:j,setShowAddSpectatorModal:y,setShowSkipApproverModal:v,setShowActionStatusModal:w,setPreviewDocument:S,setDocumentError:C,setSkipApproverData:E,setActionStatus:R,handleApproveConfirm:k,handleRejectConfirm:N,handleAddApprover:O,handleAddSpectator:I,handleSkipApprover:B,downloadDocument:T,documentPolicy:M}){return e.jsxs(e.Fragment,{children:[e.jsx(G5,{open:t,onClose:()=>b(!1),onConfirm:k,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(W5,{open:s,onClose:()=>f(!1),onConfirm:N,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(G0,{open:a,onClose:()=>j(!1),onConfirm:O,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p,currentLevels:u,maxApprovalLevels:h,onPolicyViolation:g}),e.jsx(H0,{open:r,onClose:()=>y(!1),onConfirm:I,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p}),e.jsx(Y5,{open:n,onClose:()=>{v(!1),E(null)},onConfirm:B,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),l&&e.jsx(Gr,{fileName:l.fileName,fileType:l.fileType,fileUrl:yn(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:T,open:!!l,onClose:()=>S(null)}),m&&e.jsx(z0,{open:i,onClose:()=>{w(!1),R(null)},success:m.success,title:m.title,message:m.message}),e.jsx(xt,{open:o.show,onOpenChange:F=>C(D=>({...D,show:F})),children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Et,{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((F,D)=>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:F.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:F.reason})]},D))}),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: ",M.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",M.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Dt,{children:e.jsx(P,{onClick:()=>C({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const Z0={DocumentsTab:w5,ActivityTab:T5,WorkNotesTab:I5,SummaryTab:P5,RequestDetailHeader:_5,QuickActionsSidebar:H5,RequestDetailModals:K5};function jd({className:t,...s}){return e.jsx(Pb,{"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(Eb,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(Oa,{className:"size-3.5"})})})}function q0({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,l]=x.useState(""),[o,c]=x.useState([]),[d,m]=x.useState(new Set),[p,u]=x.useState(!1),[h,g]=x.useState(!1);x.useEffect(()=>{if(!t){c([]);return}if(!i||!i.startsWith("@")||i.length<2){c([]),u(!1);return}const y=setTimeout(async()=>{var v;try{u(!0);const w=i.slice(1),S=await va(w,10),C=((v=S==null?void 0:S.data)==null?void 0:v.data)||(S==null?void 0:S.data)||[];c(Array.isArray(C)?C:[])}catch(w){console.error("Failed to search users:",w),G.error("Failed to search users")}finally{u(!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(d.size===0){G.error("Please select at least one user to share with");return}try{g(!0),await M5(a,Array.from(d)),G.success(`Summary shared with ${d.size} user(s)`),m(new Set),l(""),c([]),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(""),c([]),s()};return e.jsx(xt,{open:t,onOpenChange:j,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(ht,{children:e.jsx(mt,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(se,{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(se,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Jt,{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(ze,{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=d.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(jd,{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"}),d.size>0&&e.jsxs("div",{className:"border rounded-lg p-3 bg-blue-50",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-700 mb-2",children:["Selected (",d.size,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(d).map(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(Dt,{children:[e.jsx(P,{variant:"outline",onClick:j,disabled:h,children:"Cancel"}),e.jsx(P,{onClick:f,disabled:h||d.size===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${d.size} user(s)`})]})]})})}function ef({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,l]=x.useState(""),[o,c]=x.useState(""),[d,m]=x.useState(!1),p=()=>rs().add(1,"month").format("YYYY-MM-DD"),u=()=>rs().add(1,"month").format("YYYY-MM-DD"),h=()=>rs().add(1,"day").format("YYYY-MM-DD");x.useEffect(()=>{t&&!o&&c(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=rs(o),j=rs().add(1,"month"),y=rs().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 w1(a,r,i.trim(),f.toDate()),G.success("Workflow paused successfully"),n&&await n(),l(""),c(p()),s()}catch(E){console.error("Failed to pause workflow:",E),G.error(((w=(v=E==null?void 0:E.response)==null?void 0:v.data)==null?void 0:w.error)||((C=(S=E==null?void 0:E.response)==null?void 0:S.data)==null?void 0:C.message)||"Failed to pause workflow")}finally{m(!1)}},b=()=>{d||(l(""),c(p()),s())};return e.jsx(xt,{open:t,onOpenChange:b,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(ht,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(or,{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(se,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx($s,{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:d}),e.jsxs("p",{className:"text-xs text-gray-500",children:[i.length," / 1000 characters"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{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=>c(f.target.value),min:h(),max:u(),className:"text-sm",disabled:d}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum 1 month from today. The workflow will automatically resume on this date."})]})]}),e.jsxs(Dt,{children:[e.jsx(P,{variant:"outline",onClick:b,disabled:d,children:"Cancel"}),e.jsx(P,{onClick:g,disabled:d||!i.trim()||!o,className:"bg-orange-600 hover:bg-orange-700 text-white",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(or,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function tf({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=x.useState(""),[l,o]=x.useState(!1),c=async()=>{var m,p,u,h;try{o(!0),await C1(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)||((h=(u=g==null?void 0:g.response)==null?void 0:u.data)==null?void 0:h.message)||"Failed to resume workflow")}finally{o(!1)}},d=()=>{l||(i(""),s())};return e.jsx(xt,{open:t,onOpenChange:d,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(ht,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Hi,{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(se,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx($s,{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(Dt,{children:[e.jsx(P,{variant:"outline",onClick:d,disabled:l,children:"Cancel"}),e.jsx(P,{onClick:c,disabled:l,className:"bg-green-600 hover:bg-green-700 text-white",children:l?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Hi,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function sf({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,l]=x.useState(!1),o=async()=>{var c,d,m,p;try{l(!0),await S1(a),G.success("Retrigger request sent to approver"),n&&await n(),s()}catch(u){console.error("Failed to retrigger pause:",u),G.error(((d=(c=u==null?void 0:u.response)==null?void 0:c.data)==null?void 0:d.error)||((p=(m=u==null?void 0:u.response)==null?void 0:m.data)==null?void 0:p.message)||"Failed to send retrigger request")}finally{l(!1)}};return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[450px]",children:[e.jsx(ht,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Je,{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(Dt,{children:[e.jsx(P,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(P,{onClick:o,disabled:i,className:"bg-orange-600 hover:bg-orange-700 text-white",children:i?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:Q5,ActivityTab:X5,WorkNotesTab:J5,SummaryTab:Z5,RequestDetailHeader:q5,QuickActionsSidebar:ek,RequestDetailModals:tk}=Z0;let sk=class extends x.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("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(ss,{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(P,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(P,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function ak({requestId:t,onBack:s,dynamicRequests:a=[]}){var Kr,Xa,fr,Ja,br,jr,Za,Ia,qa;const n=Ba().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=x.useState(l),[d,m]=x.useState(!1),[p,u]=x.useState(null),[h,g]=x.useState(null),[b,f]=x.useState(!1),[j,y]=x.useState(0),[v,w]=x.useState(!1),[S,C]=x.useState(!1),[E,R]=x.useState(!1),[k,N]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[O,I]=x.useState({open:!1,violations:[]}),{user:B}=us(),{request:T,apiRequest:M,loading:F,refreshing:D,refreshDetails:A,currentApprovalLevel:H,isSpectator:$,isInitiator:_,existingParticipants:L,accessDenied:z}=gd(n,a,B),{mergedMessages:X,unreadWorkNotes:W,workNoteAttachments:U,setWorkNoteAttachments:V}=$0(n,M,o,B),{uploadingDocument:Q,triggerFileInput:ee,previewDocument:K,setPreviewDocument:q,documentPolicy:ue,documentError:Le,setDocumentError:Ze}=U0(M,A),{showApproveModal:De,setShowApproveModal:_e,showRejectModal:Ue,setShowRejectModal:re,showAddApproverModal:fe,setShowAddApproverModal:Ce,showAddSpectatorModal:Ae,setShowAddSpectatorModal:ce,showSkipApproverModal:pe,setShowSkipApproverModal:Te,showActionStatusModal:de,setShowActionStatusModal:me,skipApproverData:Ne,setSkipApproverData:Oe,actionStatus:st,setActionStatus:nt,handleApproveConfirm:St,handleRejectConfirm:Mt,handleAddApprover:ne,handleSkipApprover:Ee,handleAddSpectator:oe}=V0(n,H,A),{conclusionRemark:Xe,setConclusionRemark:Ke,conclusionLoading:tt,conclusionSubmitting:Qe,aiGenerated:it,handleGenerateConclusion:qe,handleFinalizeConclusion:ut,generationAttempts:Us,generationFailed:is,maxAttemptsReached:yt}=B0(T,n,_,A,s,nt,me);x.useEffect(()=>{(async()=>{var As;try{const ia=await ma("SYSTEM_SETTINGS"),yr=await ma("WORKFLOW_SHARING"),vr=[...ia,...yr],Ca={};vr.forEach(er=>{Ca[er.configKey]=er.configValue}),N({maxApprovalLevels:parseInt(Ca.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(Ca.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((As=Ca.ALLOW_ADD_SPECTATOR)==null?void 0:As.toLowerCase())==="true",maxSpectators:parseInt(Ca.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(ia){console.error("Failed to load system policy:",ia)}})()},[]),x.useEffect(()=>{const As=new URLSearchParams(window.location.search).get("tab");As&&c(As)},[n]);const pt=()=>{A()},It=()=>{w(!0)},Ss=()=>{C(!0)},as=async()=>{await A()},Va=()=>{R(!0)},za=async()=>{await A()},pr=async()=>{await A()},Na=async()=>{if(!(M!=null&&M.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=((T==null?void 0:T.status)==="approved"||(T==null?void 0:T.status)==="rejected")&&_,wa=(T==null?void 0:T.status)==="closed"||(T==null?void 0:T.status)==="approved"&&!_||(T==null?void 0:T.status)==="rejected"&&!_,Ms=((T==null?void 0:T.templateType)||(T==null?void 0:T.template_type)||"").toString().toUpperCase()==="FORM_16";x.useEffect(()=>{Ms&&o==="worknotes"&&c("overview")},[Ms,o]),x.useEffect(()=>{(async()=>{if(!wa||!(M!=null&&M.requestId)){g(null),u(null);return}try{f(!0);const As=await K0(M.requestId);if(As!=null&&As.summaryId){u(As.summaryId);try{const ia=await bd(As.summaryId);g(ia)}catch(ia){console.error("Failed to fetch summary details:",ia),g(null),u(null)}}else g(null),u(null)}catch{g(null),u(null)}finally{f(!1)}})()},[wa,M==null?void 0:M.requestId]);const Wr=((T==null?void 0:T.approvalFlow)||[]).filter(Kt=>Kt&&typeof Kt.step=="number").map(Kt=>({levelNumber:Kt.step||0,approverName:Kt.approver||"Unknown",status:Kt.status||"pending",tatHours:Kt.tatHours||24}));if(F&&!T&&!M)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(Pt,{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(z!=null&&z.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(Qh,{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:z.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(P,{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(P,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})});if(!T)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(Re,{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(P,{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(P,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})});const Yr=(B==null?void 0:B.role)==="MANAGEMENT"||(B==null?void 0:B.role)==="ADMIN",gr=((Kr=at.getUserData())==null?void 0:Kr.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(q5,{request:T,refreshing:D,onBack:s||(()=>window.history.back()),onRefresh:pt,onShareSummary:Na,isInitiator:_,slaData:((Xa=T==null?void 0:T.summary)==null?void 0:Xa.sla)||(T==null?void 0:T.sla)||null,isPaused:((fr=T==null?void 0:T.pauseInfo)==null?void 0:fr.isPaused)||!1}),e.jsxs(gi,{value:o,onValueChange:c,className:"w-full","data-testid":"custom-request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(fi,{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(Xh,{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"})]}),wa&&h&&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(gc,{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(Hs,{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(Re,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Docs"})]}),e.jsxs($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(zs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),W>0&&e.jsx(ae,{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-red-500 text-white text-[10px] flex items-center justify-center p-0","data-testid":"worknotes-unread-badge",children:W>9?"9+":W})]})]})}),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(V1,{request:T}):e.jsx(_1,{request:T,isInitiator:_,needsClosure:Lt,conclusionRemark:Xe,setConclusionRemark:Ke,conclusionLoading:tt,conclusionSubmitting:Qe,aiGenerated:it,handleGenerateConclusion:qe,handleFinalizeConclusion:ut,onPause:It,onResume:Ss,onRetrigger:Va,currentUserIsApprover:!!H,pausedByUserId:(br=(Ja=T==null?void 0:T.pauseInfo)==null?void 0:Ja.pausedBy)==null?void 0:br.userId,currentUserId:B==null?void 0:B.userId,generationAttempts:Us,generationFailed:is,maxAttemptsReached:yt})}),wa&&e.jsx(Ut,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(Z5,{summary:h,loading:b,onShare:Na,isInitiator:_})}),e.jsx(Ut,{value:"workflow",className:"mt-0",children:Ms?e.jsx(H1,{request:T,requestId:(M==null?void 0:M.requestId)||n,isReUser:Yr,onRefresh:A}):e.jsx($1,{request:T,user:B,isInitiator:_,onSkipApprover:Kt=>{if(!Kt.levelId){alert("Level ID not available");return}Oe(Kt),Te(!0)},onRefresh:A})}),e.jsx(Ut,{value:"documents",className:"mt-0",children:e.jsx(Q5,{request:T,workNoteAttachments:U,uploadingDocument:Q,documentPolicy:ue,triggerFileInput:ee,setPreviewDocument:q,downloadDocument:_s,isSpectator:$})}),e.jsx(Ut,{value:"activity",className:"mt-0",children:e.jsx(X5,{request:T})}),!Ms&&e.jsx(Ut,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(J5,{requestId:n,requestTitle:T.title,mergedMessages:X,setWorkNoteAttachments:V,isInitiator:_,isSpectator:$,currentLevels:Wr,onAddApprover:ne,maxApprovalLevels:k.maxApprovalLevels,onPolicyViolation:Kt=>I({open:!0,violations:Kt})})})]}),!gr&&o!=="worknotes"&&e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[Ms&&Yr&&e.jsx(v5,{requestId:(M==null?void 0:M.requestId)||n,request:T,onRefresh:A}),e.jsx(ek,{request:T,isInitiator:_,isSpectator:$,currentApprovalLevel:H,onAddApprover:()=>Ce(!0),onAddSpectator:()=>ce(!0),onApprove:()=>_e(!0),onReject:()=>re(!0),onPause:It,onResume:Ss,onRetrigger:Va,summaryId:p,refreshTrigger:j,pausedByUserId:(Za=(jr=T==null?void 0:T.pauseInfo)==null?void 0:jr.pausedBy)==null?void 0:Za.userId,currentUserId:B==null?void 0:B.userId,apiRequest:M,hideApproveReject:gr})]})]})]})]})}),d&&p&&e.jsx(q0,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(T==null?void 0:T.title)||"N/A",onSuccess:()=>{A(),y(Kt=>Kt+1)}}),v&&(M==null?void 0:M.requestId)&&e.jsx(ef,{isOpen:v,onClose:()=>w(!1),requestId:M.requestId,levelId:(H==null?void 0:H.levelId)||null,onSuccess:za}),S&&(M==null?void 0:M.requestId)&&e.jsx(tf,{isOpen:S,onClose:()=>C(!1),requestId:M.requestId,onSuccess:as}),E&&(M==null?void 0:M.requestId)&&e.jsx(sf,{isOpen:E,onClose:()=>R(!1),requestId:M.requestId,approverName:(qa=(Ia=T==null?void 0:T.pauseInfo)==null?void 0:Ia.pausedBy)==null?void 0:qa.name,onSuccess:pr}),e.jsx(tk,{showApproveModal:De,showRejectModal:Ue,showAddApproverModal:fe,showAddSpectatorModal:Ae,showSkipApproverModal:pe,showActionStatusModal:de,previewDocument:K,documentError:Le,request:T,skipApproverData:Ne,actionStatus:st,existingParticipants:L,currentLevels:Wr,maxApprovalLevels:k.maxApprovalLevels,onPolicyViolation:Kt=>I({open:!0,violations:Kt}),setShowApproveModal:_e,setShowRejectModal:re,setShowAddApproverModal:Ce,setShowAddSpectatorModal:ce,setShowSkipApproverModal:Te,setShowActionStatusModal:me,setPreviewDocument:q,setDocumentError:Ze,setSkipApproverData:Oe,setActionStatus:nt,handleApproveConfirm:St,handleRejectConfirm:Mt,handleAddApprover:ne,handleAddSpectator:oe,handleSkipApprover:Ee,downloadDocument:_s,documentPolicy:ue}),e.jsx(pi,{open:O.open,onClose:()=>I({open:!1,violations:[]}),violations:O.violations,policyDetails:{maxApprovalLevels:k.maxApprovalLevels,maxParticipants:k.maxParticipants,allowSpectators:k.allowSpectators,maxSpectators:k.maxSpectators}})]})}function rk(t){return e.jsx(sk,{children:e.jsx(ak,{...t})})}const nk=[{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 ik(){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 lk({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,form16FinancialYear:n="",form16Quarter:i="",sortBy:l,sortOrder:o,onSearchChange:c,onStatusFilterChange:d,onPriorityFilterChange:m,onTemplateTypeFilterChange:p,onForm16FinancialYearChange:u,onForm16QuarterChange:h,onSortByChange:g,onSortOrderChange:b,onClearFilters:f,activeFiltersCount:j}){const y=ik(),v=r==="FORM_16";return e.jsxs(Z,{className:"shadow-lg border-0",children:[e.jsx(ie,{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($a,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(le,{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(P,{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(Jt,{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 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors"})]}),e.jsxs(He,{value:a,onValueChange:m,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"All Priorities"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Priorities"}),e.jsx(J,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fa,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(J,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(He,{value:s,onValueChange:d,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"All Statuses"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Statuses"}),e.jsx(J,{value:"pending",children:"Pending (In Approval)"}),e.jsx(J,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs(He,{value:r,onValueChange:p,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Request type"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(J,{value:"FORM_16",children:"Form 16"})]})]}),v&&u&&e.jsxs(He,{value:n||void 0,onValueChange:u,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Financial Year"})}),e.jsx(Ye,{children:y.map(w=>e.jsx(J,{value:w,children:w},w))})]}),v&&h&&e.jsxs(He,{value:i||void 0,onValueChange:h,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Quarter"})}),e.jsx(Ye,{children:nk.map(w=>e.jsx(J,{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(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"due",children:"Due Date"}),e.jsx(J,{value:"created",children:"Date Created"}),e.jsx(J,{value:"priority",children:"Priority"}),e.jsx(J,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(P,{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(hl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(pl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}const ok=[{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 ck(){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 dk({searchTerm:t,priorityFilter:s,statusFilter:a,templateTypeFilter:r,form16FinancialYear:n="",form16Quarter:i="",sortBy:l,sortOrder:o,activeFiltersCount:c,onSearchChange:d,onPriorityChange:m,onStatusChange:p,onTemplateTypeChange:u,onForm16FinancialYearChange:h,onForm16QuarterChange:g,onSortByChange:b,onSortOrderChange:f,onClearFilters:j}){const y=ck(),v=r==="FORM_16";return e.jsxs(Z,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(ie,{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($a,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(le,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ye,{className:"text-xs sm:text-sm",children:c>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[c," filter",c>1?"s":""," active"]})})]})]}),c>0&&e.jsxs(P,{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(Jt,{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 transition-colors","data-testid":"closed-requests-search"})]}),e.jsxs(He,{value:s,onValueChange:m,children:[e.jsx(We,{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(Ge,{placeholder:"All Priorities"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Priorities"}),e.jsx(J,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fa,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(J,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(He,{value:a,onValueChange:p,children:[e.jsx(We,{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(Ge,{placeholder:"Closure Type"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Closures"}),e.jsx(J,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(J,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs(He,{value:r,onValueChange:u,children:[e.jsx(We,{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(Ge,{placeholder:"Request type"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(J,{value:"FORM_16",children:"Form 16"})]})]}),v&&h&&e.jsxs(He,{value:n||void 0,onValueChange:h,children:[e.jsx(We,{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(Ge,{placeholder:"Financial Year"})}),e.jsx(Ye,{children:y.map(w=>e.jsx(J,{value:w,children:w},w))})]}),v&&g&&e.jsxs(He,{value:i||void 0,onValueChange:g,children:[e.jsx(We,{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(Ge,{placeholder:"Quarter"})}),e.jsx(Ye,{children:ok.map(w=>e.jsx(J,{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(We,{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(Ge,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"due",children:"Due Date"}),e.jsx(J,{value:"created",children:"Date Created"}),e.jsx(J,{value:"priority",children:"Priority"})]})]}),e.jsx(P,{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(hl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(pl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function mk({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,departmentFilter:n,slaComplianceFilter:i,initiatorFilter:l,approverFilter:o,approverFilterType:c,dateRange:d,customStartDate:m,customEndDate:p,showCustomDatePicker:u,departments:h,loadingDepartments:g,initiatorSearch:b,approverSearch:f,showForm16Filter:j=!1,form16FinancialYear:y="all",form16Quarter:v="all",onForm16FinancialYearChange:w,onForm16QuarterChange:S,onSearchChange:C,onStatusChange:E,onPriorityChange:R,onTemplateTypeChange:k,onDepartmentChange:N,onSlaComplianceChange:O,onInitiatorChange:I,onApproverChange:B,onApproverTypeChange:T,onDateRangeChange:M,onCustomStartDateChange:F,onCustomEndDateChange:D,onShowCustomDatePickerChange:A,onApplyCustomDate:H,onClearFilters:$,hasActiveFilters:_}){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($a,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),_&&e.jsx(ae,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),_&&e.jsxs(P,{variant:"ghost",size:"sm",onClick:$,className:"gap-2",children:[e.jsx(Pt,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Zt,{}),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(Jt,{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:L=>C(L.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(He,{value:s,onValueChange:E,children:[e.jsx(We,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"pending",children:"Pending"}),e.jsx(J,{value:"paused",children:"Paused"}),e.jsx(J,{value:"approved",children:"Approved"}),e.jsx(J,{value:"rejected",children:"Rejected"}),e.jsx(J,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:a,onValueChange:R,children:[e.jsx(We,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"All Priority"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Priority"}),e.jsx(J,{value:"express",children:"Express"}),e.jsx(J,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:r,onValueChange:k,children:[e.jsx(We,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"All Templates"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Custom"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"}),j&&e.jsx(J,{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(We,{className:"h-10","data-testid":"form16-financial-year-filter",children:e.jsx(Ge,{placeholder:"Financial Year"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Years"}),e.jsx(J,{value:"2024-25",children:"2024-25"}),e.jsx(J,{value:"2023-24",children:"2023-24"}),e.jsx(J,{value:"2022-23",children:"2022-23"})]})]}),e.jsxs(He,{value:v,onValueChange:S??(()=>{}),children:[e.jsx(We,{className:"h-10","data-testid":"form16-quarter-filter",children:e.jsx(Ge,{placeholder:"Quarter"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Quarters"}),e.jsx(J,{value:"Q1",children:"Q1"}),e.jsx(J,{value:"Q2",children:"Q2"}),e.jsx(J,{value:"Q3",children:"Q3"}),e.jsx(J,{value:"Q4",children:"Q4"})]})]})]}),e.jsxs(He,{value:n,onValueChange:N,disabled:g||h.length===0,children:[e.jsx(We,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ge,{placeholder:g?"Loading...":"All Departments"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Departments"}),h.map(L=>e.jsx(J,{value:L,children:L},L))]})]}),e.jsxs(He,{value:i,onValueChange:O,children:[e.jsx(We,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"All SLA Status"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All SLA Status"}),e.jsx(J,{value:"compliant",children:"Compliant"}),e.jsx(J,{value:"on-track",children:"On Track"}),e.jsx(J,{value:"approaching",children:"Approaching"}),e.jsx(J,{value:"critical",children:"Critical"}),e.jsx(J,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(se,{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(P,{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:L=>b.handleSearch(L.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(L=>e.jsx("button",{type:"button",onClick:()=>b.handleSelect(L),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:L.displayName||L.email}),L.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:L.email})]})},L.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{className:"text-sm font-medium text-gray-700",children:"Approver"}),o!=="all"&&T&&e.jsxs(He,{value:c,onValueChange:L=>T(L),children:[e.jsx(We,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"current",children:"Current Only"}),e.jsx(J,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children: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(P,{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:L=>f.handleSearch(L.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(L=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(L),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:L.displayName||L.email}),L.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:L.email})]})},L.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(gt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:d,onValueChange:L=>M(L),children:[e.jsx(We,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Time"}),e.jsx(J,{value:"today",children:"Today"}),e.jsx(J,{value:"week",children:"This Week"}),e.jsx(J,{value:"month",children:"This Month"}),e.jsx(J,{value:"last7days",children:"Last 7 Days"}),e.jsx(J,{value:"last30days",children:"Last 30 Days"}),e.jsx(J,{value:"custom",children:"Custom Range"})]})]}),d==="custom"&&e.jsxs(sa,{open:u,onOpenChange:A,children:[e.jsx(aa,{asChild:!0,children:e.jsxs(P,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(gt,{className:"w-4 h-4"}),m&&p?`${et(m,"MMM d, yyyy")} - ${et(p,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ra,{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(se,{htmlFor:"start-date",children:"Start Date"}),e.jsx(ea,{value:m||null,onChange:L=>{const z=L?new Date(L):void 0;z?(F==null||F(z),p&&z>p&&(D==null||D(z))):F==null||F(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"end-date",children:"End Date"}),e.jsx(ea,{value:p||null,onChange:L=>{const z=L?new Date(L):void 0;z?(D==null||D(z),m&&z{A==null||A(!1),F==null||F(void 0),D==null||D(void 0),M("month")},children:"Cancel"})]})]})})]})]})]})})})}function uk({request:t,apiRequest:s,currentUserId:a,isInitiator:r,onEditClaimAmount:n,className:i="",needsClosure:l=!1,conclusionRemark:o="",setConclusionRemark:c,conclusionLoading:d=!1,conclusionSubmitting:m=!1,aiGenerated:p=!1,handleGenerateConclusion:u,handleFinalizeConclusion:h,generationAttempts:g=0,generationFailed:b=!1,maxAttemptsReached:f=!1}){var S,C,E,R,k,N,O,I,B;if(!ai(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=Q0(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=X0(s,a),v=J0(y),w={name:((S=s.initiator)==null?void 0:S.name)||((C=s.initiator)==null?void 0:C.displayName)||((E=s.initiator)==null?void 0:E.email)||"Unknown",role:((R=s.initiator)==null?void 0:R.role)||((k=s.initiator)==null?void 0:k.designation)||"Initiator",department:((N=s.initiator)==null?void 0:N.department)||s.department||"",email:((O=s.initiator)==null?void 0:O.email)||"N/A",phone:((I=s.initiator)==null?void 0:I.phone)||((B=s.initiator)==null?void 0:B.mobile)};return e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx($5,{activityInfo:j.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(U5,{dealerInfo:j.dealerInfo}),v.showProposalDetails&&j.proposalDetails&&e.jsx(V5,{proposalDetails:j.proposalDetails}),e.jsx(z5,{initiatorInfo:w}),(s==null?void 0:s.status)==="closed"&&(s==null?void 0:s.conclusionRemark)&&e.jsxs(Z,{children:[e.jsxs(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2 text-base",children:[e.jsx(Be,{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(Ps,{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 ",bs(s.closureDate)]}),e.jsxs("span",{children:["By ",w.name]})]})]})]}),l&&e.jsxs(Z,{"data-testid":"conclusion-remark-card",children:[e.jsx(ie,{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(le,{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(Be,{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."})]}),u&&e.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[e.jsxs(P,{variant:"outline",size:"sm",onClick:u,disabled:d||f,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx(Pt,{className:`w-3.5 h-3.5 ${d?"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:d?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(ze,{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)"})]}),c&&e.jsx(di,{value:o,onChange:T=>c(T),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"})]})]}),h&&e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(P,{onClick:h,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(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function xk({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n="Request",requestDescription:i="",requestId:l,levelName:o="Approval Level",approverName:c="Approver"}){const[d,m]=x.useState(""),[p,u]=x.useState(!1),[h,g]=x.useState(null),b=async()=>{if(!d.trim()){G.error("Please provide approval comments");return}try{u(!0),g("approve"),await a(d),j(),s()}catch(v){console.error("Failed to approve request:",v),G.error("Failed to approve request. Please try again.")}finally{u(!1),g(null)}},f=async()=>{if(!d.trim()){G.error("Please provide rejection reason");return}try{u(!0),g("reject"),await r(d),j(),s()}catch(v){console.error("Failed to reject request:",v),G.error("Failed to reject request. Please try again.")}finally{u(!1),g(null)}},j=()=>{m(""),g(null)},y=()=>{p||(j(),s())};return t?e.jsx(xt,{open:t,onOpenChange:y,children:e.jsxs(dt,{className:"dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl",children:[e.jsxs(ht,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(mt,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(Be,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),"Review Request"]}),e.jsxs(Et,{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:"})," ",c]})]})})]}),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(Re,{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(zs,{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(Ps,{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($s,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:d,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:[d.length," characters"]})]}),!d.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(Dt,{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(P,{variant:"outline",onClick:y,disabled:p,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(P,{onClick:f,disabled:!d.trim()||p,variant:"destructive",className:"bg-red-600 hover:bg-red-700",children:p&&h==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),"Reject"]})}),e.jsx(P,{onClick:b,disabled:!d.trim()||p,className:"bg-green-600 hover:bg-green-700 text-white",children:p&&h==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),"Approve"]})})]})]})]})}):null}function hk({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:l,requestNumber:o,requestId:c,dueDate:d,taxationType:m}){const[p,u]=x.useState(!1),[h,g]=x.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?bs(n.creditNoteDate,{includeTime:!1,format:"short"}):"",v=(n==null?void 0:n.creditNoteAmount)||0,w=(n==null?void 0:n.transactionNo)||"",S=(n==null?void 0:n.tdsAmount)||0,C=(n==null?void 0:n.creditAmount)||0,E=(n==null?void 0:n.status)||"PENDING",R=(n==null?void 0:n.items)||[],k=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",N=(i==null?void 0:i.dealerCode)||"RE-JP-009",O=l||"Activity",I=o||"RE-REQ-2024-CM-101",B=d?bs(d,{includeTime:!1,format:"short"}):"Jan 4, 2026",T=(()=>{var A,H;if(R.length>1){const $=(A=R[0])==null?void 0:A.transactionNo,_=(H=R[R.length-1])==null?void 0:H.transactionNo;return $&&_&&$!==_?`${$} - ${_}`:$||w||"N/A"}return w||"N/A"})(),M=async()=>{if(a)try{u(!0),await a(),G.success("Credit note downloaded successfully")}catch(A){console.error("Failed to download credit note:",A),G.error("Failed to download credit note. Please try again.")}finally{u(!1)}else G.info("Credit note will be automatically saved to Documents tab")},F=async()=>{if(r)try{g(!0),await r(),G.success("Credit note sent to dealer successfully"),s()}catch(A){console.error("Failed to send credit note to dealer:",A),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")},D=A=>`₹${A.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ht,{children:[e.jsxs(mt,{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(_t,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note Details"]}),m&&e.jsx(ae,{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(Et,{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(ae,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),E==="APPROVED"?"Approved":E==="ISSUED"?"Issued":E==="SENT"?"Sent":"Confirmed"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4 mt-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100 shadow-sm",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Fo,{className:"w-3 h-3"}),"Credit Note No"]}),e.jsx("p",{className:"font-bold text-gray-900 mt-1",children:j})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100 shadow-sm",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(gt,{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-white rounded-lg p-3 border border-green-100 shadow-sm col-span-2 md:col-span-1",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Re,{className:"w-3 h-3"}),"Transaction ID"]}),e.jsx("p",{className:"font-bold text-emerald-700 mt-1 break-all",children:T})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-4",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(ka,{className:"w-3 h-3"}),"Gross Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-blue-700",children:D(v)})]}),e.jsxs("div",{className:"bg-orange-50 border-2 border-orange-200 rounded-lg p-4",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(ka,{className:"w-3 h-3"}),"TDS Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-orange-700",children:D(S)})]}),e.jsxs("div",{className:"bg-emerald-50 border-2 border-emerald-200 rounded-lg p-4",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(ka,{className:"w-3 h-3"}),"Net Credit Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-emerald-700",children:D(C)})]})]}),R&&R.length>0&&e.jsxs("div",{className:"border border-slate-200 rounded-lg overflow-hidden mt-2",children:[e.jsxs("div",{className:"bg-slate-50 px-4 py-2 border-b border-slate-200 flex items-center justify-between",children:[e.jsxs("h4",{className:"font-semibold text-slate-900 text-sm flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4 text-slate-500"}),"Line Item Breakdown"]}),e.jsxs(ae,{variant:"outline",className:"text-[10px] font-medium uppercase tracking-wider",children:[R.length," ",R.length===1?"Item":"Items"]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto",children:e.jsxs("table",{className:"w-full text-sm text-left border-collapse",children:[e.jsx("thead",{className:"bg-white sticky top-0 shadow-sm z-10",children:e.jsxs("tr",{className:"border-b border-slate-200",children:[e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap",children:"Sl No"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap",children:"Transaction Code"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap",children:"HSN/SAC"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap text-right",children:"Claim Amount"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap text-right",children:"TDS"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap text-right",children:"Net Credit"})]})}),e.jsx("tbody",{children:R.map((A,H)=>e.jsxs("tr",{className:"border-b border-slate-100 hover:bg-slate-50/50 transition-colors",children:[e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:A.slNo}),e.jsx("td",{className:"px-4 py-2.5 font-medium text-slate-900 font-mono text-[11px]",children:A.transactionNo||"N/A"}),e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:A.hsnCd||"N/A"}),e.jsx("td",{className:"px-4 py-2.5 text-right font-medium text-slate-700",children:D(A.claimAmount||0)}),e.jsx("td",{className:"px-4 py-2.5 text-right text-orange-600 font-medium",children:D(A.tdsAmount||0)}),e.jsx("td",{className:"px-4 py-2.5 text-right text-emerald-700 font-bold",children:D(A.creditAmount||0)})]},H))})]})})]})]}):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(_t,{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(xl,{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(se,{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:k})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(se,{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:N})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(se,{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:O})]})]})]}),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(Re,{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(se,{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:I})]}),e.jsxs("div",{children:[e.jsx(se,{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:B})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Re,{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(Dt,{className:"flex-col-reverse gap-2 sm:flex-row flex items-center justify-between sm:justify-between",children:[e.jsx(P,{variant:"outline",onClick:s,disabled:p||h,className:"border-2",children:"Close"}),e.jsx("div",{className:"flex gap-2",children:f&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{variant:"outline",onClick:M,disabled:p||h,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(Tt,{className:"w-4 h-4 mr-2"}),p?"Downloading...":"Download"]}),e.jsxs(P,{onClick:F,disabled:p||h,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(Yh,{className:"w-4 h-4 mr-2"}),h?"Sending...":"Send to Dealer"]})]})})]})]})})}var nh=1,pk=.9,gk=.8,fk=.17,mo=.1,uo=.999,bk=.9999,jk=.99,yk=/[\\\/_+.#"@\[\(\{&]/,vk=/[\\\/_+.#"@\[\(\{&]/g,Nk=/[\s-]/,af=/[\s-]/g;function ac(t,s,a,r,n,i,l){if(i===s.length)return n===t.length?nh:jk;var o=`${n},${i}`;if(l[o]!==void 0)return l[o];for(var c=r.charAt(i),d=a.indexOf(c,n),m=0,p,u,h,g;d>=0;)p=ac(t,s,a,r,d+1,i+1,l),p>m&&(d===n?p*=nh:yk.test(t.charAt(d-1))?(p*=gk,h=t.slice(n,d-1).match(vk),h&&n>0&&(p*=Math.pow(uo,h.length))):Nk.test(t.charAt(d-1))?(p*=pk,g=t.slice(n,d-1).match(af),g&&n>0&&(p*=Math.pow(uo,g.length))):(p*=fk,n>0&&(p*=Math.pow(uo,d-n))),t.charAt(d)!==s.charAt(i)&&(p*=bk)),(pp&&(p=u*mo)),p>m&&(m=p),d=a.indexOf(c,d+1);return l[o]=m,m}function ih(t){return t.toLowerCase().replace(af," ")}function wk(t,s,a){return t=a&&a.length>0?`${t+" "+a.join(" ")}`:t,ac(t,s,ih(t),ih(s),0,0,{})}var Pn='[cmdk-group=""]',xo='[cmdk-group-items=""]',Ck='[cmdk-group-heading=""]',rf='[cmdk-item=""]',lh=`${rf}:not([aria-disabled="true"])`,rc="cmdk-item-select",Zr="data-value",Sk=(t,s,a)=>wk(t,s,a),nf=x.createContext(void 0),bi=()=>x.useContext(nf),lf=x.createContext(void 0),yd=()=>x.useContext(lf),of=x.createContext(void 0),cf=x.forwardRef((t,s)=>{let a=qr(()=>{var L,z;return{search:"",value:(z=(L=t.value)!=null?L:t.defaultValue)!=null?z:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=qr(()=>new Set),n=qr(()=>new Map),i=qr(()=>new Map),l=qr(()=>new Set),o=df(t),{label:c,children:d,value:m,onValueChange:p,filter:u,shouldFilter:h,loop:g,disablePointerSelection:b=!1,vimBindings:f=!0,...j}=t,y=ln(),v=ln(),w=ln(),S=x.useRef(null),C=Mk();Ur(()=>{if(m!==void 0){let L=m.trim();a.current.value=L,E.emit()}},[m]),Ur(()=>{C(6,B)},[]);let E=x.useMemo(()=>({subscribe:L=>(l.current.add(L),()=>l.current.delete(L)),snapshot:()=>a.current,setState:(L,z,X)=>{var W,U,V,Q;if(!Object.is(a.current[L],z)){if(a.current[L]=z,L==="search")I(),N(),C(1,O);else if(L==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let ee=document.getElementById(w);ee?ee.focus():(W=document.getElementById(y))==null||W.focus()}if(C(7,()=>{var ee;a.current.selectedItemId=(ee=T())==null?void 0:ee.id,E.emit()}),X||C(5,B),((U=o.current)==null?void 0:U.value)!==void 0){let ee=z??"";(Q=(V=o.current).onValueChange)==null||Q.call(V,ee);return}}E.emit()}},emit:()=>{l.current.forEach(L=>L())}}),[]),R=x.useMemo(()=>({value:(L,z,X)=>{var W;z!==((W=i.current.get(L))==null?void 0:W.value)&&(i.current.set(L,{value:z,keywords:X}),a.current.filtered.items.set(L,k(z,X)),C(2,()=>{N(),E.emit()}))},item:(L,z)=>(r.current.add(L),z&&(n.current.has(z)?n.current.get(z).add(L):n.current.set(z,new Set([L]))),C(3,()=>{I(),N(),a.current.value||O(),E.emit()}),()=>{i.current.delete(L),r.current.delete(L),a.current.filtered.items.delete(L);let X=T();C(4,()=>{I(),(X==null?void 0:X.getAttribute("id"))===L&&O(),E.emit()})}),group:L=>(n.current.has(L)||n.current.set(L,new Set),()=>{i.current.delete(L),n.current.delete(L)}),filter:()=>o.current.shouldFilter,label:c||t["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:y,inputId:w,labelId:v,listInnerRef:S}),[]);function k(L,z){var X,W;let U=(W=(X=o.current)==null?void 0:X.filter)!=null?W:Sk;return L?U(L,a.current.search,z):0}function N(){if(!a.current.search||o.current.shouldFilter===!1)return;let L=a.current.filtered.items,z=[];a.current.filtered.groups.forEach(W=>{let U=n.current.get(W),V=0;U.forEach(Q=>{let ee=L.get(Q);V=Math.max(ee,V)}),z.push([W,V])});let X=S.current;M().sort((W,U)=>{var V,Q;let ee=W.getAttribute("id"),K=U.getAttribute("id");return((V=L.get(K))!=null?V:0)-((Q=L.get(ee))!=null?Q:0)}).forEach(W=>{let U=W.closest(xo);U?U.appendChild(W.parentElement===U?W:W.closest(`${xo} > *`)):X.appendChild(W.parentElement===X?W:W.closest(`${xo} > *`))}),z.sort((W,U)=>U[1]-W[1]).forEach(W=>{var U;let V=(U=S.current)==null?void 0:U.querySelector(`${Pn}[${Zr}="${encodeURIComponent(W[0])}"]`);V==null||V.parentElement.appendChild(V)})}function O(){let L=M().find(X=>X.getAttribute("aria-disabled")!=="true"),z=L==null?void 0:L.getAttribute(Zr);E.setState("value",z||void 0)}function I(){var L,z,X,W;if(!a.current.search||o.current.shouldFilter===!1){a.current.filtered.count=r.current.size;return}a.current.filtered.groups=new Set;let U=0;for(let V of r.current){let Q=(z=(L=i.current.get(V))==null?void 0:L.value)!=null?z:"",ee=(W=(X=i.current.get(V))==null?void 0:X.keywords)!=null?W:[],K=k(Q,ee);a.current.filtered.items.set(V,K),K>0&&U++}for(let[V,Q]of n.current)for(let ee of Q)if(a.current.filtered.items.get(ee)>0){a.current.filtered.groups.add(V);break}a.current.filtered.count=U}function B(){var L,z,X;let W=T();W&&(((L=W.parentElement)==null?void 0:L.firstChild)===W&&((X=(z=W.closest(Pn))==null?void 0:z.querySelector(Ck))==null||X.scrollIntoView({block:"nearest"})),W.scrollIntoView({block:"nearest"}))}function T(){var L;return(L=S.current)==null?void 0:L.querySelector(`${rf}[aria-selected="true"]`)}function M(){var L;return Array.from(((L=S.current)==null?void 0:L.querySelectorAll(lh))||[])}function F(L){let z=M()[L];z&&E.setState("value",z.getAttribute(Zr))}function D(L){var z;let X=T(),W=M(),U=W.findIndex(Q=>Q===X),V=W[U+L];(z=o.current)!=null&&z.loop&&(V=U+L<0?W[W.length-1]:U+L===W.length?W[0]:W[U+L]),V&&E.setState("value",V.getAttribute(Zr))}function A(L){let z=T(),X=z==null?void 0:z.closest(Pn),W;for(;X&&!W;)X=L>0?Ek(X,Pn):_k(X,Pn),W=X==null?void 0:X.querySelector(lh);W?E.setState("value",W.getAttribute(Zr)):D(L)}let H=()=>F(M().length-1),$=L=>{L.preventDefault(),L.metaKey?H():L.altKey?A(1):D(1)},_=L=>{L.preventDefault(),L.metaKey?F(0):L.altKey?A(-1):D(-1)};return x.createElement(xr.div,{ref:s,tabIndex:-1,...j,"cmdk-root":"",onKeyDown:L=>{var z;(z=j.onKeyDown)==null||z.call(j,L);let X=L.nativeEvent.isComposing||L.keyCode===229;if(!(L.defaultPrevented||X))switch(L.key){case"n":case"j":{f&&L.ctrlKey&&$(L);break}case"ArrowDown":{$(L);break}case"p":case"k":{f&&L.ctrlKey&&_(L);break}case"ArrowUp":{_(L);break}case"Home":{L.preventDefault(),F(0);break}case"End":{L.preventDefault(),H();break}case"Enter":{L.preventDefault();let W=T();if(W){let U=new Event(rc);W.dispatchEvent(U)}}}}},x.createElement("label",{"cmdk-label":"",htmlFor:R.inputId,id:R.labelId,style:Ok},c),Rl(t,L=>x.createElement(lf.Provider,{value:E},x.createElement(nf.Provider,{value:R},L))))}),Ak=x.forwardRef((t,s)=>{var a,r;let n=ln(),i=x.useRef(null),l=x.useContext(of),o=bi(),c=df(t),d=(r=(a=c.current)==null?void 0:a.forceMount)!=null?r:l==null?void 0:l.forceMount;Ur(()=>{if(!d)return o.item(n,l==null?void 0:l.id)},[d]);let m=mf(n,i,[t.value,t.children,i],t.keywords),p=yd(),u=ur(C=>C.value&&C.value===m.current),h=ur(C=>d||o.filter()===!1?!0:C.search?C.filtered.items.get(n)>0:!0);x.useEffect(()=>{let C=i.current;if(!(!C||t.disabled))return C.addEventListener(rc,g),()=>C.removeEventListener(rc,g)},[h,t.onSelect,t.disabled]);function g(){var C,E;b(),(E=(C=c.current).onSelect)==null||E.call(C,m.current)}function b(){p.setState("value",m.current,!0)}if(!h)return null;let{disabled:f,value:j,onSelect:y,forceMount:v,keywords:w,...S}=t;return x.createElement(xr.div,{ref:Yn(i,s),...S,id:n,"cmdk-item":"",role:"option","aria-disabled":!!f,"aria-selected":!!u,"data-disabled":!!f,"data-selected":!!u,onPointerMove:f||o.getDisablePointerSelection()?void 0:b,onClick:f?void 0:g},t.children)}),Tk=x.forwardRef((t,s)=>{let{heading:a,children:r,forceMount:n,...i}=t,l=ln(),o=x.useRef(null),c=x.useRef(null),d=ln(),m=bi(),p=ur(h=>n||m.filter()===!1?!0:h.search?h.filtered.groups.has(l):!0);Ur(()=>m.group(l),[]),mf(l,o,[t.value,t.heading,c]);let u=x.useMemo(()=>({id:l,forceMount:n}),[n]);return x.createElement(xr.div,{ref:Yn(o,s),...i,"cmdk-group":"",role:"presentation",hidden:p?void 0:!0},a&&x.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},a),Rl(t,h=>x.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":a?d:void 0},x.createElement(of.Provider,{value:u},h))))}),kk=x.forwardRef((t,s)=>{let{alwaysRender:a,...r}=t,n=x.useRef(null),i=ur(l=>!l.search);return!a&&!i?null:x.createElement(xr.div,{ref:Yn(n,s),...r,"cmdk-separator":"",role:"separator"})}),Dk=x.forwardRef((t,s)=>{let{onValueChange:a,...r}=t,n=t.value!=null,i=yd(),l=ur(d=>d.search),o=ur(d=>d.selectedItemId),c=bi();return x.useEffect(()=>{t.value!=null&&i.setState("search",t.value)},[t.value]),x.createElement(xr.input,{ref:s,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":o,id:c.inputId,type:"text",value:n?t.value:l,onChange:d=>{n||i.setState("search",d.target.value),a==null||a(d.target.value)}})}),Rk=x.forwardRef((t,s)=>{let{children:a,label:r="Suggestions",...n}=t,i=x.useRef(null),l=x.useRef(null),o=ur(d=>d.selectedItemId),c=bi();return x.useEffect(()=>{if(l.current&&i.current){let d=l.current,m=i.current,p,u=new ResizeObserver(()=>{p=requestAnimationFrame(()=>{let h=d.offsetHeight;m.style.setProperty("--cmdk-list-height",h.toFixed(1)+"px")})});return u.observe(d),()=>{cancelAnimationFrame(p),u.unobserve(d)}}},[]),x.createElement(xr.div,{ref:Yn(i,s),...n,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},Rl(t,d=>x.createElement("div",{ref:Yn(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),Fk=x.forwardRef((t,s)=>{let{open:a,onOpenChange:r,overlayClassName:n,contentClassName:i,container:l,...o}=t;return x.createElement(Dh,{open:a,onOpenChange:r},x.createElement(kh,{container:l},x.createElement(ic,{"cmdk-overlay":"",className:n}),x.createElement(lc,{"aria-label":t.label,"cmdk-dialog":"",className:i},x.createElement(cf,{ref:s,...o}))))}),Ik=x.forwardRef((t,s)=>ur(a=>a.filtered.count===0)?x.createElement(xr.div,{ref:s,...t,"cmdk-empty":"",role:"presentation"}):null),Pk=x.forwardRef((t,s)=>{let{progress:a,children:r,label:n="Loading...",...i}=t;return x.createElement(xr.div,{ref:s,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":a,"aria-valuemin":0,"aria-valuemax":100,"aria-label":n},Rl(t,l=>x.createElement("div",{"aria-hidden":!0},l)))}),Cn=Object.assign(cf,{List:Rk,Item:Ak,Input:Dk,Group:Tk,Separator:kk,Dialog:Fk,Empty:Ik,Loading:Pk});function Ek(t,s){let a=t.nextElementSibling;for(;a;){if(a.matches(s))return a;a=a.nextElementSibling}}function _k(t,s){let a=t.previousElementSibling;for(;a;){if(a.matches(s))return a;a=a.previousElementSibling}}function df(t){let s=x.useRef(t);return Ur(()=>{s.current=t}),s}var Ur=typeof window>"u"?x.useEffect:x.useLayoutEffect;function qr(t){let s=x.useRef();return s.current===void 0&&(s.current=t()),s}function ur(t){let s=yd(),a=()=>t(s.snapshot());return x.useSyncExternalStore(s.subscribe,a,a)}function mf(t,s,a,r=[]){let n=x.useRef(),i=bi();return Ur(()=>{var l;let o=(()=>{var d;for(let m of a){if(typeof m=="string")return m.trim();if(typeof m=="object"&&"current"in m)return m.current?(d=m.current.textContent)==null?void 0:d.trim():n.current}})(),c=r.map(d=>d.trim());i.value(t,o,c),(l=s.current)==null||l.setAttribute(Zr,o),n.current=o}),n}var Mk=()=>{let[t,s]=x.useState(),a=qr(()=>new Map);return Ur(()=>{a.current.forEach(r=>r()),a.current=new Map},[t]),(r,n)=>{a.current.set(r,n),s({})}};function Lk(t){let s=t.type;return typeof s=="function"?s(t.props):"render"in s?s.render(t.props):t}function Rl({asChild:t,children:s},a){return t&&x.isValidElement(s)?x.cloneElement(Lk(s),{ref:s.ref},a(s.props.children)):a(s)}var Ok={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function $k({className:t,...s}){return e.jsx(Cn,{"data-slot":"command",className:Me("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",t),...s})}function Uk({className:t,wrapperClassName:s,...a}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:Me("flex h-9 items-center gap-2 border-b px-3",s),children:[e.jsx(Jt,{className:"size-4 shrink-0 opacity-50"}),e.jsx(Cn.Input,{"data-slot":"command-input",className:Me("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",t),...a})]})}function Bk({className:t,...s}){return e.jsx(Cn.List,{"data-slot":"command-list",className:Me("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",t),...s})}function Vk({...t}){return e.jsx(Cn.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...t})}function zk({className:t,...s}){return e.jsx(Cn.Group,{"data-slot":"command-group",className:Me("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",t),...s})}function Hk({className:t,...s}){return e.jsx(Cn.Item,{"data-slot":"command-item",className:Me("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}async function uf(t=!1,s=1,a=10,r){var c,d;const n={active:t,page:s,limit:a};r&&(n.search=r);const i=await be.get("/hsn-sac",{params:n}),l=(c=i.data)==null?void 0:c.data,o=(d=i.data)==null?void 0:d.pagination;return Array.isArray(l)&&o?{codes:l,pagination:o}:{codes:Array.isArray(l)?l:[],pagination:o||{totalRecords:0,totalPages:0,currentPage:1,limit:10}}}async function Gk(t){var a;const s=await be.post("/hsn-sac",t);return((a=s.data)==null?void 0:a.data)||s.data}async function Wk(t,s){var r;const a=await be.patch(`/hsn-sac/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function Yk(t){await be.delete(`/hsn-sac/${t}`)}async function Kk(t){var a;const s=await be.patch(`/hsn-sac/${t}/toggle-active`);return((a=s.data)==null?void 0:a.data)||s.data}function xf({value:t,onChange:s,type:a,placeholder:r,disabled:n,className:i}){var p;const[l,o]=x.useState(!1),[c,d]=x.useState([]);x.useEffect(()=>{const u=async()=>{try{const h=await uf(!0,1,1e3);d(h.codes)}catch(h){console.error("Failed to fetch HSN/SAC codes for selector:",h)}};l&&c.length===0&&u()},[l,c.length]);const m=x.useMemo(()=>c.filter(u=>u.type===a),[c,a]);return e.jsxs(sa,{open:l,onOpenChange:o,children:[e.jsx(aa,{asChild:!0,children:e.jsxs(P,{variant:"outline",role:"combobox","aria-expanded":l,disabled:n,className:Me("w-full justify-between bg-white font-normal h-9 px-3 text-xs sm:text-sm border-slate-200 hover:bg-slate-50",i),children:[e.jsx("span",{className:"font-medium text-slate-900",children:t?((p=c.find(u=>u.code===t))==null?void 0:p.code)||t:r||`Select ${a}...`}),e.jsx(Nj,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(ra,{className:"w-[320px] p-0 shadow-2xl border-slate-200",align:"start",children:e.jsxs($k,{className:"rounded-lg border-0",children:[e.jsxs("div",{className:"bg-slate-50/80 p-2.5 flex items-center gap-2",children:[e.jsx(Jt,{className:"w-4 h-4 text-slate-400"}),e.jsx(Uk,{placeholder:`Search ${a} code...`,wrapperClassName:"border-none p-0 h-auto flex-1",className:"h-8 border-none bg-transparent shadow-none ring-0 focus-visible:ring-0 placeholder:text-slate-400 text-sm"})]}),e.jsxs(Bk,{className:"max-h-[350px] scrollbar-thin scrollbar-thumb-slate-200",children:[e.jsx(Vk,{className:"py-8 text-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Jt,{className:"h-8 w-8 text-slate-200"}),e.jsxs("p",{className:"text-sm font-medium text-slate-500",children:["No ",a," code found"]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Try a different search term"})]})}),e.jsx(zk,{className:"p-1.5",children:m.map(u=>e.jsxs(Hk,{value:u.code,onSelect:h=>{s(h),o(!1)},className:"flex flex-col items-start gap-1 p-2.5 rounded-md aria-selected:bg-slate-100 transition-colors cursor-pointer mb-1 last:mb-0",children:[e.jsxs("div",{className:"flex items-center w-full justify-between",children:[e.jsx("span",{className:"font-bold text-sm text-slate-900 leading-none",children:u.code}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Oa,{className:Me("h-4 w-4 text-re-green transition-all",t===u.code?"opacity-100 scale-100":"opacity-0 scale-75")})})]}),u.description&&e.jsx("span",{className:"text-[11px] text-slate-500 line-clamp-2 leading-tight pr-4",children:u.description})]},u.id))})]})]})})]})}const fa=(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:""}},Qk={"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"},Xk="33",Jk=new Set(["04","25","26","31","35","38"]),hf=t=>{if(!t||t.length<2)return null;const s=t.substring(0,2);return Qk[s]?s:null},Zk=t=>t?Jk.has(t):!1,qk=t=>t?t!==Xk:!1,pf=t=>{if(!t)return{isIGST:!1,isCGST:!0,isSGST:!0,isUTGST:!1};if(qk(t))return{isIGST:!0,isCGST:!1,isSGST:!1,isUTGST:!1};const a=Zk(t);return{isIGST:!1,isCGST:!0,isSGST:!a,isUTGST:a}};function e4({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",dealerGSTIN:n,activityName:i="Activity",requestId:l,defaultGstRate:o=18,documentPolicy:c,taxationType:d}){var Ce,Ae;const[m,p]=x.useState(""),[u,h]=x.useState(""),g=x.useMemo(()=>{const ce=hf(n);return pf(ce)},[n]),b=x.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),[f,j]=x.useState([]),[y,v]=x.useState([]),[w,S]=x.useState([]),[C,E]=x.useState([]),[R,k]=x.useState(null),[N,O]=x.useState(""),[I,B]=x.useState(!1),[T,M]=x.useState(null),F=x.useRef(null),D=x.useRef(null),A=x.useRef(null),H=x.useRef(null),$=ce=>{const pe=ce.type.toLowerCase(),Te=ce.name.toLowerCase();return pe.includes("image")||pe.includes("pdf")||Te.endsWith(".pdf")||Te.endsWith(".jpg")||Te.endsWith(".jpeg")||Te.endsWith(".png")||Te.endsWith(".gif")||Te.endsWith(".webp")};x.useEffect(()=>()=>{T!=null&&T.url&&URL.revokeObjectURL(T.url)},[T]),x.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 _=ce=>{if(!$(ce)){G.error("Preview is only available for images and PDF files");return}T!=null&&T.url&&URL.revokeObjectURL(T.url);const pe=URL.createObjectURL(ce);M({file:ce,url:pe})},L=ce=>{const pe=URL.createObjectURL(ce),Te=document.createElement("a");Te.href=pe,Te.download=ce.name,document.body.appendChild(Te),Te.click(),document.body.removeChild(Te),URL.revokeObjectURL(pe)},z=x.useMemo(()=>f.reduce((ce,pe)=>ce+(pe.totalAmt||pe.amount||0),0),[f]),X=(ce,pe,Te=1)=>{const de=ce*Te,me=de*(pe.cgstRate||0)/100,Ne=de*(pe.sgstRate||0)/100,Oe=de*(pe.utgstRate||0)/100,st=de*(pe.igstRate||0)/100,nt=me+Ne+Oe+st,St=de+nt;return{cgstRate:pe.cgstRate,cgstAmt:me,sgstRate:pe.sgstRate,sgstAmt:Ne,utgstRate:pe.utgstRate,utgstAmt:Oe,igstRate:pe.igstRate,igstAmt:st,gstAmt:nt,gstRate:(pe.cgstRate||0)+(pe.sgstRate||0)+(pe.utgstRate||0)+(pe.igstRate||0),totalAmt:St}},W=x.useMemo(()=>{const ce=m!=="",pe=y.length>0,Te=w.length>0,de=N.trim().length>0,me=f.length>0&&f.every(Oe=>Oe.description.trim()!==""&&Oe.amount>0),Ne=b?!1:f.some(Oe=>{const{isValid:st}=fa(Oe.hsnCode,Oe.isService);return!st});return ce&&pe&&Te&&de&&me&&!Ne},[m,y,w,N,b,f]),U=new Date().toISOString().split("T")[0],V=()=>{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}])},Q=(ce,pe,Te)=>{j(f.map(de=>{if(de.id===ce){let me={...de,[pe]:Te};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate","quantity"].includes(pe)){const Ne=parseFloat(Te);if(!isNaN(Ne)&&Ne<0)return G.error("Value cannot be negative"),de;const Oe=pe==="amount"?parseFloat(Te)||0:de.amount,st=pe==="quantity"?parseInt(Te)||1:de.quantity;let nt=de.cgstRate,St=de.sgstRate,Mt=de.utgstRate,ne=de.igstRate;if(pe==="cgstRate"){if(!g.isCGST)return de;nt=parseFloat(Te)||0,g.isUTGST?(Mt=nt,St=0):(St=nt,Mt=0),ne=0}else if(pe==="sgstRate"){if(!g.isSGST)return de;St=parseFloat(Te)||0,nt=St,Mt=0,ne=0}else if(pe==="utgstRate"){if(!g.isUTGST)return de;Mt=parseFloat(Te)||0,nt=Mt,St=0,ne=0}else if(pe==="igstRate"){if(!g.isIGST)return de;ne=parseFloat(Te)||0,nt=0,St=0,Mt=0}else if(pe==="gstRate"){const oe=parseFloat(Te)||0;g.isIGST?(ne=oe,nt=0,St=0,Mt=0):(nt=oe/2,g.isUTGST?(Mt=oe/2,St=0):(St=oe/2,Mt=0),ne=0)}const Ee=X(Oe,{cgstRate:nt,sgstRate:St,igstRate:ne,utgstRate:Mt},st);return pe==="isService"&&(me.hsnCode=""),{...me,amount:Oe,quantity:st,...Ee}}return pe==="isService"&&(me.hsnCode=""),me}return de}))},ee=ce=>{j(f.filter(pe=>pe.id!==ce))},K=ce=>{const pe=Array.from(ce.target.files||[]);if(pe.length>0){const Te=[],de=c.maxFileSizeMB*1024*1024,me=[".pdf",".doc",".docx",".zip",".rar"];pe.forEach(Ne=>{var nt,St;const Oe="."+((nt=Ne.name.split(".").pop())==null?void 0:nt.toLowerCase()),st=((St=Ne.name.split(".").pop())==null?void 0:St.toLowerCase())||"";if(Ne.size>de){G.error(`"${Ne.name}" exceeds ${c.maxFileSizeMB}MB limit and was not added.`);return}if(!me.includes(Oe)){G.error(`"${Ne.name}" is not a supported document type (PDF, DOC, ZIP).`);return}if(!c.allowedFileTypes.includes(st)){G.error(`"${Ne.name}" has an unallowed file type according to system policy.`);return}Te.push(Ne)}),Te.length>0&&v([...y,...Te]),F.current&&(F.current.value="")}},q=ce=>{v(y.filter((pe,Te)=>Te!==ce))},ue=ce=>{const pe=Array.from(ce.target.files||[]);if(pe.length>0){const Te=[],de=c.maxFileSizeMB*1024*1024;pe.forEach(me=>{var Oe;const Ne=((Oe=me.name.split(".").pop())==null?void 0:Oe.toLowerCase())||"";if(me.size>de){G.error(`Photo "${me.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!me.type.startsWith("image/")){G.error(`"${me.name}" is not an image file.`);return}if(!c.allowedFileTypes.includes(Ne)){G.error(`"${me.name}" has an unsupported image format.`);return}Te.push(me)}),Te.length>0&&S([...w,...Te]),D.current&&(D.current.value="")}},Le=ce=>{S(w.filter((pe,Te)=>Te!==ce))},Ze=ce=>{const pe=Array.from(ce.target.files||[]);if(pe.length>0){const Te=[],de=c.maxFileSizeMB*1024*1024,me=[".pdf",".jpg",".jpeg",".png"];pe.forEach(Ne=>{var nt,St;const Oe="."+((nt=Ne.name.split(".").pop())==null?void 0:nt.toLowerCase()),st=((St=Ne.name.split(".").pop())==null?void 0:St.toLowerCase())||"";if(Ne.size>de){G.error(`Invoice "${Ne.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!me.includes(Oe)){G.error(`"${Ne.name}" is not a supported type (PDF, JPG, PNG).`);return}if(!c.allowedFileTypes.includes(st)){G.error(`"${Ne.name}" format is not allowed by system policy.`);return}Te.push(Ne)}),Te.length>0&&E([...C,...Te]),A.current&&(A.current.value="")}},De=ce=>{E(C.filter((pe,Te)=>Te!==ce))},_e=ce=>{var Te,de,me;const pe=(Te=ce.target.files)==null?void 0:Te[0];if(pe){const Ne=c.maxFileSizeMB*1024*1024,Oe=[".pdf",".xlsx",".xls",".csv"],st="."+((de=pe.name.split(".").pop())==null?void 0:de.toLowerCase()),nt=((me=pe.name.split(".").pop())==null?void 0:me.toLowerCase())||"";if(pe.size>Ne){G.error(`Attendance file exceeds ${c.maxFileSizeMB}MB limit.`),H.current&&(H.current.value="");return}if(!Oe.includes(st)){G.error("Please upload PDF, Excel, or CSV files only"),H.current&&(H.current.value="");return}if(!c.allowedFileTypes.includes(nt)){G.error(`"${pe.name}" format is not allowed by system policy.`),H.current&&(H.current.value="");return}k(pe)}},Ue=async()=>{if(!W){G.error("Please fill all required fields");return}if(f.some(de=>de.amount<0||de.quantity<1)){G.error("Please ensure all amounts are non-negative and quantity is at least 1");return}const pe=f.filter(de=>de.description.trim()!==""&&de.amount>0);if(!b&&pe.some(de=>de.description.trim()!==""&&de.amount>0&&(de.gstRate===0||!de.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(P,{variant:"ghost",size:"sm",onClick:()=>E(!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:q.map((ne,Ee)=>{const oe=ne.userId===N;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(cs,{className:"h-9 w-9 sm:h-10 sm:w-10",children:e.jsx(ds,{className:`text-white font-semibold text-sm ${ne.role==="Initiator"?"bg-green-600":oe?"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 ${k5(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," ",oe&&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:D5(ne.status)})]}),ne.lastSeen&&ne.status==="offline"&&e.jsx("p",{className:"text-xs text-gray-400",children:ne.lastSeen})]})]},Ee)})})]}),!De&&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(P,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>D(!0),children:[e.jsx(ml,{className:"h-4 w-4"}),"Add Approver"]}),e.jsxs(P,{variant:"outline",size:"sm",className:"w-full justify-start gap-2 h-9 text-sm",onClick:()=>M(!0),children:[e.jsx(vt,{className:"h-4 w-4"}),"Add Spectator"]})]})]})]})]}),I&&e.jsx(Gr,{fileName:I.fileName,fileType:I.fileType,fileUrl:I.fileUrl,fileSize:I.fileSize,attachmentId:I.attachmentId,onDownload:Du,open:!!I,onClose:()=>B(null)}),!De&&e.jsx(H0,{open:T,onClose:()=>M(!1),onConfirm:Ne,requestIdDisplay:h,requestTitle:K.title,existingParticipants:Ue}),!De&&l&&e.jsx(G0,{open:F,onClose:()=>D(!1),onConfirm:Oe,requestIdDisplay:h,requestTitle:K.title,existingParticipants:Ue,currentLevels:c,maxApprovalLevels:m,onPolicyViolation:p}),e.jsx(xt,{open:Q.open,onOpenChange:ne=>ee(Ee=>({...Ee,open:ne})),children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Et,{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:Q.errors.map((ne,Ee)=>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})]},Ee))}),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: ",U.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",U.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Dt,{children:e.jsx(P,{onClick:()=>ee({open:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(z0,{open:A,onClose:()=>H(!1),success:$.success,title:$.title,message:$.message})]})}function I5({requestId:t,requestTitle:s,mergedMessages:a,setWorkNoteAttachments:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d}){return e.jsx("div",{className:"h-[calc(100vh-300px)] min-h-[600px]",children:e.jsx(W0,{requestId:t,requestTitle:s,skipSocketJoin:!0,messages:a,onAttachmentsExtracted:r,isInitiator:n,isSpectator:i,currentLevels:l,onAddApprover:o,maxApprovalLevels:c,onPolicyViolation:d})})}function P5({summary:t,loading:s,onShare:a,isInitiator:r}){const n=o=>{const c=o.toLowerCase();return c==="approved"?e.jsx(Be,{className:"h-4 w-4 text-green-600"}):c==="rejected"?e.jsx(Ct,{className:"h-4 w-4 text-red-600"}):c==="pending"||c==="in progress"?e.jsx(rt,{className:"h-4 w-4 text-orange-600"}):e.jsx(Re,{className:"h-4 w-4 text-gray-600"})},i=o=>{const c=o.toLowerCase();return c==="approved"?"bg-green-100 text-green-700 border-green-300":c==="rejected"?"bg-red-100 text-red-700 border-red-300":c==="pending"||c==="in progress"?"bg-orange-100 text-orange-700 border-orange-300":"bg-gray-100 text-gray-700 border-gray-300"},l=(o,c)=>o&&o.trim()&&o.trim().toUpperCase()!=="N/A"?o:c&&c.trim()&&c.trim().toUpperCase()!=="N/A"?c:"N/A";return s?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ze,{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(P,{variant:"outline",size:"sm",onClick:a,className:"flex items-center gap-2",children:[e.jsx(pn,{className:"w-4 h-4"}),e.jsx("span",{children:"Share"})]}):e.jsxs(ae,{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(Ps,{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,c)=>e.jsxs("div",{className:"mb-6 last:mb-0",children:[e.jsx("h4",{className:"text-md font-semibold text-gray-800 mb-3",children: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(Ps,{content:o.remarks,className:"text-sm text-gray-700"}):e.jsx("p",{className:"text-sm text-gray-700",children:"—"})]})]},c))]}),e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Closing Remarks (Conclusion)"}),e.jsxs("div",{className:"bg-gray-50 rounded-lg p-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Name"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.initiator.name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Designation"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children: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(ae,{variant:"outline",className:"text-xs",children:"AI Generated"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 mb-1",children:"Remarks"}),t.closingRemarks?e.jsx(Ps,{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(Re,{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 E5({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(nr,{className:"h-4 w-4 text-gray-600"}):s==="approved"?e.jsx(Be,{className:"h-4 w-4 text-green-600"}):s==="rejected"?e.jsx(Ct,{className:"h-4 w-4 text-red-600"}):e.jsx(rt,{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",c=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"},d=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(nr,{className:`h-4 w-4 ${c.icon}`}):e.jsx(rt,{className:`h-4 w-4 ${c.icon}`}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:a?"SLA Progress (Paused)":"SLA Progress"})]}),e.jsxs(ae,{className:`text-xs ${c.badge}`,"data-testid":`${r}-badge`,children:[i,"% elapsed ",a&&"(frozen)"]})]}),e.jsx(na,{value:i,className:"h-3 mb-2",indicatorClassName:c.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 ${d==="breached"||d==="critical"?c.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: ",Ra(t.deadline,!0)," • ",i,"% elapsed"]}),d==="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(ss,{className:"h-3.5 w-3.5"}),"Approaching Deadline"]}),d==="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(Gi,{className:"h-3.5 w-3.5"}),"URGENT - Deadline Passed"]})]})}function _5({request:t,refreshing:s,onBack:a,onRefresh:r,onShareSummary:n,isInitiator:i,slaData:l,isPaused:o=!1}){var g,b;const c=C5((t==null?void 0:t.priority)||"standard"),d=((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)),u=m&&String(m).toLowerCase()==="duplicate",h=d&&m?{color:p?"bg-red-100 !text-red-800 border-red-200":m==="Completed"?"bg-green-100 !text-green-800 border-green-200":u?"bg-amber-100 !text-amber-800 border-amber-200":"bg-gray-100 !text-gray-700 border-gray-200",icon:ah((t==null?void 0:t.status)||"pending").icon,label:m}:ah((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(P,{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(Re,{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(ae,{className:`${c.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"priority-badge",children:c.label}),e.jsx(ae,{className:`${h.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`,variant:"outline","data-testid":"status-badge",children:h.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",E="bg-purple-100 !text-purple-600 border-purple-200";return v?(C="Form 16",E="bg-emerald-100 !text-emerald-700 border-emerald-200"):S?(C="Dealer Claim",E="bg-blue-100 !text-blue-700 border-blue-200"):w?(C="Claim Management",E="bg-blue-100 !text-blue-700 border-blue-200"):y==="TEMPLATE"&&(C="Template"),e.jsx(ae,{className:`${E} 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(P,{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(pn,{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(P,{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(Pt,{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(E5,{sla:l,requestStatus:t.status,isPaused:o,testId:"request-sla"})})]})}async function bd(t){return(await be.get(`/summaries/${t}`)).data.data}async function M5(t,s){return(await be.post(`/summaries/${t}/share`,{userIds:s})).data.data}async function L5(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 Y0(t){await be.patch(`/summaries/shared/${t}/view`)}async function K0(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 O5(t){return(await be.get(`/summaries/${t}/recipients`)).data.data||[]}function $5({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(ie,{children:e.jsxs(le,{className:"flex items-center gap-2 text-base",children:[e.jsx(gt,{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(pc,{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(ka,{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(_t,{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(Ps,{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:bs(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:bs(r)})]})]})]})]})}function U5({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(ie,{children:e.jsxs(le,{className:"flex items-center gap-2 text-base",children:[e.jsx(xl,{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(ya,{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(ri,{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(pc,{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 B5({dmsDetails:t,claimAmount:s,estimatedBudgetBreakdown:a,closedExpensesBreakdown:r,visibility:n,onEditClaimAmount:i,className:l}){const o=u=>u==null||Number.isNaN(u)?"₹0.00":`₹${u.toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,c=u=>{if(!u)return"";try{return et(new Date(u),"MMM d, yyyy, h:mm a")}catch{return u||""}},d=u=>!u||u.length===0?0:u.reduce((h,g)=>h+(g.totalAmt??g.amount+(g.gstAmt??0)),0),m=!!(t!=null&&t.eInvoiceNumber||t!=null&&t.ackNo||t!=null&&t.eInvoiceDate||t!=null&&t.dmsNumber||t!=null&&t.ackDate||t!=null&&t.irn||t!=null&&t.signedInvoiceUrl);return n.showDMSDetails&&t||(t==null?void 0:t.creditNoteWfmData)&&t.creditNoteWfmData.length>0||n.showClaimAmount&&s&&s.amount!==void 0&&s.amount!==null||a&&a.length>0||r&&r.length>0?e.jsxs(Z,{className:`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${l}`,children:[e.jsxs(ie,{children:[e.jsxs(le,{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:[n.showDMSDetails&&t&&m&&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(se,{className:"text-xs font-semibold text-purple-900 uppercase tracking-wide",children:"E-Invoice Details"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-2",children:[(t.eInvoiceNumber||t.ackNo)&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Invoice Number"}),e.jsx("p",{className:"font-bold text-sm text-purple-700",children:t.eInvoiceNumber||t.ackNo})]}),t.eInvoiceDate&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Invoice Date"}),e.jsx("p",{className:"font-semibold text-xs text-gray-700",children:c(t.eInvoiceDate)})]}),t.dmsNumber&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"DMS Number"}),e.jsx("p",{className:"font-semibold text-xs text-gray-700",children:t.dmsNumber})]}),t.ackDate&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Ack Date"}),e.jsx("p",{className:"font-semibold text-xs text-gray-700",children:c(t.ackDate)})]}),t.ackNo&&t.eInvoiceNumber&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 uppercase",children:"Ack No"}),e.jsx("p",{className:"font-semibold text-xs text-gray-700",children:t.ackNo})]})]}),t.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:t.irn})]}),t.signedInvoiceUrl&&e.jsxs(P,{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(t.signedInvoiceUrl,"_blank"),children:[e.jsx(_t,{className:"w-3.5 h-3.5"}),"View E-Invoice"]}),t.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:t.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 ",t.createdByName||"System"]}),e.jsx("p",{className:"text-[10px] text-gray-500",children:c(t.createdAt)})]})]}),(t==null?void 0:t.creditNoteWfmData)&&t.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(_t,{className:"w-4 h-4 text-pink-600"}),e.jsx(se,{className:"text-xs font-semibold text-pink-900 uppercase tracking-wide",children:"Credit Note Details"})]}),e.jsx("div",{className:"space-y-2",children:t.creditNoteWfmData.map((u,h)=>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.5 text-pink-900",children:[e.jsxs("span",{className:"font-semibold break-words flex-1 pr-2 uppercase",children:["CN No: ",u.DOC_NO||"N/A"]}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-sm text-white font-medium self-start whitespace-nowrap ${u.MSG_TYP==="E"?"bg-red-500":"bg-green-500"}`,children:u.MSG_TYP==="E"?"Error":u.MSG_TYP==="S"?"Success":u.MSG_TYP||"Processed"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1 mb-1.5 text-gray-600",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Txn No:"}),e.jsx("span",{className:"font-medium",children:u.TRNS_UNIQ_NO||"N/A"})]}),u.TDS_AMT!==void 0&&u.TDS_AMT!==null&&u.TDS_AMT!==""&&(Number.isNaN(Number(u.TDS_AMT))||Number(u.TDS_AMT)!==0)&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"TDS:"}),e.jsx("span",{className:"font-medium text-red-600",children:Number.isNaN(Number(u.TDS_AMT))?String(u.TDS_AMT):o(Number(u.TDS_AMT))})]}),e.jsxs("div",{className:"flex justify-between col-span-2 pt-1 border-t border-pink-100",children:[e.jsx("span",{className:"font-semibold",children:"Credit Amount:"}),e.jsx("span",{className:"font-bold text-pink-700",children:u.CREDITED_TOTAL_AMT!==void 0&&u.CREDITED_TOTAL_AMT!==null&&u.CREDITED_TOTAL_AMT!==""?Number.isNaN(Number(u.CREDITED_TOTAL_AMT))?String(u.CREDITED_TOTAL_AMT):o(Number(u.CREDITED_TOTAL_AMT)):o(0)})]})]}),u.MESSAGE&&e.jsx("div",{className:"text-gray-700 italic border-l-2 border-pink-200 pl-1.5 mt-1 leading-tight",children:u.MESSAGE})]},h))})]}),n.showClaimAmount&&s&&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(ka,{className:"w-4 h-4 text-green-600"}),e.jsx(se,{className:"text-xs font-semibold text-green-900 uppercase tracking-wide",children:"Claim Amount"})]}),n.canEditClaimAmount&&i&&e.jsxs(P,{variant:"outline",size:"sm",onClick:i,className:"h-7 px-2 text-xs border-green-300 hover:bg-green-50",children:[e.jsx(Qn,{className:"w-3 h-3 mr-1 text-green-700"}),"Edit"]})]}),e.jsx("p",{className:"text-2xl font-bold text-green-700",children:o(s.amount)}),s.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 ",s.lastUpdatedBy]}),s.lastUpdatedAt&&e.jsx("p",{className:"text-xs text-gray-500",children:c(s.lastUpdatedAt)})]})]}),a&&a.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(_t,{className:"w-4 h-4 text-amber-600"}),e.jsx(se,{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:[a.map((u,h)=>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:u.description,children:u.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:o(u.totalAmt??u.amount+(u.gstAmt??0))})]},h)),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:o(d(a))})]})]})]}),r&&r.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(_t,{className:"w-4 h-4 text-indigo-600"}),e.jsx(se,{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:[r.map((u,h)=>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:u.description,children:u.description}),e.jsx("span",{className:"font-medium text-gray-900 whitespace-nowrap",children:o(u.totalAmt??u.amount+(u.gstAmt??0))})]},h)),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:o(d(r))})]})]})]})]})]}):null}function V5({proposalDetails:t,className:s}){const r=(()=>{const o=t.totalEstimatedBudget??t.estimatedBudgetTotal;return o??(t.costBreakup&&t.costBreakup.length>0?t.costBreakup.reduce((d,m)=>{const p=m.amount||0,u=m.gstAmt||0,h=m.totalAmt||Number(p)+Number(u);return d+(Number.isNaN(h)?0:h)},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(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2 text-base",children:[e.jsx(_t,{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,c)=>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))})]},c)),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(gt,{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 z5({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(ie,{children:e.jsx(le,{className:"text-base",children:"Request Initiator"})}),e.jsx(te,{children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(cs,{className:"h-14 w-14 ring-2 ring-white shadow-md",children:e.jsx(ds,{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(ya,{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(ri,{className:"w-4 h-4"}),e.jsx("span",{children:t.phone})]})]})]})]})})]})}function Q0(t,s){var a,r,n,i,l;try{if(!ai(t))return null;const o=t.claimDetails||{},c=t.proposalDetails||{},d=t.completionDetails||{},m=t.internalOrder||t.internal_order||{},p=t.budgetTracking||t.budget_tracking||{},u=t.invoice||{},h=t.creditNote||t.credit_note||{},g=t.completionExpenses||t.completion_expenses||[],b=o.periodStartDate||o.period_start_date,f=o.periodEndDate||o.period_end_date,j=o.activityName||o.activity_name||"",y=o.activityType||o.activity_type||"",v=o.location||"",w=p.proposalEstimatedBudget??p.proposal_estimated_budget??p.initialEstimatedBudget??p.initial_estimated_budget??o.estimatedBudget??o.estimated_budget,S=(p==null?void 0:p.closedExpenses)??(p==null?void 0:p.closed_expenses)??(d==null?void 0:d.totalClosedExpenses)??(d==null?void 0:d.total_closed_expenses)??(o==null?void 0:o.closedExpenses)??(o==null?void 0:o.closed_expenses),C=S!=null?Number(S):void 0,E=Array.isArray(g)&&g.length>0?g.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})):(d==null?void 0:d.closedExpenses)||(d==null?void 0:d.closed_expenses)||(d==null?void 0:d.closedExpensesBreakdown)||[],R={activityName:j,activityType:y,defaultGstRate:o.defaultGstRate||18,requestedDate:o.activityDate||o.activity_date||t.createdAt,location:v,period:b&&f?{startDate:b,endDate:f}:void 0,estimatedBudget:w,closedExpenses:C,closedExpensesBreakdown:E,description:t.description||""},k={dealerCode:(o==null?void 0:o.dealerCode)||(o==null?void 0:o.dealer_code)||(o==null?void 0:o.DealerCode)||"",dealerName:(o==null?void 0:o.dealerName)||(o==null?void 0:o.dealer_name)||(o==null?void 0:o.DealerName)||"",email:(o==null?void 0:o.dealerEmail)||(o==null?void 0:o.dealer_email)||(o==null?void 0:o.DealerEmail)||"",phone:(o==null?void 0:o.dealerPhone)||(o==null?void 0:o.dealer_phone)||(o==null?void 0:o.DealerPhone)||"",address:(o==null?void 0:o.dealerAddress)||(o==null?void 0:o.dealer_address)||(o==null?void 0:o.DealerAddress)||""};(!k.dealerCode||!k.dealerName)&&console.warn("[claimDataMapper] Dealer information is missing from claimDetails:",{hasClaimDetails:!!o,dealerCode:k.dealerCode,dealerName:k.dealerName,rawClaimDetails:o,availableKeys:o?Object.keys(o):[]});const N=(c==null?void 0:c.expectedCompletionDate)||(c==null?void 0:c.expected_completion_date),I=!!(c&&Object.keys(c).length>0&&(Array.isArray(c.costItems||c.cost_items)&&(c.costItems||c.cost_items).length>0||Array.isArray(c.costBreakup||c.cost_breakup)&&(c.costBreakup||c.cost_breakup).length>0||c.proposalDocumentUrl||c.proposal_document_url||c.totalEstimatedBudget||c.total_estimated_budget||c.expectedCompletionDate||c.expected_completion_date||c.submittedAt||c.submitted_at))?{proposalDocumentUrl:c.proposalDocumentUrl||c.proposal_document_url,costBreakup:Array.isArray(c.costItems||c.cost_items)?(c.costItems||c.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(c.costBreakup||c.cost_breakup)?(c.costBreakup||c.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:c.totalEstimatedBudget||c.total_estimated_budget||0,timelineMode:c.timelineMode||c.timeline_mode,expectedCompletionDate:N,timelineForClosure:N,expectedCompletionDays:c.expectedCompletionDays||c.expected_completion_days,dealerComments:c.dealerComments||c.dealer_comments,submittedAt:c.submittedAt||c.submitted_at||c.submittedOn,submittedOn:c.submittedAt||c.submitted_at||c.submittedOn}:void 0,B={ioNumber:m.ioNumber||m.io_number||o.ioNumber||o.io_number,ioRemark:m.ioRemark||m.io_remark||"",availableBalance:m.ioAvailableBalance||m.io_available_balance||o.ioAvailableBalance||o.io_available_balance,blockedAmount:m.ioBlockedAmount||m.io_blocked_amount||o.ioBlockedAmount||o.io_blocked_amount,remainingBalance:m.ioRemainingBalance||m.io_remaining_balance||o.ioRemainingBalance||o.io_remaining_balance,organizedBy:((a=m.organizer)==null?void 0:a.displayName)||((r=m.organizer)==null?void 0:r.name)||m.organizedBy||"",organizedAt:m.organizedAt||m.organized_at||""},T=t.invoice||t.claimInvoice||t.claim_invoice||((n=t.claimRequest)==null?void 0:n.invoice)||((i=t.request)==null?void 0:i.invoice)||u||{},M=o||{},F={eInvoiceNumber:T.invoiceNumber||T.invoice_number||M.eInvoiceNumber||M.e_invoice_number||T.dmsNumber||T.dms_number,eInvoiceDate:T.invoiceDate||T.invoice_date||M.eInvoiceDate||M.e_invoice_date,dmsNumber:T.dmsNumber||T.dms_number||M.dmsNumber||M.dms_number,creditNoteNumber:h.creditNoteNumber||h.credit_note_number||M.creditNoteNumber||M.credit_note_number,creditNoteDate:h.creditNoteDate||h.credit_note_date||M.creditNoteDate||M.credit_note_date,creditNoteAmount:h.creditNoteAmount!==void 0&&h.creditNoteAmount!==null?Number(h.creditNoteAmount):h.credit_note_amount!==void 0&&h.credit_note_amount!==null?Number(h.credit_note_amount):M.creditNoteAmount!==void 0&&M.creditNoteAmount!==null?Number(M.creditNoteAmount):M.credit_note_amount!==void 0&&M.credit_note_amount!==null?Number(M.credit_note_amount):void 0,irn:T.irn||M.irn,ackNo:T.ackNo||T.ack_no||M.ackNo||M.ack_no,ackDate:T.ackDate||T.ack_date||M.ackDate||M.ack_date,signedInvoiceUrl:T.signedInvoiceUrl||T.signed_invoice_url||M.signedInvoiceUrl||M.signed_invoice_url,taxBreakdown:T.taxBreakdown||M.taxBreakdown,creditNoteWfmData:(((l=t.creditNote)==null?void 0:l.items)||t.creditNoteWfmData||o.creditNoteWfmData||[]).map(A=>{var H;return{...A,DOC_NO:A.creditNoteNumber||((H=t.creditNote)==null?void 0:H.creditNoteNumber)||A.DOC_NO,TRNS_UNIQ_NO:A.transactionNo||A.TRNS_UNIQ_NO,MESSAGE:A.description||A.MESSAGE,TDS_AMT:A.tdsAmount||A.TDS_AMT,CREDITED_TOTAL_AMT:A.creditAmount||A.amount||A.CREDITED_TOTAL_AMT}})},D={estimated:R.estimatedBudget||0,closed:R.closedExpenses||0};return{activityInfo:R,dealerInfo:k,proposalDetails:I,ioDetails:Object.keys(B).some(A=>B[A])?B:void 0,dmsDetails:Object.keys(F).some(A=>F[A])?F:void 0,claimAmount:D}}catch(o){return console.error("[claimDataMapper] Error mapping claim data:",o),null}}function X0(t,s){var a,r,n,i,l,o,c,d;try{const m=v=>(v||"").toString().trim().toLowerCase(),p=Array.isArray(t.participants)?t.participants:[],u=p.find(v=>{var w;return v.userId===s||v.user_id===s||((w=v.user)==null?void 0:w.userId)===s}),h=m((u==null?void 0:u.userEmail)||(u==null?void 0:u.user_email)||(u==null?void 0:u.email)||((a=u==null?void 0:u.user)==null?void 0:a.email)||(t.initiatorId===s?(r=t.initiator)==null?void 0:r.email:"")),g=m(((n=t==null?void 0:t.claimDetails)==null?void 0:n.dealerEmail)||((i=t==null?void 0:t.claimDetails)==null?void 0:i.dealer_email)||(t==null?void 0:t.dealerEmail)||((l=t==null?void 0:t.dealer)==null?void 0:l.email));if(g&&h&&h===g)return"DEALER";if(t.initiatorId===s||t.initiator_id===s||((o=t.initiator)==null?void 0:o.userId)===s||((c=t.initiator)==null?void 0:c.user_id)===s||((d=t.requestedBy)==null?void 0:d.userId)===s)return"INITIATOR";if(p.find(v=>{var w,S;return(v.userId===s||v.user_id===s||((w=v.user)==null?void 0:w.userId)===s||((S=v.user)==null?void 0:S.user_id)===s)&&(v.participantType||v.participant_type||v.type||"").toString().toUpperCase()==="DEALER"}))return"DEALER";const f=t.approvalLevels||[];return f.find(v=>{var w;return v.levelNumber===3&&(v.approverId===s||((w=v.approver)==null?void 0:w.userId)===s)})?"DEPARTMENT_LEAD":f.find(v=>{var w;return(v.approverId===s||((w=v.approver)==null?void 0:w.userId)===s)&&v.status==="PENDING"})?"APPROVER":"SPECTATOR"}catch(m){return console.error("[claimDataMapper] Error determining user role:",m),"SPECTATOR"}}function J0(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:!0,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:!0,showProposalDetails:!0,showIODetails:!1,showDMSDetails:!0,showClaimAmount:!1,canEditClaimAmount:!1}}}function H5({request:t,isInitiator:s,isSpectator:a,currentApprovalLevel:r,onAddApprover:n,onAddSpectator:i,onApprove:l,onReject:o,onPause:c,onResume:d,onRetrigger:m,summaryId:p,refreshTrigger:u,pausedByUserId:h,currentUserId:g,apiRequest:b,onEditClaimAmount:f,hideApproveReject:j=!1}){var D,A,H,$,_;const{user:y}=us(),[v,w]=x.useState([]),[S,C]=x.useState(!1),[E,R]=x.useState(!1),k=(t==null?void 0:t.status)==="closed",N=((D=t==null?void 0:t.pauseInfo)==null?void 0:D.isPaused)||!1,O=h||((H=(A=t==null?void 0:t.pauseInfo)==null?void 0:A.pausedBy)==null?void 0:H.userId),I=g||(y==null?void 0:y.userId)||"",B=!N&&!k&&(r||s),T=N&&d&&(r||s),M=N&&s&&O&&O!==I&&m;x.useEffect(()=>{if(!N||!r||!(t!=null&&t.requestId)){R(!1);return}(async()=>{var z;try{const U=(((z=(await ir.list({page:1,limit:50,unreadOnly:!0})).data)==null?void 0:z.notifications)||[]).some(V=>V.requestId===t.requestId&&V.notificationType==="pause_retrigger_request");R(U)}catch(X){console.error("Failed to check retrigger notifications:",X),R(!1)}})()},[N,r,t==null?void 0:t.requestId,u]),x.useEffect(()=>{(async()=>{if(!k||!p||!s){w([]);return}try{C(!0);const z=await O5(p);w(z)}catch(z){console.error("Failed to fetch shared recipients:",z),w([])}finally{C(!1)}})()},[k,p,s,u]);const F=x.useMemo(()=>{if(!b||!ai(b))return null;const L=Q0(b);if(!L)return null;const z=X0(b,I),X=J0(z);return{claimRequest:L,visibility:X}},[b,I]);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(ie,{className:"pb-2",children:e.jsx(le,{className:"text-sm sm:text-base",children:"Quick Actions"})}),e.jsxs(te,{className:"space-y-2",children:[s&&t.status!=="closed"&&e.jsxs(P,{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(ml,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Approver"]}),t.status!=="closed"&&e.jsxs(P,{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(vt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Add Spectator"]}),B&&c&&e.jsxs(P,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-orange-700 border-orange-300 hover:bg-orange-50 hover:text-orange-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:c,"data-testid":"pause-workflow-button",children:[e.jsx(or,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Pause Workflow"]}),T&&e.jsxs(P,{variant:"outline",className:"w-full justify-start gap-2 bg-white text-green-700 border-green-300 hover:bg-green-50 hover:text-green-900 h-9 sm:h-10 text-xs sm:text-sm",onClick:d,"data-testid":"resume-workflow-button",children:[e.jsx(Hi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Resume Workflow"]}),M&&e.jsxs(P,{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(Je,{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(P,{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(Be,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 mr-2"}),"Approve Request"]}),e.jsxs(P,{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:O===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&&e.jsx(Je,{className:"w-3.5 h-3.5"}),E?"Initiator has requested you to resume":"You paused this workflow"]}),e.jsx("p",{className:"text-xs text-orange-600 mt-1",children:E?"Please review and resume if appropriate":'Click "Resume Workflow" to continue'})]}):r&&O!==I&&E?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(Je,{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&&O!==I?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&&O&&O!==I?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:M?'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(ie,{className:"pb-2",children:e.jsx(le,{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((L,z)=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`spectator-${z}`,children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:L.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:L.name}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:L.role})]})]},z)):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No spectators added"})})})]}),k&&s&&e.jsxs(Z,{"data-testid":"shared-recipients-card",children:[e.jsx(ie,{className:"pb-2",children:e.jsxs(le,{className:"text-sm sm:text-base flex items-center gap-2",children:[e.jsx(pn,{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((L,z)=>{const X=(L.displayName||"NA").split(" ").map(W=>W[0]).join("").slice(0,2).toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`shared-recipient-${z}`,children:[e.jsx(cs,{className:"h-8 w-8",children:e.jsx(ds,{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:L.displayName}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:L.email}),L.isRead&&e.jsx("p",{className:"text-xs text-green-600 mt-0.5",children:"Viewed"})]})]},L.userId||z)}):e.jsx("div",{className:"py-4 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Summary not shared yet"})})})]}),F&&e.jsx(B5,{ioDetails:F.claimRequest.ioDetails,dmsDetails:F.claimRequest.dmsDetails,claimAmount:{amount:F.claimRequest.claimAmount.closed||F.claimRequest.claimAmount.estimated||0},estimatedBudgetBreakdown:($=F.claimRequest.proposalDetails)==null?void 0:$.costBreakup,closedExpensesBreakdown:(_=F.claimRequest.activityInfo)==null?void 0:_.closedExpensesBreakdown,visibility:F.visibility,onEditClaimAmount:f})]})}function G5({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Approve Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=x.useState(r),[d,m]=x.useState(!1),p=(o==null?void 0:o.length)||0,u=x.useMemo(()=>o.slice(0,500),[o]),h=async()=>{try{m(!0),await a(u),s()}finally{m(!1)}};return e.jsx(xt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(dt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ht,{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(Be,{className:"w-7 h-7 text-green-600"})}),e.jsxs("div",{children:[e.jsx(mt,{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(ae,{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($s,{value:u,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter your approval comments and any conditions or notes...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(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(Be,{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(Dt,{className:"mt-4",children:[e.jsx(P,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(P,{onClick:h,disabled:d,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),d?"Approving...":"Approve Request"]})]})]})})}function W5({open:t,onClose:s,onConfirm:a,defaultDescription:r="",title:n="Reject Request",requestIdDisplay:i,requestTitle:l}){const[o,c]=x.useState(r),[d,m]=x.useState(!1),p=(o==null?void 0:o.length)||0,u=x.useMemo(()=>o.slice(0,500),[o]),h=async()=>{if(!u.trim()){alert("Comments & remarks are required");return}try{m(!0),await a(u),s()}finally{m(!1)}};return e.jsx(xt,{open:t,onOpenChange:g=>!g&&s(),children:e.jsxs(dt,{className:"sm:max-w-[640px] bg-white",children:[e.jsx(ht,{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(mt,{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(ae,{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($s,{value:u,onChange:g=>c(g.target.value),rows:5,placeholder:"Enter detailed reasons for rejection and any suggestions for improvement...",className:"border-gray-300"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"Comments are required and will be visible to all participants"}),e.jsxs("span",{children:[Math.min(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(Je,{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(Dt,{className:"mt-4",children:[e.jsx(P,{variant:"outline",onClick:s,disabled:d,children:"Cancel"}),e.jsxs(P,{variant:"destructive",onClick:h,disabled:d,children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),d?"Rejecting...":"Reject Request"]})]})]})})}function Y5({open:t,onClose:s,onConfirm:a,approverName:r,levelNumber:n,requestIdDisplay:i,requestTitle:l}){const[o,c]=x.useState(""),[d,m]=x.useState(!1),p=async()=>{if(o.trim())try{m(!0),await a(o.trim()),c(""),s()}catch(h){console.error("Failed to skip approver:",h)}finally{m(!1)}},u=()=>{d||(c(""),s())};return e.jsx(xt,{open:t,onOpenChange:u,children:e.jsxs(dt,{className:"sm:max-w-md max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:u,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:d,children:[e.jsx(jt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(ht,{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(Je,{className:"w-5 h-5 text-orange-600"})}),e.jsx(mt,{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(Je,{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(se,{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(se,{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(se,{htmlFor:"skip-reason",className:"text-sm font-semibold text-gray-700",children:"Reason for Skipping *"}),e.jsx($s,{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:h=>c(h.target.value),className:"min-h-[100px] border-2 border-gray-300 focus:border-orange-500",disabled:d,autoFocus:!0}),e.jsx("p",{className:"text-xs text-gray-500",children:"This reason will be recorded in the activity log and all participants will be notified."})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(P,{type:"button",variant:"outline",onClick:u,className:"flex-1 h-11 border-gray-300",disabled:d,children:"Cancel"}),e.jsxs(P,{type:"button",onClick:p,className:"flex-1 h-11 bg-orange-600 hover:bg-orange-700 text-white",disabled:d||!o.trim(),children:[e.jsx(Je,{className:"w-4 h-4 mr-2"}),d?"Skipping...":"Skip Approver"]})]})]})})}function K5({showApproveModal:t,showRejectModal:s,showAddApproverModal:a,showAddSpectatorModal:r,showSkipApproverModal:n,showActionStatusModal:i,previewDocument:l,documentError:o,request:c,skipApproverData:d,actionStatus:m,existingParticipants:p,currentLevels:u,maxApprovalLevels:h,onPolicyViolation:g,setShowApproveModal:b,setShowRejectModal:f,setShowAddApproverModal:j,setShowAddSpectatorModal:y,setShowSkipApproverModal:v,setShowActionStatusModal:w,setPreviewDocument:S,setDocumentError:C,setSkipApproverData:E,setActionStatus:R,handleApproveConfirm:k,handleRejectConfirm:N,handleAddApprover:O,handleAddSpectator:I,handleSkipApprover:B,downloadDocument:T,documentPolicy:M}){return e.jsxs(e.Fragment,{children:[e.jsx(G5,{open:t,onClose:()=>b(!1),onConfirm:k,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(W5,{open:s,onClose:()=>f(!1),onConfirm:N,requestIdDisplay:c.id,requestTitle:c.title}),e.jsx(G0,{open:a,onClose:()=>j(!1),onConfirm:O,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p,currentLevels:u,maxApprovalLevels:h,onPolicyViolation:g}),e.jsx(H0,{open:r,onClose:()=>y(!1),onConfirm:I,requestIdDisplay:c.id,requestTitle:c.title,existingParticipants:p}),e.jsx(Y5,{open:n,onClose:()=>{v(!1),E(null)},onConfirm:B,approverName:d==null?void 0:d.approverName,levelNumber:d==null?void 0:d.levelNumber,requestIdDisplay:c.id,requestTitle:c.title}),l&&e.jsx(Gr,{fileName:l.fileName,fileType:l.fileType,fileUrl:yn(l.documentId),fileSize:l.fileSize,attachmentId:l.documentId,onDownload:T,open:!!l,onClose:()=>S(null)}),m&&e.jsx(z0,{open:i,onClose:()=>{w(!1),R(null)},success:m.success,title:m.title,message:m.message}),e.jsx(xt,{open:o.show,onOpenChange:F=>C(D=>({...D,show:F})),children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(ht,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Et,{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((F,D)=>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:F.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:F.reason})]},D))}),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: ",M.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types: ",M.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Dt,{children:e.jsx(P,{onClick:()=>C({show:!1,errors:[]}),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const Z0={DocumentsTab:w5,ActivityTab:T5,WorkNotesTab:I5,SummaryTab:P5,RequestDetailHeader:_5,QuickActionsSidebar:H5,RequestDetailModals:K5};function jd({className:t,...s}){return e.jsx(Pb,{"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(Eb,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:e.jsx(Oa,{className:"size-3.5"})})})}function q0({isOpen:t,onClose:s,summaryId:a,requestTitle:r,onSuccess:n}){const[i,l]=x.useState(""),[o,c]=x.useState([]),[d,m]=x.useState(new Set),[p,u]=x.useState(!1),[h,g]=x.useState(!1);x.useEffect(()=>{if(!t){c([]);return}if(!i||!i.startsWith("@")||i.length<2){c([]),u(!1);return}const y=setTimeout(async()=>{var v;try{u(!0);const w=i.slice(1),S=await va(w,10),C=((v=S==null?void 0:S.data)==null?void 0:v.data)||(S==null?void 0:S.data)||[];c(Array.isArray(C)?C:[])}catch(w){console.error("Failed to search users:",w),G.error("Failed to search users")}finally{u(!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(d.size===0){G.error("Please select at least one user to share with");return}try{g(!0),await M5(a,Array.from(d)),G.success(`Summary shared with ${d.size} user(s)`),m(new Set),l(""),c([]),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(""),c([]),s()};return e.jsx(xt,{open:t,onOpenChange:j,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(ht,{children:e.jsx(mt,{children:"Share Summary"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx(se,{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(se,{htmlFor:"user-search",className:"text-sm font-medium text-gray-700",children:"Search Users"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Jt,{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(ze,{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=d.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(jd,{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"}),d.size>0&&e.jsxs("div",{className:"border rounded-lg p-3 bg-blue-50",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-700 mb-2",children:["Selected (",d.size,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(d).map(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(Dt,{children:[e.jsx(P,{variant:"outline",onClick:j,disabled:h,children:"Cancel"}),e.jsx(P,{onClick:f,disabled:h||d.size===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):`Share with ${d.size} user(s)`})]})]})})}function ef({isOpen:t,onClose:s,requestId:a,levelId:r,onSuccess:n}){const[i,l]=x.useState(""),[o,c]=x.useState(""),[d,m]=x.useState(!1),p=()=>rs().add(1,"month").format("YYYY-MM-DD"),u=()=>rs().add(1,"month").format("YYYY-MM-DD"),h=()=>rs().add(1,"day").format("YYYY-MM-DD");x.useEffect(()=>{t&&!o&&c(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=rs(o),j=rs().add(1,"month"),y=rs().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 w1(a,r,i.trim(),f.toDate()),G.success("Workflow paused successfully"),n&&await n(),l(""),c(p()),s()}catch(E){console.error("Failed to pause workflow:",E),G.error(((w=(v=E==null?void 0:E.response)==null?void 0:v.data)==null?void 0:w.error)||((C=(S=E==null?void 0:E.response)==null?void 0:S.data)==null?void 0:C.message)||"Failed to pause workflow")}finally{m(!1)}},b=()=>{d||(l(""),c(p()),s())};return e.jsx(xt,{open:t,onOpenChange:b,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(ht,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(or,{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(se,{htmlFor:"pause-reason",className:"text-sm font-medium",children:["Reason for Pausing ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx($s,{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:d}),e.jsxs("p",{className:"text-xs text-gray-500",children:[i.length," / 1000 characters"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{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=>c(f.target.value),min:h(),max:u(),className:"text-sm",disabled:d}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum 1 month from today. The workflow will automatically resume on this date."})]})]}),e.jsxs(Dt,{children:[e.jsx(P,{variant:"outline",onClick:b,disabled:d,children:"Cancel"}),e.jsx(P,{onClick:g,disabled:d||!i.trim()||!o,className:"bg-orange-600 hover:bg-orange-700 text-white",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Pausing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(or,{className:"w-4 h-4 mr-2"}),"Pause Workflow"]})})]})]})})}function tf({isOpen:t,onClose:s,requestId:a,onSuccess:r}){const[n,i]=x.useState(""),[l,o]=x.useState(!1),c=async()=>{var m,p,u,h;try{o(!0),await C1(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)||((h=(u=g==null?void 0:g.response)==null?void 0:u.data)==null?void 0:h.message)||"Failed to resume workflow")}finally{o(!1)}},d=()=>{l||(i(""),s())};return e.jsx(xt,{open:t,onOpenChange:d,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsx(ht,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Hi,{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(se,{htmlFor:"resume-notes",className:"text-sm font-medium",children:"Notes (Optional)"}),e.jsx($s,{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(Dt,{children:[e.jsx(P,{variant:"outline",onClick:d,disabled:l,children:"Cancel"}),e.jsx(P,{onClick:c,disabled:l,className:"bg-green-600 hover:bg-green-700 text-white",children:l?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Resuming..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Hi,{className:"w-4 h-4 mr-2"}),"Resume Workflow"]})})]})]})})}function sf({isOpen:t,onClose:s,requestId:a,approverName:r,onSuccess:n}){const[i,l]=x.useState(!1),o=async()=>{var c,d,m,p;try{l(!0),await S1(a),G.success("Retrigger request sent to approver"),n&&await n(),s()}catch(u){console.error("Failed to retrigger pause:",u),G.error(((d=(c=u==null?void 0:u.response)==null?void 0:c.data)==null?void 0:d.error)||((p=(m=u==null?void 0:u.response)==null?void 0:m.data)==null?void 0:p.message)||"Failed to send retrigger request")}finally{l(!1)}};return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[450px]",children:[e.jsx(ht,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(Je,{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(Dt,{children:[e.jsx(P,{variant:"outline",onClick:s,disabled:i,children:"Cancel"}),e.jsx(P,{onClick:o,disabled:i,className:"bg-orange-600 hover:bg-orange-700 text-white",children:i?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-4 h-4 mr-2"}),"Send Request"]})})]})]})})}const{DocumentsTab:Q5,ActivityTab:X5,WorkNotesTab:J5,SummaryTab:Z5,RequestDetailHeader:q5,QuickActionsSidebar:ek,RequestDetailModals:tk}=Z0;let sk=class extends x.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("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(ss,{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(P,{onClick:()=>window.location.reload(),className:"mr-2",children:"Reload Page"}),e.jsx(P,{variant:"outline",onClick:()=>window.history.back(),children:"Go Back"})]})}):this.props.children}};function ak({requestId:t,onBack:s,dynamicRequests:a=[]}){var Kr,Xa,fr,Ja,br,jr,Za,Ia,qa;const n=Ba().requestId||t||"",l=new URLSearchParams(window.location.search).get("tab")||"overview",[o,c]=x.useState(l),[d,m]=x.useState(!1),[p,u]=x.useState(null),[h,g]=x.useState(null),[b,f]=x.useState(!1),[j,y]=x.useState(0),[v,w]=x.useState(!1),[S,C]=x.useState(!1),[E,R]=x.useState(!1),[k,N]=x.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[O,I]=x.useState({open:!1,violations:[]}),{user:B}=us(),{request:T,apiRequest:M,loading:F,refreshing:D,refreshDetails:A,currentApprovalLevel:H,isSpectator:$,isInitiator:_,existingParticipants:L,accessDenied:z}=gd(n,a,B),{mergedMessages:X,unreadWorkNotes:W,workNoteAttachments:U,setWorkNoteAttachments:V}=$0(n,M,o,B),{uploadingDocument:Q,triggerFileInput:ee,previewDocument:K,setPreviewDocument:q,documentPolicy:ue,documentError:Le,setDocumentError:Ze}=U0(M,A),{showApproveModal:De,setShowApproveModal:_e,showRejectModal:Ue,setShowRejectModal:re,showAddApproverModal:fe,setShowAddApproverModal:Ce,showAddSpectatorModal:Ae,setShowAddSpectatorModal:ce,showSkipApproverModal:pe,setShowSkipApproverModal:Te,showActionStatusModal:de,setShowActionStatusModal:me,skipApproverData:Ne,setSkipApproverData:Oe,actionStatus:st,setActionStatus:nt,handleApproveConfirm:St,handleRejectConfirm:Mt,handleAddApprover:ne,handleSkipApprover:Ee,handleAddSpectator:oe}=V0(n,H,A),{conclusionRemark:Xe,setConclusionRemark:Ke,conclusionLoading:tt,conclusionSubmitting:Qe,aiGenerated:it,handleGenerateConclusion:qe,handleFinalizeConclusion:ut,generationAttempts:Us,generationFailed:is,maxAttemptsReached:yt}=B0(T,n,_,A,s,nt,me);x.useEffect(()=>{(async()=>{var As;try{const ia=await ma("SYSTEM_SETTINGS"),yr=await ma("WORKFLOW_SHARING"),vr=[...ia,...yr],Ca={};vr.forEach(er=>{Ca[er.configKey]=er.configValue}),N({maxApprovalLevels:parseInt(Ca.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(Ca.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((As=Ca.ALLOW_ADD_SPECTATOR)==null?void 0:As.toLowerCase())==="true",maxSpectators:parseInt(Ca.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(ia){console.error("Failed to load system policy:",ia)}})()},[]),x.useEffect(()=>{const As=new URLSearchParams(window.location.search).get("tab");As&&c(As)},[n]);const pt=()=>{A()},It=()=>{w(!0)},Ss=()=>{C(!0)},as=async()=>{await A()},Va=()=>{R(!0)},za=async()=>{await A()},pr=async()=>{await A()},Na=async()=>{if(!(M!=null&&M.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=((T==null?void 0:T.status)==="approved"||(T==null?void 0:T.status)==="rejected")&&_,wa=(T==null?void 0:T.status)==="closed"||(T==null?void 0:T.status)==="approved"&&!_||(T==null?void 0:T.status)==="rejected"&&!_,Ms=((T==null?void 0:T.templateType)||(T==null?void 0:T.template_type)||"").toString().toUpperCase()==="FORM_16";x.useEffect(()=>{Ms&&o==="worknotes"&&c("overview")},[Ms,o]),x.useEffect(()=>{(async()=>{if(!wa||!(M!=null&&M.requestId)){g(null),u(null);return}try{f(!0);const As=await K0(M.requestId);if(As!=null&&As.summaryId){u(As.summaryId);try{const ia=await bd(As.summaryId);g(ia)}catch(ia){console.error("Failed to fetch summary details:",ia),g(null),u(null)}}else g(null),u(null)}catch{g(null),u(null)}finally{f(!1)}})()},[wa,M==null?void 0:M.requestId]);const Wr=((T==null?void 0:T.approvalFlow)||[]).filter(Kt=>Kt&&typeof Kt.step=="number").map(Kt=>({levelNumber:Kt.step||0,approverName:Kt.approver||"Unknown",status:Kt.status||"pending",tatHours:Kt.tatHours||24}));if(F&&!T&&!M)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(Pt,{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(z!=null&&z.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(Qh,{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:z.message}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsxs(P,{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(P,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})});if(!T)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(Re,{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(P,{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(P,{onClick:()=>window.location.href="/dashboard",className:"bg-blue-600 hover:bg-blue-700",children:"Go to Dashboard"})]})]})});const Yr=(B==null?void 0:B.role)==="MANAGEMENT"||(B==null?void 0:B.role)==="ADMIN",gr=((Kr=at.getUserData())==null?void 0:Kr.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(q5,{request:T,refreshing:D,onBack:s||(()=>window.history.back()),onRefresh:pt,onShareSummary:Na,isInitiator:_,slaData:((Xa=T==null?void 0:T.summary)==null?void 0:Xa.sla)||(T==null?void 0:T.sla)||null,isPaused:((fr=T==null?void 0:T.pauseInfo)==null?void 0:fr.isPaused)||!1}),e.jsxs(gi,{value:o,onValueChange:c,className:"w-full","data-testid":"custom-request-detail-tabs",children:[e.jsx("div",{className:"mb-4 sm:mb-6",children:e.jsxs(fi,{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(Xh,{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"})]}),wa&&h&&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(gc,{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(Hs,{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(Re,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Docs"})]}),e.jsxs($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(zs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:"Work Notes"}),W>0&&e.jsx(ae,{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-red-500 text-white text-[10px] flex items-center justify-center p-0","data-testid":"worknotes-unread-badge",children:W>9?"9+":W})]})]})}),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(V1,{request:T}):e.jsx(_1,{request:T,isInitiator:_,needsClosure:Lt,conclusionRemark:Xe,setConclusionRemark:Ke,conclusionLoading:tt,conclusionSubmitting:Qe,aiGenerated:it,handleGenerateConclusion:qe,handleFinalizeConclusion:ut,onPause:It,onResume:Ss,onRetrigger:Va,currentUserIsApprover:!!H,pausedByUserId:(br=(Ja=T==null?void 0:T.pauseInfo)==null?void 0:Ja.pausedBy)==null?void 0:br.userId,currentUserId:B==null?void 0:B.userId,generationAttempts:Us,generationFailed:is,maxAttemptsReached:yt})}),wa&&e.jsx(Ut,{value:"summary",className:"mt-0","data-testid":"summary-tab-content",children:e.jsx(Z5,{summary:h,loading:b,onShare:Na,isInitiator:_})}),e.jsx(Ut,{value:"workflow",className:"mt-0",children:Ms?e.jsx(H1,{request:T,requestId:(M==null?void 0:M.requestId)||n,isReUser:Yr,onRefresh:A}):e.jsx($1,{request:T,user:B,isInitiator:_,onSkipApprover:Kt=>{if(!Kt.levelId){alert("Level ID not available");return}Oe(Kt),Te(!0)},onRefresh:A})}),e.jsx(Ut,{value:"documents",className:"mt-0",children:e.jsx(Q5,{request:T,workNoteAttachments:U,uploadingDocument:Q,documentPolicy:ue,triggerFileInput:ee,setPreviewDocument:q,downloadDocument:_s,isSpectator:$})}),e.jsx(Ut,{value:"activity",className:"mt-0",children:e.jsx(X5,{request:T})}),!Ms&&e.jsx(Ut,{value:"worknotes",className:"mt-0",forceMount:!0,hidden:o!=="worknotes",children:e.jsx(J5,{requestId:n,requestTitle:T.title,mergedMessages:X,setWorkNoteAttachments:V,isInitiator:_,isSpectator:$,currentLevels:Wr,onAddApprover:ne,maxApprovalLevels:k.maxApprovalLevels,onPolicyViolation:Kt=>I({open:!0,violations:Kt})})})]}),!gr&&o!=="worknotes"&&e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[Ms&&Yr&&e.jsx(v5,{requestId:(M==null?void 0:M.requestId)||n,request:T,onRefresh:A}),e.jsx(ek,{request:T,isInitiator:_,isSpectator:$,currentApprovalLevel:H,onAddApprover:()=>Ce(!0),onAddSpectator:()=>ce(!0),onApprove:()=>_e(!0),onReject:()=>re(!0),onPause:It,onResume:Ss,onRetrigger:Va,summaryId:p,refreshTrigger:j,pausedByUserId:(Za=(jr=T==null?void 0:T.pauseInfo)==null?void 0:jr.pausedBy)==null?void 0:Za.userId,currentUserId:B==null?void 0:B.userId,apiRequest:M,hideApproveReject:gr})]})]})]})]})}),d&&p&&e.jsx(q0,{isOpen:d,onClose:()=>m(!1),summaryId:p,requestTitle:(T==null?void 0:T.title)||"N/A",onSuccess:()=>{A(),y(Kt=>Kt+1)}}),v&&(M==null?void 0:M.requestId)&&e.jsx(ef,{isOpen:v,onClose:()=>w(!1),requestId:M.requestId,levelId:(H==null?void 0:H.levelId)||null,onSuccess:za}),S&&(M==null?void 0:M.requestId)&&e.jsx(tf,{isOpen:S,onClose:()=>C(!1),requestId:M.requestId,onSuccess:as}),E&&(M==null?void 0:M.requestId)&&e.jsx(sf,{isOpen:E,onClose:()=>R(!1),requestId:M.requestId,approverName:(qa=(Ia=T==null?void 0:T.pauseInfo)==null?void 0:Ia.pausedBy)==null?void 0:qa.name,onSuccess:pr}),e.jsx(tk,{showApproveModal:De,showRejectModal:Ue,showAddApproverModal:fe,showAddSpectatorModal:Ae,showSkipApproverModal:pe,showActionStatusModal:de,previewDocument:K,documentError:Le,request:T,skipApproverData:Ne,actionStatus:st,existingParticipants:L,currentLevels:Wr,maxApprovalLevels:k.maxApprovalLevels,onPolicyViolation:Kt=>I({open:!0,violations:Kt}),setShowApproveModal:_e,setShowRejectModal:re,setShowAddApproverModal:Ce,setShowAddSpectatorModal:ce,setShowSkipApproverModal:Te,setShowActionStatusModal:me,setPreviewDocument:q,setDocumentError:Ze,setSkipApproverData:Oe,setActionStatus:nt,handleApproveConfirm:St,handleRejectConfirm:Mt,handleAddApprover:ne,handleAddSpectator:oe,handleSkipApprover:Ee,downloadDocument:_s,documentPolicy:ue}),e.jsx(pi,{open:O.open,onClose:()=>I({open:!1,violations:[]}),violations:O.violations,policyDetails:{maxApprovalLevels:k.maxApprovalLevels,maxParticipants:k.maxParticipants,allowSpectators:k.allowSpectators,maxSpectators:k.maxSpectators}})]})}function rk(t){return e.jsx(sk,{children:e.jsx(ak,{...t})})}const nk=[{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 ik(){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 lk({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,form16FinancialYear:n="",form16Quarter:i="",sortBy:l,sortOrder:o,onSearchChange:c,onStatusFilterChange:d,onPriorityFilterChange:m,onTemplateTypeFilterChange:p,onForm16FinancialYearChange:u,onForm16QuarterChange:h,onSortByChange:g,onSortOrderChange:b,onClearFilters:f,activeFiltersCount:j}){const y=ik(),v=r==="FORM_16";return e.jsxs(Z,{className:"shadow-lg border-0",children:[e.jsx(ie,{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($a,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(le,{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(P,{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(Jt,{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 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 transition-colors"})]}),e.jsxs(He,{value:a,onValueChange:m,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"All Priorities"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Priorities"}),e.jsx(J,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fa,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(J,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(He,{value:s,onValueChange:d,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"All Statuses"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Statuses"}),e.jsx(J,{value:"pending",children:"Pending (In Approval)"}),e.jsx(J,{value:"approved",children:"Approved (Needs Closure)"})]})]}),e.jsxs(He,{value:r,onValueChange:p,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Request type"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(J,{value:"FORM_16",children:"Form 16"})]})]}),v&&u&&e.jsxs(He,{value:n||void 0,onValueChange:u,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Financial Year"})}),e.jsx(Ye,{children:y.map(w=>e.jsx(J,{value:w,children:w},w))})]}),v&&h&&e.jsxs(He,{value:i||void 0,onValueChange:h,children:[e.jsx(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Quarter"})}),e.jsx(Ye,{children:nk.map(w=>e.jsx(J,{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(We,{className:"h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white focus:border-blue-400 focus:ring-1 focus:ring-blue-200",children:e.jsx(Ge,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"due",children:"Due Date"}),e.jsx(J,{value:"created",children:"Date Created"}),e.jsx(J,{value:"priority",children:"Priority"}),e.jsx(J,{value:"sla",children:"SLA Progress"})]})]}),e.jsx(P,{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(hl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(pl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}const ok=[{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 ck(){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 dk({searchTerm:t,priorityFilter:s,statusFilter:a,templateTypeFilter:r,form16FinancialYear:n="",form16Quarter:i="",sortBy:l,sortOrder:o,activeFiltersCount:c,onSearchChange:d,onPriorityChange:m,onStatusChange:p,onTemplateTypeChange:u,onForm16FinancialYearChange:h,onForm16QuarterChange:g,onSortByChange:b,onSortOrderChange:f,onClearFilters:j}){const y=ck(),v=r==="FORM_16";return e.jsxs(Z,{className:"shadow-lg border-0","data-testid":"closed-requests-filters",children:[e.jsx(ie,{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($a,{className:"h-4 w-4 sm:h-5 sm:w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(le,{className:"text-base sm:text-lg",children:"Filters & Search"}),e.jsx(ye,{className:"text-xs sm:text-sm",children:c>0&&e.jsxs("span",{className:"text-blue-600 font-medium",children:[c," filter",c>1?"s":""," active"]})})]})]}),c>0&&e.jsxs(P,{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(Jt,{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 transition-colors","data-testid":"closed-requests-search"})]}),e.jsxs(He,{value:s,onValueChange:m,children:[e.jsx(We,{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(Ge,{placeholder:"All Priorities"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Priorities"}),e.jsx(J,{value:"express",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fa,{className:"w-4 h-4 text-orange-600"}),e.jsx("span",{children:"Express"})]})}),e.jsx(J,{value:"standard",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{children:"Standard"})]})})]})]}),e.jsxs(He,{value:a,onValueChange:p,children:[e.jsx(We,{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(Ge,{placeholder:"Closure Type"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Closures"}),e.jsx(J,{value:"approved",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{children:"Closed After Approval"})]})}),e.jsx(J,{value:"rejected",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{className:"w-4 h-4 text-red-600"}),e.jsx("span",{children:"Closed After Rejection"})]})})]})]}),e.jsxs(He,{value:r,onValueChange:u,children:[e.jsx(We,{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(Ge,{placeholder:"Request type"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Non-Templatized"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"}),e.jsx(J,{value:"FORM_16",children:"Form 16"})]})]}),v&&h&&e.jsxs(He,{value:n||void 0,onValueChange:h,children:[e.jsx(We,{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(Ge,{placeholder:"Financial Year"})}),e.jsx(Ye,{children:y.map(w=>e.jsx(J,{value:w,children:w},w))})]}),v&&g&&e.jsxs(He,{value:i||void 0,onValueChange:g,children:[e.jsx(We,{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(Ge,{placeholder:"Quarter"})}),e.jsx(Ye,{children:ok.map(w=>e.jsx(J,{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(We,{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(Ge,{placeholder:"Sort by"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"due",children:"Due Date"}),e.jsx(J,{value:"created",children:"Date Created"}),e.jsx(J,{value:"priority",children:"Priority"})]})]}),e.jsx(P,{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(hl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}):e.jsx(pl,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]})})]})}function mk({searchTerm:t,statusFilter:s,priorityFilter:a,templateTypeFilter:r,departmentFilter:n,slaComplianceFilter:i,initiatorFilter:l,approverFilter:o,approverFilterType:c,dateRange:d,customStartDate:m,customEndDate:p,showCustomDatePicker:u,departments:h,loadingDepartments:g,initiatorSearch:b,approverSearch:f,showForm16Filter:j=!1,form16FinancialYear:y="all",form16Quarter:v="all",onForm16FinancialYearChange:w,onForm16QuarterChange:S,onSearchChange:C,onStatusChange:E,onPriorityChange:R,onTemplateTypeChange:k,onDepartmentChange:N,onSlaComplianceChange:O,onInitiatorChange:I,onApproverChange:B,onApproverTypeChange:T,onDateRangeChange:M,onCustomStartDateChange:F,onCustomEndDateChange:D,onShowCustomDatePickerChange:A,onApplyCustomDate:H,onClearFilters:$,hasActiveFilters:_}){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($a,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-gray-900",children:"Advanced Filters"}),_&&e.jsx(ae,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200",children:"Active"})]}),_&&e.jsxs(P,{variant:"ghost",size:"sm",onClick:$,className:"gap-2",children:[e.jsx(Pt,{className:"w-4 h-4"}),"Clear All"]})]}),e.jsx(Zt,{}),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(Jt,{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:L=>C(L.target.value),className:"pl-10 h-10","data-testid":"search-input"})]}),e.jsxs(He,{value:s,onValueChange:E,children:[e.jsx(We,{className:"h-10","data-testid":"status-filter",children:e.jsx(Ge,{placeholder:"All Status"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Status"}),e.jsx(J,{value:"pending",children:"Pending"}),e.jsx(J,{value:"paused",children:"Paused"}),e.jsx(J,{value:"approved",children:"Approved"}),e.jsx(J,{value:"rejected",children:"Rejected"}),e.jsx(J,{value:"closed",children:"Closed"})]})]}),e.jsxs(He,{value:a,onValueChange:R,children:[e.jsx(We,{className:"h-10","data-testid":"priority-filter",children:e.jsx(Ge,{placeholder:"All Priority"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Priority"}),e.jsx(J,{value:"express",children:"Express"}),e.jsx(J,{value:"standard",children:"Standard"})]})]}),e.jsxs(He,{value:r,onValueChange:k,children:[e.jsx(We,{className:"h-10","data-testid":"template-type-filter",children:e.jsx(Ge,{placeholder:"All Templates"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Templates"}),e.jsx(J,{value:"CUSTOM",children:"Custom"}),e.jsx(J,{value:"DEALER CLAIM",children:"Dealer Claim"}),j&&e.jsx(J,{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(We,{className:"h-10","data-testid":"form16-financial-year-filter",children:e.jsx(Ge,{placeholder:"Financial Year"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Years"}),e.jsx(J,{value:"2024-25",children:"2024-25"}),e.jsx(J,{value:"2023-24",children:"2023-24"}),e.jsx(J,{value:"2022-23",children:"2022-23"})]})]}),e.jsxs(He,{value:v,onValueChange:S??(()=>{}),children:[e.jsx(We,{className:"h-10","data-testid":"form16-quarter-filter",children:e.jsx(Ge,{placeholder:"Quarter"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Quarters"}),e.jsx(J,{value:"Q1",children:"Q1"}),e.jsx(J,{value:"Q2",children:"Q2"}),e.jsx(J,{value:"Q3",children:"Q3"}),e.jsx(J,{value:"Q4",children:"Q4"})]})]})]}),e.jsxs(He,{value:n,onValueChange:N,disabled:g||h.length===0,children:[e.jsx(We,{className:"h-10","data-testid":"department-filter",children:e.jsx(Ge,{placeholder:g?"Loading...":"All Departments"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Departments"}),h.map(L=>e.jsx(J,{value:L,children:L},L))]})]}),e.jsxs(He,{value:i,onValueChange:O,children:[e.jsx(We,{className:"h-10","data-testid":"sla-compliance-filter",children:e.jsx(Ge,{placeholder:"All SLA Status"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All SLA Status"}),e.jsx(J,{value:"compliant",children:"Compliant"}),e.jsx(J,{value:"on-track",children:"On Track"}),e.jsx(J,{value:"approaching",children:"Approaching"}),e.jsx(J,{value:"critical",children:"Critical"}),e.jsx(J,{value:"breached",children:"Breached"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx(se,{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(P,{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:L=>b.handleSearch(L.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(L=>e.jsx("button",{type:"button",onClick:()=>b.handleSelect(L),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:L.displayName||L.email}),L.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:L.email})]})},L.userId))})]})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{className:"text-sm font-medium text-gray-700",children:"Approver"}),o!=="all"&&T&&e.jsxs(He,{value:c,onValueChange:L=>T(L),children:[e.jsx(We,{className:"h-7 w-32 text-xs",children:e.jsx(Ge,{})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"current",children:"Current Only"}),e.jsx(J,{value:"any",children:"Any Approver"})]})]})]}),e.jsx("div",{className:"relative",children: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(P,{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:L=>f.handleSearch(L.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(L=>e.jsx("button",{type:"button",onClick:()=>f.handleSelect(L),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:L.displayName||L.email}),L.displayName&&e.jsx("span",{className:"text-xs text-gray-500",children:L.email})]})},L.userId))})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(gt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(He,{value:d,onValueChange:L=>M(L),children:[e.jsx(We,{className:"w-[160px] h-10",children:e.jsx(Ge,{placeholder:"Date Range"})}),e.jsxs(Ye,{children:[e.jsx(J,{value:"all",children:"All Time"}),e.jsx(J,{value:"today",children:"Today"}),e.jsx(J,{value:"week",children:"This Week"}),e.jsx(J,{value:"month",children:"This Month"}),e.jsx(J,{value:"last7days",children:"Last 7 Days"}),e.jsx(J,{value:"last30days",children:"Last 30 Days"}),e.jsx(J,{value:"custom",children:"Custom Range"})]})]}),d==="custom"&&e.jsxs(sa,{open:u,onOpenChange:A,children:[e.jsx(aa,{asChild:!0,children:e.jsxs(P,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(gt,{className:"w-4 h-4"}),m&&p?`${et(m,"MMM d, yyyy")} - ${et(p,"MMM d, yyyy")}`:"Select dates"]})}),e.jsx(ra,{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(se,{htmlFor:"start-date",children:"Start Date"}),e.jsx(ea,{value:m||null,onChange:L=>{const z=L?new Date(L):void 0;z?(F==null||F(z),p&&z>p&&(D==null||D(z))):F==null||F(void 0)},maxDate:new Date,placeholderText:"dd/mm/yyyy",className:"w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"end-date",children:"End Date"}),e.jsx(ea,{value:p||null,onChange:L=>{const z=L?new Date(L):void 0;z?(D==null||D(z),m&&z{A==null||A(!1),F==null||F(void 0),D==null||D(void 0),M("month")},children:"Cancel"})]})]})})]})]})]})})})}function uk({request:t,apiRequest:s,currentUserId:a,isInitiator:r,onEditClaimAmount:n,className:i="",needsClosure:l=!1,conclusionRemark:o="",setConclusionRemark:c,conclusionLoading:d=!1,conclusionSubmitting:m=!1,aiGenerated:p=!1,handleGenerateConclusion:u,handleFinalizeConclusion:h,generationAttempts:g=0,generationFailed:b=!1,maxAttemptsReached:f=!1}){var S,C,E,R,k,N,O,I,B;if(!ai(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=Q0(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=X0(s,a),v=J0(y),w={name:((S=s.initiator)==null?void 0:S.name)||((C=s.initiator)==null?void 0:C.displayName)||((E=s.initiator)==null?void 0:E.email)||"Unknown",role:((R=s.initiator)==null?void 0:R.role)||((k=s.initiator)==null?void 0:k.designation)||"Initiator",department:((N=s.initiator)==null?void 0:N.department)||s.department||"",email:((O=s.initiator)==null?void 0:O.email)||"N/A",phone:((I=s.initiator)==null?void 0:I.phone)||((B=s.initiator)==null?void 0:B.mobile)};return e.jsxs("div",{className:`space-y-6 ${i}`,children:[e.jsx($5,{activityInfo:j.activityInfo,createdAt:s==null?void 0:s.createdAt,updatedAt:s==null?void 0:s.updatedAt}),e.jsx(U5,{dealerInfo:j.dealerInfo}),v.showProposalDetails&&j.proposalDetails&&e.jsx(V5,{proposalDetails:j.proposalDetails}),e.jsx(z5,{initiatorInfo:w}),(s==null?void 0:s.status)==="closed"&&(s==null?void 0:s.conclusionRemark)&&e.jsxs(Z,{children:[e.jsxs(ie,{children:[e.jsxs(le,{className:"flex items-center gap-2 text-base",children:[e.jsx(Be,{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(Ps,{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 ",bs(s.closureDate)]}),e.jsxs("span",{children:["By ",w.name]})]})]})]}),l&&e.jsxs(Z,{"data-testid":"conclusion-remark-card",children:[e.jsx(ie,{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(le,{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(Be,{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."})]}),u&&e.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[e.jsxs(P,{variant:"outline",size:"sm",onClick:u,disabled:d||f,className:"gap-2 shrink-0 h-9","data-testid":"generate-ai-conclusion-button",children:[e.jsx(Pt,{className:`w-3.5 h-3.5 ${d?"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:d?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(ze,{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)"})]}),c&&e.jsx(di,{value:o,onChange:T=>c(T),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"})]})]}),h&&e.jsx("div",{className:"flex gap-3 justify-end pt-3 border-t",children:e.jsx(P,{onClick:h,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(ze,{className:"w-4 h-4 mr-2 animate-spin"}),"Finalizing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),"Finalize & Close Request"]})})})]})})]})]})}function xk({isOpen:t,onClose:s,onApprove:a,onReject:r,requestTitle:n="Request",requestDescription:i="",requestId:l,levelName:o="Approval Level",approverName:c="Approver"}){const[d,m]=x.useState(""),[p,u]=x.useState(!1),[h,g]=x.useState(null),b=async()=>{if(!d.trim()){G.error("Please provide approval comments");return}try{u(!0),g("approve"),await a(d),j(),s()}catch(v){console.error("Failed to approve request:",v),G.error("Failed to approve request. Please try again.")}finally{u(!1),g(null)}},f=async()=>{if(!d.trim()){G.error("Please provide rejection reason");return}try{u(!0),g("reject"),await r(d),j(),s()}catch(v){console.error("Failed to reject request:",v),G.error("Failed to reject request. Please try again.")}finally{u(!1),g(null)}},j=()=>{m(""),g(null)},y=()=>{p||(j(),s())};return t?e.jsx(xt,{open:t,onOpenChange:y,children:e.jsxs(dt,{className:"dealer-proposal-modal overflow-hidden flex flex-col max-w-3xl",children:[e.jsxs(ht,{className:"flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b",children:[e.jsxs(mt,{className:"flex items-center gap-2 text-lg lg:text-xl",children:[e.jsx(Be,{className:"w-4 h-4 lg:w-5 lg:h-5 text-blue-600"}),"Review Request"]}),e.jsxs(Et,{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:"})," ",c]})]})})]}),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(Re,{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(zs,{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(Ps,{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($s,{placeholder:"Provide your evaluation comments, approval conditions, or rejection reasons...",value:d,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:[d.length," characters"]})]}),!d.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(Dt,{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(P,{variant:"outline",onClick:y,disabled:p,className:"border-2",children:"Cancel"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(P,{onClick:f,disabled:!d.trim()||p,variant:"destructive",className:"bg-red-600 hover:bg-red-700",children:p&&h==="reject"?"Rejecting...":e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"w-4 h-4 mr-2"}),"Reject"]})}),e.jsx(P,{onClick:b,disabled:!d.trim()||p,className:"bg-green-600 hover:bg-green-700 text-white",children:p&&h==="approve"?"Approving...":e.jsxs(e.Fragment,{children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),"Approve"]})})]})]})]})}):null}function hk({isOpen:t,onClose:s,onDownload:a,onSendToDealer:r,creditNoteData:n,dealerInfo:i,activityName:l,requestNumber:o,requestId:c,dueDate:d,taxationType:m}){const[p,u]=x.useState(!1),[h,g]=x.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?bs(n.creditNoteDate,{includeTime:!1,format:"short"}):"",v=(n==null?void 0:n.creditNoteAmount)||0,w=(n==null?void 0:n.transactionNo)||"",S=(n==null?void 0:n.tdsAmount)||0,C=(n==null?void 0:n.creditAmount)||0,E=(n==null?void 0:n.status)||"PENDING",R=(n==null?void 0:n.items)||[],k=(i==null?void 0:i.dealerName)||"Jaipur Royal Enfield",N=(i==null?void 0:i.dealerCode)||"RE-JP-009",O=l||"Activity",I=o||"RE-REQ-2024-CM-101",B=d?bs(d,{includeTime:!1,format:"short"}):"Jan 4, 2026",T=(()=>{var A,H;if(R.length>1){const $=(A=R[0])==null?void 0:A.transactionNo,_=(H=R[R.length-1])==null?void 0:H.transactionNo;return $&&_&&$!==_?`${$} - ${_}`:$||w||"N/A"}return w||"N/A"})(),M=async()=>{if(a)try{u(!0),await a(),G.success("Credit note downloaded successfully")}catch(A){console.error("Failed to download credit note:",A),G.error("Failed to download credit note. Please try again.")}finally{u(!1)}else G.info("Credit note will be automatically saved to Documents tab")},F=async()=>{if(r)try{g(!0),await r(),G.success("Credit note sent to dealer successfully"),s()}catch(A){console.error("Failed to send credit note to dealer:",A),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")},D=A=>`₹${A.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:0})}`;return e.jsx(xt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ht,{children:[e.jsxs(mt,{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(_t,{className:"w-6 h-6 text-[--re-green]"}),"Credit Note Details"]}),m&&e.jsx(ae,{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(Et,{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(ae,{className:"bg-green-600 text-white px-4 py-2 text-base",children:[e.jsx(Be,{className:"w-4 h-4 mr-2"}),E==="APPROVED"?"Approved":E==="ISSUED"?"Issued":E==="SENT"?"Sent":"Confirmed"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4 mt-4",children:[e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100 shadow-sm",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Fo,{className:"w-3 h-3"}),"Credit Note No"]}),e.jsx("p",{className:"font-bold text-gray-900 mt-1",children:j})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-green-100 shadow-sm",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(gt,{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-white rounded-lg p-3 border border-green-100 shadow-sm col-span-2 md:col-span-1",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-500 uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Re,{className:"w-3 h-3"}),"Transaction ID"]}),e.jsx("p",{className:"font-bold text-emerald-700 mt-1 break-all",children:T})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-4",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(ka,{className:"w-3 h-3"}),"Gross Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-blue-700",children:D(v)})]}),e.jsxs("div",{className:"bg-orange-50 border-2 border-orange-200 rounded-lg p-4",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(ka,{className:"w-3 h-3"}),"TDS Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-orange-700",children:D(S)})]}),e.jsxs("div",{className:"bg-emerald-50 border-2 border-emerald-200 rounded-lg p-4",children:[e.jsxs(se,{className:"font-medium text-[10px] text-gray-600 uppercase tracking-wider flex items-center gap-1 mb-2",children:[e.jsx(ka,{className:"w-3 h-3"}),"Net Credit Amount"]}),e.jsx("p",{className:"text-2xl font-bold text-emerald-700",children:D(C)})]})]}),R&&R.length>0&&e.jsxs("div",{className:"border border-slate-200 rounded-lg overflow-hidden mt-2",children:[e.jsxs("div",{className:"bg-slate-50 px-4 py-2 border-b border-slate-200 flex items-center justify-between",children:[e.jsxs("h4",{className:"font-semibold text-slate-900 text-sm flex items-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4 text-slate-500"}),"Line Item Breakdown"]}),e.jsxs(ae,{variant:"outline",className:"text-[10px] font-medium uppercase tracking-wider",children:[R.length," ",R.length===1?"Item":"Items"]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto",children:e.jsxs("table",{className:"w-full text-sm text-left border-collapse",children:[e.jsx("thead",{className:"bg-white sticky top-0 shadow-sm z-10",children:e.jsxs("tr",{className:"border-b border-slate-200",children:[e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap",children:"Sl No"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap",children:"Transaction Code"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap",children:"HSN/SAC"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap text-right",children:"Claim Amount"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap text-right",children:"TDS"}),e.jsx("th",{className:"px-4 py-2.5 font-semibold text-slate-700 text-[11px] uppercase whitespace-nowrap text-right",children:"Net Credit"})]})}),e.jsx("tbody",{children:R.map((A,H)=>e.jsxs("tr",{className:"border-b border-slate-100 hover:bg-slate-50/50 transition-colors",children:[e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:A.slNo}),e.jsx("td",{className:"px-4 py-2.5 font-medium text-slate-900 font-mono text-[11px]",children:A.transactionNo||"N/A"}),e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:A.hsnCd||"N/A"}),e.jsx("td",{className:"px-4 py-2.5 text-right font-medium text-slate-700",children:D(A.claimAmount||0)}),e.jsx("td",{className:"px-4 py-2.5 text-right text-orange-600 font-medium",children:D(A.tdsAmount||0)}),e.jsx("td",{className:"px-4 py-2.5 text-right text-emerald-700 font-bold",children:D(A.creditAmount||0)})]},H))})]})})]})]}):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(_t,{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(xl,{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(se,{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:k})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(se,{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:N})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 border border-purple-100",children:[e.jsx(se,{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:O})]})]})]}),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(Re,{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(se,{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:I})]}),e.jsxs("div",{children:[e.jsx(se,{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:B})]})]})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(Re,{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(Dt,{className:"flex-col-reverse gap-2 sm:flex-row flex items-center justify-between sm:justify-between",children:[e.jsx(P,{variant:"outline",onClick:s,disabled:p||h,className:"border-2",children:"Close"}),e.jsx("div",{className:"flex gap-2",children:f&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{variant:"outline",onClick:M,disabled:p||h,className:"border-blue-600 text-blue-600 hover:bg-blue-50",children:[e.jsx(Tt,{className:"w-4 h-4 mr-2"}),p?"Downloading...":"Download"]}),e.jsxs(P,{onClick:F,disabled:p||h,className:"bg-green-600 hover:bg-green-700 text-white shadow-md",children:[e.jsx(Yh,{className:"w-4 h-4 mr-2"}),h?"Sending...":"Send to Dealer"]})]})})]})]})})}var nh=1,pk=.9,gk=.8,fk=.17,mo=.1,uo=.999,bk=.9999,jk=.99,yk=/[\\\/_+.#"@\[\(\{&]/,vk=/[\\\/_+.#"@\[\(\{&]/g,Nk=/[\s-]/,af=/[\s-]/g;function ac(t,s,a,r,n,i,l){if(i===s.length)return n===t.length?nh:jk;var o=`${n},${i}`;if(l[o]!==void 0)return l[o];for(var c=r.charAt(i),d=a.indexOf(c,n),m=0,p,u,h,g;d>=0;)p=ac(t,s,a,r,d+1,i+1,l),p>m&&(d===n?p*=nh:yk.test(t.charAt(d-1))?(p*=gk,h=t.slice(n,d-1).match(vk),h&&n>0&&(p*=Math.pow(uo,h.length))):Nk.test(t.charAt(d-1))?(p*=pk,g=t.slice(n,d-1).match(af),g&&n>0&&(p*=Math.pow(uo,g.length))):(p*=fk,n>0&&(p*=Math.pow(uo,d-n))),t.charAt(d)!==s.charAt(i)&&(p*=bk)),(pp&&(p=u*mo)),p>m&&(m=p),d=a.indexOf(c,d+1);return l[o]=m,m}function ih(t){return t.toLowerCase().replace(af," ")}function wk(t,s,a){return t=a&&a.length>0?`${t+" "+a.join(" ")}`:t,ac(t,s,ih(t),ih(s),0,0,{})}var Pn='[cmdk-group=""]',xo='[cmdk-group-items=""]',Ck='[cmdk-group-heading=""]',rf='[cmdk-item=""]',lh=`${rf}:not([aria-disabled="true"])`,rc="cmdk-item-select",Zr="data-value",Sk=(t,s,a)=>wk(t,s,a),nf=x.createContext(void 0),bi=()=>x.useContext(nf),lf=x.createContext(void 0),yd=()=>x.useContext(lf),of=x.createContext(void 0),cf=x.forwardRef((t,s)=>{let a=qr(()=>{var L,z;return{search:"",value:(z=(L=t.value)!=null?L:t.defaultValue)!=null?z:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=qr(()=>new Set),n=qr(()=>new Map),i=qr(()=>new Map),l=qr(()=>new Set),o=df(t),{label:c,children:d,value:m,onValueChange:p,filter:u,shouldFilter:h,loop:g,disablePointerSelection:b=!1,vimBindings:f=!0,...j}=t,y=ln(),v=ln(),w=ln(),S=x.useRef(null),C=Mk();Ur(()=>{if(m!==void 0){let L=m.trim();a.current.value=L,E.emit()}},[m]),Ur(()=>{C(6,B)},[]);let E=x.useMemo(()=>({subscribe:L=>(l.current.add(L),()=>l.current.delete(L)),snapshot:()=>a.current,setState:(L,z,X)=>{var W,U,V,Q;if(!Object.is(a.current[L],z)){if(a.current[L]=z,L==="search")I(),N(),C(1,O);else if(L==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let ee=document.getElementById(w);ee?ee.focus():(W=document.getElementById(y))==null||W.focus()}if(C(7,()=>{var ee;a.current.selectedItemId=(ee=T())==null?void 0:ee.id,E.emit()}),X||C(5,B),((U=o.current)==null?void 0:U.value)!==void 0){let ee=z??"";(Q=(V=o.current).onValueChange)==null||Q.call(V,ee);return}}E.emit()}},emit:()=>{l.current.forEach(L=>L())}}),[]),R=x.useMemo(()=>({value:(L,z,X)=>{var W;z!==((W=i.current.get(L))==null?void 0:W.value)&&(i.current.set(L,{value:z,keywords:X}),a.current.filtered.items.set(L,k(z,X)),C(2,()=>{N(),E.emit()}))},item:(L,z)=>(r.current.add(L),z&&(n.current.has(z)?n.current.get(z).add(L):n.current.set(z,new Set([L]))),C(3,()=>{I(),N(),a.current.value||O(),E.emit()}),()=>{i.current.delete(L),r.current.delete(L),a.current.filtered.items.delete(L);let X=T();C(4,()=>{I(),(X==null?void 0:X.getAttribute("id"))===L&&O(),E.emit()})}),group:L=>(n.current.has(L)||n.current.set(L,new Set),()=>{i.current.delete(L),n.current.delete(L)}),filter:()=>o.current.shouldFilter,label:c||t["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:y,inputId:w,labelId:v,listInnerRef:S}),[]);function k(L,z){var X,W;let U=(W=(X=o.current)==null?void 0:X.filter)!=null?W:Sk;return L?U(L,a.current.search,z):0}function N(){if(!a.current.search||o.current.shouldFilter===!1)return;let L=a.current.filtered.items,z=[];a.current.filtered.groups.forEach(W=>{let U=n.current.get(W),V=0;U.forEach(Q=>{let ee=L.get(Q);V=Math.max(ee,V)}),z.push([W,V])});let X=S.current;M().sort((W,U)=>{var V,Q;let ee=W.getAttribute("id"),K=U.getAttribute("id");return((V=L.get(K))!=null?V:0)-((Q=L.get(ee))!=null?Q:0)}).forEach(W=>{let U=W.closest(xo);U?U.appendChild(W.parentElement===U?W:W.closest(`${xo} > *`)):X.appendChild(W.parentElement===X?W:W.closest(`${xo} > *`))}),z.sort((W,U)=>U[1]-W[1]).forEach(W=>{var U;let V=(U=S.current)==null?void 0:U.querySelector(`${Pn}[${Zr}="${encodeURIComponent(W[0])}"]`);V==null||V.parentElement.appendChild(V)})}function O(){let L=M().find(X=>X.getAttribute("aria-disabled")!=="true"),z=L==null?void 0:L.getAttribute(Zr);E.setState("value",z||void 0)}function I(){var L,z,X,W;if(!a.current.search||o.current.shouldFilter===!1){a.current.filtered.count=r.current.size;return}a.current.filtered.groups=new Set;let U=0;for(let V of r.current){let Q=(z=(L=i.current.get(V))==null?void 0:L.value)!=null?z:"",ee=(W=(X=i.current.get(V))==null?void 0:X.keywords)!=null?W:[],K=k(Q,ee);a.current.filtered.items.set(V,K),K>0&&U++}for(let[V,Q]of n.current)for(let ee of Q)if(a.current.filtered.items.get(ee)>0){a.current.filtered.groups.add(V);break}a.current.filtered.count=U}function B(){var L,z,X;let W=T();W&&(((L=W.parentElement)==null?void 0:L.firstChild)===W&&((X=(z=W.closest(Pn))==null?void 0:z.querySelector(Ck))==null||X.scrollIntoView({block:"nearest"})),W.scrollIntoView({block:"nearest"}))}function T(){var L;return(L=S.current)==null?void 0:L.querySelector(`${rf}[aria-selected="true"]`)}function M(){var L;return Array.from(((L=S.current)==null?void 0:L.querySelectorAll(lh))||[])}function F(L){let z=M()[L];z&&E.setState("value",z.getAttribute(Zr))}function D(L){var z;let X=T(),W=M(),U=W.findIndex(Q=>Q===X),V=W[U+L];(z=o.current)!=null&&z.loop&&(V=U+L<0?W[W.length-1]:U+L===W.length?W[0]:W[U+L]),V&&E.setState("value",V.getAttribute(Zr))}function A(L){let z=T(),X=z==null?void 0:z.closest(Pn),W;for(;X&&!W;)X=L>0?Ek(X,Pn):_k(X,Pn),W=X==null?void 0:X.querySelector(lh);W?E.setState("value",W.getAttribute(Zr)):D(L)}let H=()=>F(M().length-1),$=L=>{L.preventDefault(),L.metaKey?H():L.altKey?A(1):D(1)},_=L=>{L.preventDefault(),L.metaKey?F(0):L.altKey?A(-1):D(-1)};return x.createElement(xr.div,{ref:s,tabIndex:-1,...j,"cmdk-root":"",onKeyDown:L=>{var z;(z=j.onKeyDown)==null||z.call(j,L);let X=L.nativeEvent.isComposing||L.keyCode===229;if(!(L.defaultPrevented||X))switch(L.key){case"n":case"j":{f&&L.ctrlKey&&$(L);break}case"ArrowDown":{$(L);break}case"p":case"k":{f&&L.ctrlKey&&_(L);break}case"ArrowUp":{_(L);break}case"Home":{L.preventDefault(),F(0);break}case"End":{L.preventDefault(),H();break}case"Enter":{L.preventDefault();let W=T();if(W){let U=new Event(rc);W.dispatchEvent(U)}}}}},x.createElement("label",{"cmdk-label":"",htmlFor:R.inputId,id:R.labelId,style:Ok},c),Rl(t,L=>x.createElement(lf.Provider,{value:E},x.createElement(nf.Provider,{value:R},L))))}),Ak=x.forwardRef((t,s)=>{var a,r;let n=ln(),i=x.useRef(null),l=x.useContext(of),o=bi(),c=df(t),d=(r=(a=c.current)==null?void 0:a.forceMount)!=null?r:l==null?void 0:l.forceMount;Ur(()=>{if(!d)return o.item(n,l==null?void 0:l.id)},[d]);let m=mf(n,i,[t.value,t.children,i],t.keywords),p=yd(),u=ur(C=>C.value&&C.value===m.current),h=ur(C=>d||o.filter()===!1?!0:C.search?C.filtered.items.get(n)>0:!0);x.useEffect(()=>{let C=i.current;if(!(!C||t.disabled))return C.addEventListener(rc,g),()=>C.removeEventListener(rc,g)},[h,t.onSelect,t.disabled]);function g(){var C,E;b(),(E=(C=c.current).onSelect)==null||E.call(C,m.current)}function b(){p.setState("value",m.current,!0)}if(!h)return null;let{disabled:f,value:j,onSelect:y,forceMount:v,keywords:w,...S}=t;return x.createElement(xr.div,{ref:Yn(i,s),...S,id:n,"cmdk-item":"",role:"option","aria-disabled":!!f,"aria-selected":!!u,"data-disabled":!!f,"data-selected":!!u,onPointerMove:f||o.getDisablePointerSelection()?void 0:b,onClick:f?void 0:g},t.children)}),Tk=x.forwardRef((t,s)=>{let{heading:a,children:r,forceMount:n,...i}=t,l=ln(),o=x.useRef(null),c=x.useRef(null),d=ln(),m=bi(),p=ur(h=>n||m.filter()===!1?!0:h.search?h.filtered.groups.has(l):!0);Ur(()=>m.group(l),[]),mf(l,o,[t.value,t.heading,c]);let u=x.useMemo(()=>({id:l,forceMount:n}),[n]);return x.createElement(xr.div,{ref:Yn(o,s),...i,"cmdk-group":"",role:"presentation",hidden:p?void 0:!0},a&&x.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},a),Rl(t,h=>x.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":a?d:void 0},x.createElement(of.Provider,{value:u},h))))}),kk=x.forwardRef((t,s)=>{let{alwaysRender:a,...r}=t,n=x.useRef(null),i=ur(l=>!l.search);return!a&&!i?null:x.createElement(xr.div,{ref:Yn(n,s),...r,"cmdk-separator":"",role:"separator"})}),Dk=x.forwardRef((t,s)=>{let{onValueChange:a,...r}=t,n=t.value!=null,i=yd(),l=ur(d=>d.search),o=ur(d=>d.selectedItemId),c=bi();return x.useEffect(()=>{t.value!=null&&i.setState("search",t.value)},[t.value]),x.createElement(xr.input,{ref:s,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":o,id:c.inputId,type:"text",value:n?t.value:l,onChange:d=>{n||i.setState("search",d.target.value),a==null||a(d.target.value)}})}),Rk=x.forwardRef((t,s)=>{let{children:a,label:r="Suggestions",...n}=t,i=x.useRef(null),l=x.useRef(null),o=ur(d=>d.selectedItemId),c=bi();return x.useEffect(()=>{if(l.current&&i.current){let d=l.current,m=i.current,p,u=new ResizeObserver(()=>{p=requestAnimationFrame(()=>{let h=d.offsetHeight;m.style.setProperty("--cmdk-list-height",h.toFixed(1)+"px")})});return u.observe(d),()=>{cancelAnimationFrame(p),u.unobserve(d)}}},[]),x.createElement(xr.div,{ref:Yn(i,s),...n,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},Rl(t,d=>x.createElement("div",{ref:Yn(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),Fk=x.forwardRef((t,s)=>{let{open:a,onOpenChange:r,overlayClassName:n,contentClassName:i,container:l,...o}=t;return x.createElement(Dh,{open:a,onOpenChange:r},x.createElement(kh,{container:l},x.createElement(ic,{"cmdk-overlay":"",className:n}),x.createElement(lc,{"aria-label":t.label,"cmdk-dialog":"",className:i},x.createElement(cf,{ref:s,...o}))))}),Ik=x.forwardRef((t,s)=>ur(a=>a.filtered.count===0)?x.createElement(xr.div,{ref:s,...t,"cmdk-empty":"",role:"presentation"}):null),Pk=x.forwardRef((t,s)=>{let{progress:a,children:r,label:n="Loading...",...i}=t;return x.createElement(xr.div,{ref:s,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":a,"aria-valuemin":0,"aria-valuemax":100,"aria-label":n},Rl(t,l=>x.createElement("div",{"aria-hidden":!0},l)))}),Cn=Object.assign(cf,{List:Rk,Item:Ak,Input:Dk,Group:Tk,Separator:kk,Dialog:Fk,Empty:Ik,Loading:Pk});function Ek(t,s){let a=t.nextElementSibling;for(;a;){if(a.matches(s))return a;a=a.nextElementSibling}}function _k(t,s){let a=t.previousElementSibling;for(;a;){if(a.matches(s))return a;a=a.previousElementSibling}}function df(t){let s=x.useRef(t);return Ur(()=>{s.current=t}),s}var Ur=typeof window>"u"?x.useEffect:x.useLayoutEffect;function qr(t){let s=x.useRef();return s.current===void 0&&(s.current=t()),s}function ur(t){let s=yd(),a=()=>t(s.snapshot());return x.useSyncExternalStore(s.subscribe,a,a)}function mf(t,s,a,r=[]){let n=x.useRef(),i=bi();return Ur(()=>{var l;let o=(()=>{var d;for(let m of a){if(typeof m=="string")return m.trim();if(typeof m=="object"&&"current"in m)return m.current?(d=m.current.textContent)==null?void 0:d.trim():n.current}})(),c=r.map(d=>d.trim());i.value(t,o,c),(l=s.current)==null||l.setAttribute(Zr,o),n.current=o}),n}var Mk=()=>{let[t,s]=x.useState(),a=qr(()=>new Map);return Ur(()=>{a.current.forEach(r=>r()),a.current=new Map},[t]),(r,n)=>{a.current.set(r,n),s({})}};function Lk(t){let s=t.type;return typeof s=="function"?s(t.props):"render"in s?s.render(t.props):t}function Rl({asChild:t,children:s},a){return t&&x.isValidElement(s)?x.cloneElement(Lk(s),{ref:s.ref},a(s.props.children)):a(s)}var Ok={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function $k({className:t,...s}){return e.jsx(Cn,{"data-slot":"command",className:Me("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",t),...s})}function Uk({className:t,wrapperClassName:s,...a}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:Me("flex h-9 items-center gap-2 border-b px-3",s),children:[e.jsx(Jt,{className:"size-4 shrink-0 opacity-50"}),e.jsx(Cn.Input,{"data-slot":"command-input",className:Me("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",t),...a})]})}function Bk({className:t,...s}){return e.jsx(Cn.List,{"data-slot":"command-list",className:Me("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",t),...s})}function Vk({...t}){return e.jsx(Cn.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...t})}function zk({className:t,...s}){return e.jsx(Cn.Group,{"data-slot":"command-group",className:Me("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",t),...s})}function Hk({className:t,...s}){return e.jsx(Cn.Item,{"data-slot":"command-item",className:Me("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}async function uf(t=!1,s=1,a=10,r){var c,d;const n={active:t,page:s,limit:a};r&&(n.search=r);const i=await be.get("/hsn-sac",{params:n}),l=(c=i.data)==null?void 0:c.data,o=(d=i.data)==null?void 0:d.pagination;return Array.isArray(l)&&o?{codes:l,pagination:o}:{codes:Array.isArray(l)?l:[],pagination:o||{totalRecords:0,totalPages:0,currentPage:1,limit:10}}}async function Gk(t){var a;const s=await be.post("/hsn-sac",t);return((a=s.data)==null?void 0:a.data)||s.data}async function Wk(t,s){var r;const a=await be.patch(`/hsn-sac/${t}`,s);return((r=a.data)==null?void 0:r.data)||a.data}async function Yk(t){await be.delete(`/hsn-sac/${t}`)}async function Kk(t){var a;const s=await be.patch(`/hsn-sac/${t}/toggle-active`);return((a=s.data)==null?void 0:a.data)||s.data}function xf({value:t,onChange:s,type:a,placeholder:r,disabled:n,className:i}){var p;const[l,o]=x.useState(!1),[c,d]=x.useState([]);x.useEffect(()=>{const u=async()=>{try{const h=await uf(!0,1,1e3);d(h.codes)}catch(h){console.error("Failed to fetch HSN/SAC codes for selector:",h)}};l&&c.length===0&&u()},[l,c.length]);const m=x.useMemo(()=>c.filter(u=>u.type===a),[c,a]);return e.jsxs(sa,{open:l,onOpenChange:o,children:[e.jsx(aa,{asChild:!0,children:e.jsxs(P,{variant:"outline",role:"combobox","aria-expanded":l,disabled:n,className:Me("w-full justify-between bg-white font-normal h-9 px-3 text-xs sm:text-sm border-slate-200 hover:bg-slate-50",i),children:[e.jsx("span",{className:"font-medium text-slate-900",children:t?((p=c.find(u=>u.code===t))==null?void 0:p.code)||t:r||`Select ${a}...`}),e.jsx(Nj,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(ra,{className:"w-[320px] p-0 shadow-2xl border-slate-200",align:"start",children:e.jsxs($k,{className:"rounded-lg border-0",children:[e.jsxs("div",{className:"bg-slate-50/80 p-2.5 flex items-center gap-2",children:[e.jsx(Jt,{className:"w-4 h-4 text-slate-400"}),e.jsx(Uk,{placeholder:`Search ${a} code...`,wrapperClassName:"border-none p-0 h-auto flex-1",className:"h-8 border-none bg-transparent shadow-none ring-0 focus-visible:ring-0 placeholder:text-slate-400 text-sm"})]}),e.jsxs(Bk,{className:"max-h-[350px] scrollbar-thin scrollbar-thumb-slate-200",children:[e.jsx(Vk,{className:"py-8 text-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Jt,{className:"h-8 w-8 text-slate-200"}),e.jsxs("p",{className:"text-sm font-medium text-slate-500",children:["No ",a," code found"]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Try a different search term"})]})}),e.jsx(zk,{className:"p-1.5",children:m.map(u=>e.jsxs(Hk,{value:u.code,onSelect:h=>{s(h),o(!1)},className:"flex flex-col items-start gap-1 p-2.5 rounded-md aria-selected:bg-slate-100 transition-colors cursor-pointer mb-1 last:mb-0",children:[e.jsxs("div",{className:"flex items-center w-full justify-between",children:[e.jsx("span",{className:"font-bold text-sm text-slate-900 leading-none",children:u.code}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Oa,{className:Me("h-4 w-4 text-re-green transition-all",t===u.code?"opacity-100 scale-100":"opacity-0 scale-75")})})]}),u.description&&e.jsx("span",{className:"text-[11px] text-slate-500 line-clamp-2 leading-tight pr-4",children:u.description})]},u.id))})]})]})})]})}const fa=(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:""}},Qk={"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"},Xk="33",Jk=new Set(["04","25","26","31","35","38"]),hf=t=>{if(!t||t.length<2)return null;const s=t.substring(0,2);return Qk[s]?s:null},Zk=t=>t?Jk.has(t):!1,qk=t=>t?t!==Xk:!1,pf=t=>{if(!t)return{isIGST:!1,isCGST:!0,isSGST:!0,isUTGST:!1};if(qk(t))return{isIGST:!0,isCGST:!1,isSGST:!1,isUTGST:!1};const a=Zk(t);return{isIGST:!1,isCGST:!0,isSGST:!a,isUTGST:a}};function e4({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",dealerGSTIN:n,activityName:i="Activity",requestId:l,defaultGstRate:o=18,documentPolicy:c,taxationType:d}){var Ce,Ae;const[m,p]=x.useState(""),[u,h]=x.useState(""),g=x.useMemo(()=>{const ce=hf(n);return pf(ce)},[n]),b=x.useMemo(()=>d==="Non GST"||d==="Non-GST",[d]),[f,j]=x.useState([]),[y,v]=x.useState([]),[w,S]=x.useState([]),[C,E]=x.useState([]),[R,k]=x.useState(null),[N,O]=x.useState(""),[I,B]=x.useState(!1),[T,M]=x.useState(null),F=x.useRef(null),D=x.useRef(null),A=x.useRef(null),H=x.useRef(null),$=ce=>{const pe=ce.type.toLowerCase(),Te=ce.name.toLowerCase();return pe.includes("image")||pe.includes("pdf")||Te.endsWith(".pdf")||Te.endsWith(".jpg")||Te.endsWith(".jpeg")||Te.endsWith(".png")||Te.endsWith(".gif")||Te.endsWith(".webp")};x.useEffect(()=>()=>{T!=null&&T.url&&URL.revokeObjectURL(T.url)},[T]),x.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 _=ce=>{if(!$(ce)){G.error("Preview is only available for images and PDF files");return}T!=null&&T.url&&URL.revokeObjectURL(T.url);const pe=URL.createObjectURL(ce);M({file:ce,url:pe})},L=ce=>{const pe=URL.createObjectURL(ce),Te=document.createElement("a");Te.href=pe,Te.download=ce.name,document.body.appendChild(Te),Te.click(),document.body.removeChild(Te),URL.revokeObjectURL(pe)},z=x.useMemo(()=>f.reduce((ce,pe)=>ce+(pe.totalAmt||pe.amount||0),0),[f]),X=(ce,pe,Te=1)=>{const de=ce*Te,me=de*(pe.cgstRate||0)/100,Ne=de*(pe.sgstRate||0)/100,Oe=de*(pe.utgstRate||0)/100,st=de*(pe.igstRate||0)/100,nt=me+Ne+Oe+st,St=de+nt;return{cgstRate:pe.cgstRate,cgstAmt:me,sgstRate:pe.sgstRate,sgstAmt:Ne,utgstRate:pe.utgstRate,utgstAmt:Oe,igstRate:pe.igstRate,igstAmt:st,gstAmt:nt,gstRate:(pe.cgstRate||0)+(pe.sgstRate||0)+(pe.utgstRate||0)+(pe.igstRate||0),totalAmt:St}},W=x.useMemo(()=>{const ce=m!=="",pe=y.length>0,Te=w.length>0,de=N.trim().length>0,me=f.length>0&&f.every(Oe=>Oe.description.trim()!==""&&Oe.amount>0),Ne=b?!1:f.some(Oe=>{const{isValid:st}=fa(Oe.hsnCode,Oe.isService);return!st});return ce&&pe&&Te&&de&&me&&!Ne},[m,y,w,N,b,f]),U=new Date().toISOString().split("T")[0],V=()=>{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}])},Q=(ce,pe,Te)=>{j(f.map(de=>{if(de.id===ce){let me={...de,[pe]:Te};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate","quantity"].includes(pe)){const Ne=parseFloat(Te);if(!isNaN(Ne)&&Ne<0)return G.error("Value cannot be negative"),de;const Oe=pe==="amount"?parseFloat(Te)||0:de.amount,st=pe==="quantity"?parseInt(Te)||1:de.quantity;let nt=de.cgstRate,St=de.sgstRate,Mt=de.utgstRate,ne=de.igstRate;if(pe==="cgstRate"){if(!g.isCGST)return de;nt=parseFloat(Te)||0,g.isUTGST?(Mt=nt,St=0):(St=nt,Mt=0),ne=0}else if(pe==="sgstRate"){if(!g.isSGST)return de;St=parseFloat(Te)||0,nt=St,Mt=0,ne=0}else if(pe==="utgstRate"){if(!g.isUTGST)return de;Mt=parseFloat(Te)||0,nt=Mt,St=0,ne=0}else if(pe==="igstRate"){if(!g.isIGST)return de;ne=parseFloat(Te)||0,nt=0,St=0,Mt=0}else if(pe==="gstRate"){const oe=parseFloat(Te)||0;g.isIGST?(ne=oe,nt=0,St=0,Mt=0):(nt=oe/2,g.isUTGST?(Mt=oe/2,St=0):(St=oe/2,Mt=0),ne=0)}const Ee=X(Oe,{cgstRate:nt,sgstRate:St,igstRate:ne,utgstRate:Mt},st);return pe==="isService"&&(me.hsnCode=""),{...me,amount:Oe,quantity:st,...Ee}}return pe==="isService"&&(me.hsnCode=""),me}return de}))},ee=ce=>{j(f.filter(pe=>pe.id!==ce))},K=ce=>{const pe=Array.from(ce.target.files||[]);if(pe.length>0){const Te=[],de=c.maxFileSizeMB*1024*1024,me=[".pdf",".doc",".docx",".zip",".rar"];pe.forEach(Ne=>{var nt,St;const Oe="."+((nt=Ne.name.split(".").pop())==null?void 0:nt.toLowerCase()),st=((St=Ne.name.split(".").pop())==null?void 0:St.toLowerCase())||"";if(Ne.size>de){G.error(`"${Ne.name}" exceeds ${c.maxFileSizeMB}MB limit and was not added.`);return}if(!me.includes(Oe)){G.error(`"${Ne.name}" is not a supported document type (PDF, DOC, ZIP).`);return}if(!c.allowedFileTypes.includes(st)){G.error(`"${Ne.name}" has an unallowed file type according to system policy.`);return}Te.push(Ne)}),Te.length>0&&v([...y,...Te]),F.current&&(F.current.value="")}},q=ce=>{v(y.filter((pe,Te)=>Te!==ce))},ue=ce=>{const pe=Array.from(ce.target.files||[]);if(pe.length>0){const Te=[],de=c.maxFileSizeMB*1024*1024;pe.forEach(me=>{var Oe;const Ne=((Oe=me.name.split(".").pop())==null?void 0:Oe.toLowerCase())||"";if(me.size>de){G.error(`Photo "${me.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!me.type.startsWith("image/")){G.error(`"${me.name}" is not an image file.`);return}if(!c.allowedFileTypes.includes(Ne)){G.error(`"${me.name}" has an unsupported image format.`);return}Te.push(me)}),Te.length>0&&S([...w,...Te]),D.current&&(D.current.value="")}},Le=ce=>{S(w.filter((pe,Te)=>Te!==ce))},Ze=ce=>{const pe=Array.from(ce.target.files||[]);if(pe.length>0){const Te=[],de=c.maxFileSizeMB*1024*1024,me=[".pdf",".jpg",".jpeg",".png"];pe.forEach(Ne=>{var nt,St;const Oe="."+((nt=Ne.name.split(".").pop())==null?void 0:nt.toLowerCase()),st=((St=Ne.name.split(".").pop())==null?void 0:St.toLowerCase())||"";if(Ne.size>de){G.error(`Invoice "${Ne.name}" exceeds ${c.maxFileSizeMB}MB limit.`);return}if(!me.includes(Oe)){G.error(`"${Ne.name}" is not a supported type (PDF, JPG, PNG).`);return}if(!c.allowedFileTypes.includes(st)){G.error(`"${Ne.name}" format is not allowed by system policy.`);return}Te.push(Ne)}),Te.length>0&&E([...C,...Te]),A.current&&(A.current.value="")}},De=ce=>{E(C.filter((pe,Te)=>Te!==ce))},_e=ce=>{var Te,de,me;const pe=(Te=ce.target.files)==null?void 0:Te[0];if(pe){const Ne=c.maxFileSizeMB*1024*1024,Oe=[".pdf",".xlsx",".xls",".csv"],st="."+((de=pe.name.split(".").pop())==null?void 0:de.toLowerCase()),nt=((me=pe.name.split(".").pop())==null?void 0:me.toLowerCase())||"";if(pe.size>Ne){G.error(`Attendance file exceeds ${c.maxFileSizeMB}MB limit.`),H.current&&(H.current.value="");return}if(!Oe.includes(st)){G.error("Please upload PDF, Excel, or CSV files only"),H.current&&(H.current.value="");return}if(!c.allowedFileTypes.includes(nt)){G.error(`"${pe.name}" format is not allowed by system policy.`),H.current&&(H.current.value="");return}k(pe)}},Ue=async()=>{if(!W){G.error("Please fill all required fields");return}if(f.some(de=>de.amount<0||de.quantity<1)){G.error("Please ensure all amounts are non-negative and quantity is at least 1");return}const pe=f.filter(de=>de.description.trim()!==""&&de.amount>0);if(!b&&pe.some(de=>de.description.trim()!==""&&de.amount>0&&(de.gstRate===0||!de.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.`)){B(!1);return}try{B(!0),await a({activityCompletionDate:m,numberOfParticipants:u?parseInt(u):void 0,closedExpenses:pe,totalClosedExpenses:z,completionDocuments:y,activityPhotos:w,invoicesReceipts:C.length>0?C:void 0,attendanceSheet:R||void 0,completionDescription:N}),re(),s()}catch(de){console.error("Failed to submit completion documents:",de),fd(de)||G.error("Failed to submit completion documents. Please try again.")}finally{B(!1)}},re=()=>{T!=null&&T.url&&URL.revokeObjectURL(T.url),M(null),p(""),h(""),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([]),E([]),k(null),O(""),F.current&&(F.current.value=""),D.current&&(D.current.value=""),A.current&&(A.current.value=""),H.current&&(H.current.value="")},fe=()=>{I||(re(),s())};return e.jsxs(e.Fragment,{children:[e.jsx(xt,{open:t,onOpenChange:fe,children:e.jsxs(dt,{className:"dealer-completion-documents-modal overflow-hidden flex flex-col",children:[e.jsxs(ht,{className:"px-6 pt-6 pb-3 flex-shrink-0",children:[e.jsxs(mt,{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(ys,{className:"w-5 h-5 sm:w-6 sm:h-6 text-[--re-green]"}),"Activity Completion Documents"]}),d&&e.jsx(ae,{className:`ml-2 border-none shadow-sm ${d==="GST"?"bg-emerald-600 text-white hover:bg-emerald-700":"bg-indigo-600 text-white hover:bg-indigo-700"}`,children:d==="GST"?"GST Claim":"Non-GST Claim"})]}),e.jsx(Et,{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(se,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDate",children:[e.jsx(gt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),"Activity Completion Date *"]}),e.jsx(ea,{value:m||null,onChange:ce=>p(ce||""),maxDate:U,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(P,{type:"button",onClick:V,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white",size:"sm",children:[e.jsx(ms,{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(ce=>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(se,{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:ce.description,onChange:pe=>Q(ce.id,"description",pe.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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount"}),e.jsxs("div",{className:"relative",children:[e.jsx(Os,{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:ce.amount||"",onChange:pe=>Q(ce.id,"amount",pe.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(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Amount (Base)"}),e.jsxs("div",{className:"relative",children:[e.jsx(Os,{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:ce.amount||"",onChange:pe=>Q(ce.id,"amount",pe.target.value),className:"w-full bg-white text-sm pl-8"})]})]}),!b&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"w-32 sm:w-36 flex-shrink-0 relative pb-5",children:[e.jsx(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"HSN/SAC Code"}),e.jsx(xf,{value:ce.hsnCode||"",onChange:pe=>Q(ce.id,"hsnCode",pe),type:ce.isService?"SAC":"HSN",className:fa(ce.hsnCode,ce.isService).isValid?"":"border-red-500",placeholder:ce.isService?"SAC":"HSN"}),!fa(ce.hsnCode,ce.isService).isValid&&e.jsx("span",{className:"text-[10px] text-red-500 absolute left-0 bottom-0 block leading-tight",children:fa(ce.hsnCode,ce.isService).message})]}),e.jsxs("div",{className:"w-24 sm:w-28 flex-shrink-0",children:[e.jsx(se,{className:"text-[10px] uppercase text-gray-500 font-bold mb-1 block",children:"Item Type"}),e.jsxs("select",{value:ce.isService?"SAC":"HSN",onChange:pe=>Q(ce.id,"isService",pe.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(se,{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:ce.cgstRate||"",onChange:pe=>Q(ce.id,"cgstRate",pe.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(se,{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:ce.sgstRate||"",onChange:pe=>Q(ce.id,"sgstRate",pe.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(se,{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:ce.utgstRate||"",onChange:pe=>Q(ce.id,"utgstRate",pe.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(se,{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:ce.igstRate||"",onChange:pe=>Q(ce.id,"igstRate",pe.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(P,{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:()=>ee(ce.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:["₹",(ce.cgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),ce.sgstAmt>0&&e.jsxs("span",{children:["SGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(ce.sgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),ce.utgstAmt>0&&e.jsxs("span",{children:["UTGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(ce.utgstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs("span",{children:["IGST: ",e.jsxs("span",{className:"text-gray-900 font-semibold",children:["₹",(ce.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:["₹",(ce.gstAmt||0).toLocaleString("en-IN",{minimumFractionDigits:1})]})]}),e.jsxs(ae,{className:"bg-[#2d4a3e] text-white px-3 py-1 text-xs",children:["Item Total: ₹",(ce.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:["₹",(ce.amount||0).toLocaleString("en-IN",{minimumFractionDigits:2})]})]})]})]},ce.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&&z>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:["₹",z.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(ae,{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(se,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Re,{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:F,type:"file",multiple:!0,accept:[".pdf",".doc",".docx",".zip",".rar"].filter(ce=>c.allowedFileTypes.includes(ce.replace(".",""))).join(","),className:"hidden",id:"completionDocs",onChange:K}),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(ps,{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(ys,{className:"w-8 h-8 text-gray-400"}),e.jsxs("span",{className:"text-sm text-gray-600",children:["Click to upload documents (Max ",c.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((ce,pe)=>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(Re,{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:ce.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[$(ce)&&e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>_(ce),title:"Preview file",children:e.jsx(vt,{className:"w-3.5 h-3.5"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>L(ce),title:"Download file",children:e.jsx(Tt,{className:"w-3.5 h-3.5"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>q(pe),title:"Remove document",children:e.jsx(jt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},pe))]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(Di,{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:D,type:"file",multiple:!0,accept:[".jpg",".jpeg",".png",".gif",".webp"].filter(ce=>c.allowedFileTypes.includes(ce.replace(".",""))).join(","),className:"hidden",id:"completionPhotos",onChange:ue}),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(ps,{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(Di,{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((ce,pe)=>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(Di,{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:ce.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[$(ce)&&e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>_(ce),title:"Preview photo",children:e.jsx(vt,{className:"w-3.5 h-3.5"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>L(ce),title:"Download photo",children:e.jsx(Tt,{className:"w-3.5 h-3.5"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>Le(pe),title:"Remove photo",children:e.jsx(jt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},pe))]})]})]})]}),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(ae,{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(se,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",children:[e.jsx(_t,{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:A,type:"file",multiple:!0,accept:[".pdf",".jpg",".jpeg",".png"].filter(ce=>c.allowedFileTypes.includes(ce.replace(".",""))).join(","),className:"hidden",id:"invoiceReceipts",onChange:Ze}),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(ps,{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(_t,{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((ce,pe)=>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(_t,{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:ce.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[$(ce)&&e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>_(ce),title:"Preview file",children:e.jsx(vt,{className:"w-3.5 h-3.5"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>L(ce),title:"Download file",children:e.jsx(Tt,{className:"w-3.5 h-3.5"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>De(pe),title:"Remove document",children:e.jsx(jt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"})})]})]},pe))]})]}),e.jsxs("div",{children:[e.jsx(se,{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 ${R?"border-blue-500 bg-blue-50 hover:border-blue-600":"border-gray-300 hover:border-blue-500 bg-white"}`,children:[e.jsx("input",{ref:H,type:"file",accept:[".pdf",".xlsx",".xls",".csv"].filter(ce=>c.allowedFileTypes.includes(ce.replace(".",""))).join(","),className:"hidden",id:"attendanceDoc",onChange:_e}),e.jsx("label",{htmlFor:"attendanceDoc",className:"cursor-pointer flex flex-col items-center gap-2",children:R?e.jsxs(e.Fragment,{children:[e.jsx(ps,{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:R.name}),e.jsx("span",{className:"text-xs text-blue-600",children:"Document selected"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(ys,{className:"w-8 h-8 text-gray-400"}),e.jsx("span",{className:"text-sm text-gray-600",children:"Click to upload attendance sheet (Excel, PDF, CSV)"})]})})]}),R&&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(Re,{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:R.name})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[$(R)&&e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700",onClick:()=>_(R),title:"Preview file",children:e.jsx(vt,{className:"w-3.5 h-3.5"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700",onClick:()=>L(R),title:"Download file",children:e.jsx(Tt,{className:"w-3.5 h-3.5"})}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700",onClick:()=>{k(null),H.current&&(H.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(se,{className:"text-sm sm:text-base font-semibold flex items-center gap-2",htmlFor:"completionDescription",children:"Brief Description of Completion *"}),e.jsx($s,{id:"completionDescription",placeholder:"Provide a brief description of the completed activity, including key highlights, outcomes, challenges faced, and any relevant observations...",value:N,onChange:ce=>O(ce.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"]})]}),!W&&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(Je,{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(Dt,{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(P,{variant:"outline",onClick:fe,disabled:I,className:"border-2",children:"Cancel"}),e.jsx(P,{onClick:Ue,disabled:I||!W,className:"bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500",children:I?"Submitting...":"Submit Documents"})]})]})}),T&&e.jsx(xt,{open:!!T,onOpenChange:()=>{T!=null&&T.url&&URL.revokeObjectURL(T.url),M(null)},children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(ht,{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(vt,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:T.file.name}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[T.file.type||"Unknown type"," • ",(T.file.size/1024).toFixed(1)," KB"]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:e.jsxs(P,{variant:"outline",size:"sm",onClick:()=>L(T.file),className:"gap-2 h-9",children:[e.jsx(Tt,{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:(Ce=T.file.type)!=null&&Ce.includes("image")?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:T.url,alt:T.file.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}):(Ae=T.file.type)!=null&&Ae.includes("pdf")||T.file.name.toLowerCase().endsWith(".pdf")?e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:T.url,className:"w-full h-full rounded-lg border-0",title:T.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(vt,{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(P,{onClick:()=>L(T.file),className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4"}),"Download ",T.file.name]})]})})]})})})]})}function t4({isOpen:t,onClose:s,onSubmit:a,dealerName:r="Jaipur Royal Enfield",dealerGSTIN:n,activityName:i="Activity",requestId:l,previousProposalData:o,defaultGstRate:c=18,documentPolicy:d,taxationType:m,totalBlockedAmount:p=0}){const[u,h]=x.useState(null),g=x.useMemo(()=>{const re=hf(n);return pf(re)},[n]),b=x.useMemo(()=>m==="Non GST"||m==="Non-GST",[m]),[f,j]=x.useState([{id:"1",description:"",amount:0,gstRate:c||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=(re,fe,Ce=1)=>{const Ae=re*Ce,ce=Ae*(fe.cgstRate||0)/100,pe=Ae*(fe.sgstRate||0)/100,Te=Ae*(fe.utgstRate||0)/100,de=Ae*(fe.igstRate||0)/100,me=ce+pe+Te+de,Ne=Ae+me;return{cgstRate:fe.cgstRate,cgstAmt:ce,sgstRate:fe.sgstRate,sgstAmt:pe,utgstRate:fe.utgstRate,utgstAmt:Te,igstRate:fe.igstRate,igstAmt:de,gstAmt:me,gstRate:(fe.cgstRate||0)+(fe.sgstRate||0)+(fe.utgstRate||0)+(fe.igstRate||0),totalAmt:Ne}},[v,w]=x.useState("date"),[S,C]=x.useState(""),[E,R]=x.useState(""),[k,N]=x.useState([]),[O,I]=x.useState(""),[B,T]=x.useState(!1),[M,F]=x.useState(null),[D,A]=x.useState(!1),H=x.useRef(null),$=x.useRef(null),_=re=>{if(!re)return!1;const fe=re.toLowerCase();return fe.endsWith(".pdf")||!!fe.match(/\.(jpg|jpeg|png|gif|webp)$/i)},L=re=>_(re.name);x.useEffect(()=>()=>{M!=null&&M.fileUrl&&M.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(M.fileUrl)},[M]);const z=re=>{if(!L(re)){G.error("Preview is only available for images and PDF files");return}M!=null&&M.fileUrl&&M.fileUrl.startsWith("blob:")&&URL.revokeObjectURL(M.fileUrl);const fe=URL.createObjectURL(re);F({fileName:re.name,fileType:re.type,documentId:"",fileUrl:fe,fileSize:re.size})},X=re=>{const fe=re.originalFileName||re.fileName||re.name||"Document",Ce=re.documentId||re.id||"",Ae=fe.toLowerCase().endsWith(".pdf")?"application/pdf":"image/jpeg";let ce="";if(Ce)ce=yn(Ce);else if(ce=re.storageUrl||re.documentUrl||"",ce&&!ce.startsWith("http")){const pe="https://reflow-uat.royalenfield.com",Te=pe.endsWith("/")?pe.slice(0,-1):pe,de=ce.startsWith("/")?ce:`/${ce}`;ce=`${Te}${de}`}F({fileName:fe,fileType:Ae,documentId:Ce,fileUrl:ce})},W=re=>{const fe=URL.createObjectURL(re),Ce=document.createElement("a");Ce.href=fe,Ce.download=re.name,document.body.appendChild(Ce),Ce.click(),document.body.removeChild(Ce),URL.revokeObjectURL(fe)};x.useEffect(()=>{if(t&&o){const re=p>0;if(o.costItems&&o.costItems.length>0){const fe=o.costItems.map((Ce,Ae)=>({id:`original-${Ae}`,description:Ce.itemDescription||Ce.description||"",amount:Number(Ce.amount)||0,quantity:Number(Ce.quantity)||1,hsnCode:Ce.hsnCode||"",isService:!!Ce.isService,gstRate:Number(Ce.gstRate)||c,cgstRate:Number(Ce.cgstRate)||0,sgstRate:Number(Ce.sgstRate)||0,utgstRate:Number(Ce.utgstRate)||0,igstRate:Number(Ce.igstRate)||0,gstAmt:Number(Ce.gstAmt)||0,cgstAmt:Number(Ce.cgstAmt)||0,sgstAmt:Number(Ce.sgstAmt)||0,utgstAmt:Number(Ce.utgstAmt)||0,igstAmt:Number(Ce.igstAmt)||0,cessRate:Number(Ce.cessRate)||0,cessAmt:Number(Ce.cessAmt)||0,totalAmt:Number(Ce.totalAmt)||0,isOriginal:re}));j(fe)}o.expectedCompletionDate&&(C(o.expectedCompletionDate.split("T")[0]),w("date"))}else t&&!o&&(j([{id:"1",description:"",amount:0,gstRate:c||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(""),I(""))},[t,o,c,p]);const U=x.useMemo(()=>f.reduce((re,fe)=>re+(fe.totalAmt||fe.amount||0),0),[f]),V=x.useMemo(()=>{const re=u!==null,fe=f.length>0&&f.every(pe=>pe.description.trim()!==""&&pe.amount>0),Ce=v==="date"?S!=="":E!==""&&parseInt(E)>0,Ae=O.trim().length>0,ce=b?!1:f.some(pe=>{const{isValid:Te}=fa(pe.hsnCode,pe.isService);return!Te});return re&&fe&&Ce&&Ae&&!ce},[u,f,v,S,E,O,b]),Q=re=>{var Ce,Ae,ce;const fe=(Ce=re.target.files)==null?void 0:Ce[0];if(fe){const pe=d.maxFileSizeMB*1024*1024;if(fe.size>pe){G.error(`File size exceeds the maximum allowed size of ${d.maxFileSizeMB}MB. Current size: ${(fe.size/(1024*1024)).toFixed(2)}MB`),H.current&&(H.current.value="");return}const Te=[".pdf",".doc",".docx"],de="."+((Ae=fe.name.split(".").pop())==null?void 0:Ae.toLowerCase()),me=((ce=fe.name.split(".").pop())==null?void 0:ce.toLowerCase())||"";if(!Te.includes(de)||!d.allowedFileTypes.includes(me)){G.error("Please upload a valid PDF, DOC, or DOCX file as per system policy"),H.current&&(H.current.value="");return}h(fe)}},ee=re=>{const fe=Array.from(re.target.files||[]),Ce=[],Ae=d.maxFileSizeMB*1024*1024;fe.forEach(ce=>{var Te;if(ce.size>Ae){G.error(`"${ce.name}" exceeds ${d.maxFileSizeMB}MB limit and was not added.`);return}const pe=((Te=ce.name.split(".").pop())==null?void 0:Te.toLowerCase())||"";if(!d.allowedFileTypes.includes(pe)){G.error(`"${ce.name}" has an unsupported file type and was not added.`);return}Ce.push(ce)}),Ce.length>0&&N(ce=>[...ce,...Ce]),$.current&&($.current.value="")},K=()=>{j(re=>[...re,{id:Date.now().toString(),description:"",amount:0,gstRate:c||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}])},q=re=>{f.length>1&&j(fe=>fe.filter(Ce=>Ce.id!==re))},ue=(re,fe,Ce)=>{j(Ae=>Ae.map(ce=>{if(ce.id===re){let pe={...ce,[fe]:Ce};if(["amount","gstRate","cgstRate","sgstRate","utgstRate","igstRate"].includes(fe)){const Te=parseFloat(Ce);if(!isNaN(Te)&&Te<0)return G.error("Value cannot be negative"),ce;const de=fe==="amount"?parseFloat(Ce)||0:ce.amount,me=1;let Ne=ce.cgstRate,Oe=ce.sgstRate,st=ce.utgstRate,nt=ce.igstRate;if(fe==="cgstRate"){if(!g.isCGST)return ce;Ne=parseFloat(Ce)||0,g.isUTGST?(st=Ne,Oe=0):(Oe=Ne,st=0),nt=0}else if(fe==="sgstRate"){if(!g.isSGST)return ce;Oe=parseFloat(Ce)||0,Ne=Oe,st=0,nt=0}else if(fe==="utgstRate"){if(!g.isUTGST)return ce;st=parseFloat(Ce)||0,Ne=st,Oe=0,nt=0}else if(fe==="igstRate"){if(!g.isIGST)return ce;nt=parseFloat(Ce)||0,Ne=0,Oe=0,st=0}else if(fe==="gstRate"){const Mt=parseFloat(Ce)||0;g.isIGST?(nt=Mt,Ne=0,Oe=0,st=0):(Ne=Mt/2,g.isUTGST?(st=Mt/2,Oe=0):(Oe=Mt/2,st=0),nt=0)}const St=y(de,{cgstRate:Ne,sgstRate:Oe,igstRate:nt,utgstRate:st},me);return{...pe,amount:de,quantity:me,...St}}return pe}return ce}))},Le=re=>{N(fe=>fe.filter((Ce,Ae)=>Ae!==re))},Ze=async()=>{if(!V){G.error("Please fill all required fields");return}if(f.some(Ce=>Ce.amount<0)){G.error("Please ensure all amounts are non-negative");return}if(v==="days"&&(parseInt(E)<=0||isNaN(parseInt(E)))){G.error("Please enter a valid number of days greater than 0");return}let fe=S||"";if(v==="days"&&E){const Ce=parseInt(E),Ae=new Date;Ae.setDate(Ae.getDate()+Ce),fe=Ae.toISOString().split("T")[0]}try{if(T(!0),!b&&f.some(pe=>pe.description.trim()!==""&&pe.amount>0&&(pe.gstRate===0||!pe.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 d90cfc2..e46ac31 100644 --- a/build/index.html +++ b/build/index.html @@ -13,7 +13,7 @@ - +