From 60c5d4b47529f500449ea814ab30b94c4754b5fc Mon Sep 17 00:00:00 2001 From: laxmanhalaki Date: Fri, 13 Feb 2026 19:11:03 +0530 Subject: [PATCH] okta url issue partial url --- ...{conclusionApi-CzJL-0h7.js => conclusionApi-C_Bd1V1u.js} | 2 +- build/assets/{index-Dpa9DrmL.js => index-CYOEuscl.js} | 6 +++--- build/index.html | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) rename build/assets/{conclusionApi-CzJL-0h7.js => conclusionApi-C_Bd1V1u.js} (90%) rename build/assets/{index-Dpa9DrmL.js => index-CYOEuscl.js} (97%) diff --git a/build/assets/conclusionApi-CzJL-0h7.js b/build/assets/conclusionApi-C_Bd1V1u.js similarity index 90% rename from build/assets/conclusionApi-CzJL-0h7.js rename to build/assets/conclusionApi-C_Bd1V1u.js index 09b9796..5a4c710 100644 --- a/build/assets/conclusionApi-CzJL-0h7.js +++ b/build/assets/conclusionApi-C_Bd1V1u.js @@ -1 +1 @@ -import{a as s}from"./index-Dpa9DrmL.js";import"./radix-vendor-CYvDqP9X.js";import"./charts-vendor-BVfwAPj-.js";import"./utils-vendor-BTBPSQfW.js";import"./ui-vendor-BFJfF1vG.js";import"./socket-vendor-TjCxX7sJ.js";import"./redux-vendor-tbZCm13o.js";import"./router-vendor-B_rK4TXr.js";async function m(n){return(await s.post(`/conclusions/${n}/generate`)).data.data}async function f(n,t){return(await s.post(`/conclusions/${n}/finalize`,{finalRemark:t})).data.data}async function d(n){var t;try{return(await s.get(`/conclusions/${n}`)).data.data}catch(o){if(((t=o.response)==null?void 0:t.status)===404)return null;throw o}}export{f as finalizeConclusion,m as generateConclusion,d as getConclusion}; +import{a as s}from"./index-CYOEuscl.js";import"./radix-vendor-CYvDqP9X.js";import"./charts-vendor-BVfwAPj-.js";import"./utils-vendor-BTBPSQfW.js";import"./ui-vendor-BFJfF1vG.js";import"./socket-vendor-TjCxX7sJ.js";import"./redux-vendor-tbZCm13o.js";import"./router-vendor-B_rK4TXr.js";async function m(n){return(await s.post(`/conclusions/${n}/generate`)).data.data}async function f(n,t){return(await s.post(`/conclusions/${n}/finalize`,{finalRemark:t})).data.data}async function d(n){var t;try{return(await s.get(`/conclusions/${n}`)).data.data}catch(o){if(((t=o.response)==null?void 0:t.status)===404)return null;throw o}}export{f as finalizeConclusion,m as generateConclusion,d as getConclusion}; diff --git a/build/assets/index-Dpa9DrmL.js b/build/assets/index-CYOEuscl.js similarity index 97% rename from build/assets/index-Dpa9DrmL.js rename to build/assets/index-CYOEuscl.js index 57e2d05..ccecba7 100644 --- a/build/assets/index-Dpa9DrmL.js +++ b/build/assets/index-CYOEuscl.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-CzJL-0h7.js","assets/radix-vendor-CYvDqP9X.js","assets/charts-vendor-BVfwAPj-.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-BFJfF1vG.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-B_rK4TXr.js"])))=>i.map(i=>d[i]); -var jg=Object.defineProperty;var Ng=(t,s,a)=>s in t?jg(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var Ui=(t,s,a)=>Ng(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Ru,R as Du,I as Pu,F as Iu,a as wg,T as Cg,P as Sg,C as Ag,b as Tg,O as Eu,c as Fu,d as kg,e as Rg,f as Dg,D as Pg,g as Ig,A as Eg,h as Fg,i as _g,k as Lg,l as Mg,m as $g,n as Og,V as Ug,o as Bg,p as Vg,q as zg,r as Hg,s as Wg,t as Gg,u as Yg,v as Kg,w as Xg,x as Zg,y as Jg,z as Qg,B as qg,E as ef,G as tf,H as sf,J as af,K as rf,L as nf,M as lf,N as of,Q as _u,U as Lu,W as cf,X as Mu,Y as $u,Z as df,_ as mf,$ as uf,a0 as xf,a1 as hf,a2 as pf,a3 as gf,a4 as ff,a5 as bf,a6 as yf,a7 as vf,a8 as jf,a9 as Nf,aa as wf,ab as Cf}from"./radix-vendor-CYvDqP9X.js";import{a as Sf,r as p,c as Ou,d as Pr,B as kl,C as ei,X as ti,Y as si,T as Ir,L as ai,e as fa,P as Uu,f as Bu,g as Vu,h as Af,i as Td,j as fi,k as bi,b as Tf}from"./charts-vendor-BVfwAPj-.js";import{a as no,f as zu,s as Vs,e as io,b as kd,c as kf,d as ja,g as hn,i as lo,h as Hu,j as _s,k as Us,l as Bi,m as ka,n as Rf,o as Rl,p as Df,q as He,r as Dl,t as Pf,u as If,v as Ef,w as Ff,x as Vi,y as Rd,z as _f,A as Wu,B as Gu,C as oo,D as co,E as Lf,F as Mf,G as Yu,H as wr,I as zi,J as $f,K as Of,L as Uf}from"./utils-vendor-BTBPSQfW.js";import{L as Bf,S as hs,C as ze,a as Ls,b as lt,X as ft,H as Vf,c as Ku,U as Vt,F as Re,d as De,e as wn,P as gs,f as zf,g as Hf,B as qs,h as Va,i as Hi,j as mo,k as uo,l as yr,m as Xu,n as yi,o as Zu,p as ot,q as Ya,R as $t,I as Ur,T as Ot,r as st,s as ha,t as Wf,A as ss,u as as,M as As,v as vi,w as kt,x as Pl,D as Ct,Z as xo,y as cs,z as Gf,E as Yf,G as Kf,J as Xf,K as Zf,N as Jf,O as Qf,Q as qf,V as e0,W as Ju,Y as t0,_ as s0,$ as Ra,a0 as ji,a1 as za,a2 as ri,a3 as Dd,a4 as _n,a5 as ni,a6 as Qu,a7 as wt,a8 as a0,a9 as K,aa as ta,ab as Ns,ac as qu,ad as Gt,ae as ex,af as ht,ag as r0,ah as n0,ai as tx,aj as Ni,ak as sx,al as i0,am as l0,an as ho,ao as zs,ap as Da,aq as wi,ar as Ci,as as Rs,at as o0,au as c0,av as ax,aw as d0,ax as Wn,ay as pn,az as po,aA as Si,aB as ii,aC as rx,aD as nx,aE as ix,aF as Ai,aG as Ti,aH as m0,aI as ln,aJ as lx,aK as Il,aL as u0,aM as x0,aN as h0,aO as go,aP as fo,aQ as bo,aR as p0,aS as Pd,aT as ox,aU as g0,aV as yo,aW as f0,aX as Ln,aY as b0,aZ as Id,a_ as y0,a$ as v0,b0 as j0}from"./ui-vendor-BFJfF1vG.js";import{l as N0}from"./socket-vendor-TjCxX7sJ.js";import{c as Br,a as w0}from"./redux-vendor-tbZCm13o.js";import{u as Ks,a as Ea,b as cx,B as C0,R as S0,c as Lt,O as A0}from"./router-vendor-B_rK4TXr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function a(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=a(n);fetch(n.href,i)}})();var El={},Ed=Sf;El.createRoot=Ed.createRoot,El.hydrateRoot=Ed.hydrateRoot;var dx={exports:{}},mx={};var Cn=p;function T0(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var k0=typeof Object.is=="function"?Object.is:T0,R0=Cn.useSyncExternalStore,D0=Cn.useRef,P0=Cn.useEffect,I0=Cn.useMemo,E0=Cn.useDebugValue;mx.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=D0(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=I0(function(){function c(u){if(!d){if(d=!0,m=u,u=r(u),n!==void 0&&l.hasValue){var g=l.value;if(n(g,u))return h=g}return h=u}if(g=h,k0(m,u))return g;var b=r(u);return n!==void 0&&n(g,b)?(m=u,g):(m=u,h=b)}var d=!1,m,h,x=a===void 0?null:a;return[function(){return c(s())},x===null?void 0:function(){return c(x())}]},[s,a,r,n]);var o=R0(t,i[0],i[1]);return P0(function(){l.hasValue=!0,l.value=o},[o]),E0(o),o};dx.exports=mx;var F0=dx.exports;function _0(t){t()}function L0(){let t=null,s=null;return{clear(){t=null,s=null},notify(){_0(()=>{let a=t;for(;a;)a.callback(),a=a.next})},get(){const a=[];let r=t;for(;r;)a.push(r),r=r.next;return a},subscribe(a){let r=!0;const n=s={callback:a,next:null,prev:s};return n.prev?n.prev.next=n:t=n,function(){!r||t===null||(r=!1,n.next?n.next.prev=n.prev:s=n.prev,n.prev?n.prev.next=n.next:t=n.next)}}}}var Fd={notify(){},get:()=>[]};function M0(t,s){let a,r=Fd,n=0,i=!1;function l(b){m();const f=r.subscribe(b);let y=!1;return()=>{y||(y=!0,f(),h())}}function o(){r.notify()}function c(){g.onStateChange&&g.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=L0())}function h(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Fd)}function x(){i||(i=!0,m())}function u(){i&&(i=!1,h())}const g={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:c,isSubscribed:d,trySubscribe:x,tryUnsubscribe:u,getListeners:()=>r};return g}var $0=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",O0=$0(),U0=()=>typeof navigator<"u"&&navigator.product==="ReactNative",B0=U0(),V0=()=>O0||B0?p.useLayoutEffect:p.useEffect,z0=V0(),Wi=Symbol.for("react-redux-context"),Gi=typeof globalThis<"u"?globalThis:{};function H0(){if(!p.createContext)return{};const t=Gi[Wi]??(Gi[Wi]=new Map);let s=t.get(p.createContext);return s||(s=p.createContext(null),t.set(p.createContext,s)),s}var Ha=H0();function W0(t){const{children:s,context:a,serverState:r,store:n}=t,i=p.useMemo(()=>{const c=M0(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=p.useMemo(()=>n.getState(),[n]);z0(()=>{const{subscription:c}=i;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),l!==n.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[i,l]);const o=a||Ha;return p.createElement(o.Provider,{value:i},s)}var G0=W0;function vo(t=Ha){return function(){return p.useContext(t)}}var ux=vo();function xx(t=Ha){const s=t===Ha?ux:vo(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var Y0=xx();function K0(t=Ha){const s=t===Ha?Y0:xx(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var X0=K0(),Z0=(t,s)=>t===s;function J0(t=Ha){const s=t===Ha?ux:vo(t),a=(r,n={})=>{const{equalityFn:i=Z0}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:c,getServerState:d}=l;p.useRef(!0);const m=p.useCallback({[r.name](x){return r(x)}}[r.name],[r]),h=F0.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return p.useDebugValue(h),h};return Object.assign(a,{withTypes:()=>a}),a}var Q0=J0(),Fl=function(t,s){return Fl=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,r){a.__proto__=r}||function(a,r){for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(a[n]=r[n])},Fl(t,s)};function q0(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");Fl(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var li=function(){return li=Object.assign||function(s){for(var a,r=1,n=arguments.length;r0&&g[g.length-1])||C[0]!==6&&C[0]!==2)){f=0;continue}if(C[0]===3&&(!g||C[1]>g[0]&&C[1]0?setTimeout(u,w):u(null)}}window.addEventListener("storage",y),m.addToWaiting(y);var v=setTimeout(y,Math.max(0,h-Date.now()))})];case 1:return x.sent(),[2]}})})},m.addToWaiting=function(h){this.removeFromWaiting(h),m.waiters!==void 0&&m.waiters.push(h)},m.removeFromWaiting=function(h){m.waiters!==void 0&&(m.waiters=m.waiters.filter(function(x){return x!==h}))},m.notifyWaiters=function(){m.waiters!==void 0&&m.waiters.slice().forEach(function(h){return h()})},m.prototype.releaseLock=function(h){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,this.releaseLock__private__(h)];case 1:return[2,x.sent()]}})})},m.prototype.releaseLock__private__=function(h){return a(this,void 0,void 0,function(){var x,u,g,b;return r(this,function(f){switch(f.label){case 0:return x=this.storageHandler===void 0?l:this.storageHandler,u=i+"-"+h,(g=x.getItemSync(u))===null?[2]:(b=JSON.parse(g)).id!==this.id?[3,2]:[4,ir.default().lock(b.iat)];case 1:f.sent(),this.acquiredIatSet.delete(b.iat),x.removeItemSync(u),ir.default().unlock(b.iat),m.notifyWaiters(),f.label=2;case 2:return[2]}})})},m.lockCorrector=function(h){for(var x=Date.now()-5e3,u=h,g=[],b=0;;){var f=u.keySync(b);if(f===null)break;g.push(f),b++}for(var y=!1,v=0;v.")},sb=li(li({},tb),{buildAuthorizeUrl:Es,buildLogoutUrl:Es,getAccessTokenSilently:Es,getAccessTokenWithPopup:Es,getIdTokenClaims:Es,loginWithRedirect:Es,loginWithPopup:Es,connectAccountWithRedirect:Es,logout:Es,handleRedirectCallback:Es,getDpopNonce:Es,setDpopNonce:Es,generateDpopProof:Es,createFetcher:Es}),ab=p.createContext(sb);(function(t){q0(s,t);function s(a,r){var n=t.call(this,r??a)||this;return n.error=a,n.error_description=r,Object.setPrototypeOf(n,s.prototype),n}return s})(Error);var rb=function(t){return t===void 0&&(t=ab),p.useContext(t)};const Yi="idToken",Ki="userData",nb=()=>!0;class tt{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(Yi,s)}static getIdToken(){return sessionStorage.getItem(Yi)}static setUserData(s){localStorage.setItem(Ki,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(Ki);if(!s)return null;try{return JSON.parse(s)}catch{return null}}static clearAll(){try{sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true")}catch(s){console.warn("Could not set logout flags:",s)}try{localStorage.removeItem(Ki),sessionStorage.removeItem(Yi)}catch(s){console.warn("Error clearing user data:",s)}{try{sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true")}catch{}return}}static hasAccessToken(){return!!this.getUserData()}static hasRefreshToken(){return!!this.getUserData()}static isLocalhost(){return window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"||window.location.hostname===""}static isProduction(){return nb()}}function Xi(t,s=5){if(!t)return!0;try{const a=t.split(".");if(a.length!==3||!a[1])return!0;const n=JSON.parse(atob(a[1])).exp*1e3,i=Date.now(),l=s*60*1e3;return n-it,t=>Promise.reject(t));je.interceptors.response.use(t=>t,async t=>{var a,r;const s=t.config;if(t.code==="ERR_NETWORK"||t.code==="ECONNREFUSED"||(a=t.message)!=null&&a.includes("ERR_CONNECTION_REFUSED"),((r=t.response)==null?void 0:r.status)===401&&!s._retry){s._retry=!0;const n=!0;try{const i=tt.getRefreshToken(),l=await no.post(`${hx}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),c=(l.data.data||l.data).accessToken;return je(s)}catch(i){return tt.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function ib(t,s){var a,r;try{const n=await je.post("/auth/token-exchange",{code:t,redirectUri:s},{responseType:"json",headers:{"Content-Type":"application/json",Accept:"application/json"}});if(Array.isArray(n.data))throw console.error("โŒ Response is an array (buffer issue):",{arrayLength:n.data.length,firstFew:n.data.slice(0,10),rawResponse:n}),new Error("Invalid response format: received array instead of JSON. Check Content-Type header.");const i=n.data,l=i.data||i;return l.user&&tt.setUserData(l.user),l.idToken&&tt.setIdToken(l.idToken),l.accessToken&&l.refreshToken&&(tt.setAccessToken(l.accessToken),tt.setRefreshToken(l.refreshToken)),l}catch(n){throw console.error("โŒ Token exchange failed:",{message:n.message,response:(a=n.response)==null?void 0:a.data,status:(r=n.response)==null?void 0:r.status,code:t?`${t.substring(0,10)}...`:"MISSING",redirectUri:s}),n}}async function lb(){var r;const t={},a=(await je.post("/auth/refresh",t)).data;if((r=a.data)!=null&&r.accessToken||a.accessToken,a.success!==!1)return"cookie-based-auth";throw new Error("Failed to refresh token")}async function sn(){const s=(await je.get("/auth/me")).data;return s.data||s}async function ob(){var t,s;try{await je.post("/auth/logout",{},{withCredentials:!0})}catch(a){console.error("๐Ÿ“ก Logout API error:",a),console.error("๐Ÿ“ก Error details:",{message:a.message,status:(t=a.response)==null?void 0:t.status,data:(s=a.response)==null?void 0:s.data})}}const _l="https://ssodev.rebridge.co.in/realms/RE",px="REFLOW",wo=`${window.location.origin}/login/callback`;function cb(){const t=new URLSearchParams(window.location.search),s=t.has("logout")||t.has("tanflow_logged_out");s&&(sessionStorage.removeItem("tanflow_logged_out"),sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),console.log("๐Ÿšช Cleared logout flags before initiating Tanflow login"));const a=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","tanflow"),sessionStorage.setItem("tanflow_auth_state",a);let r=`${_l}/protocol/openid-connect/auth?client_id=${px}&response_type=code&scope=openid&redirect_uri=${encodeURIComponent(wo)}&state=${a}`;s&&(r+="&prompt=login",console.log("๐Ÿšช Adding prompt=login to force re-authentication after logout")),console.log("๐Ÿšช Initiating Tanflow login",{isAfterLogout:s,hasPrompt:s}),window.location.href=r}async function db(t,s){var r,n,i;const a="https://reflow-uat.royalenfield.com/api/v1/";try{const l=await no.post(`${a}/auth/tanflow/token-exchange`,{code:t,redirectUri:wo,state:s},{withCredentials:!0,headers:{"Content-Type":"application/json"}}),o=((r=l.data)==null?void 0:r.data)||l.data;return o.accessToken&&tt.setAccessToken(o.accessToken),o.refreshToken&&tt.setRefreshToken(o.refreshToken),o.idToken&&tt.setIdToken(o.idToken),o.user&&tt.setUserData(o.user),o}catch(l){throw console.error("โŒ Tanflow token exchange failed:",{message:l.message,response:(n=l.response)==null?void 0:n.data,status:(i=l.response)==null?void 0:i.status}),l}}function mb(t){if(!t){console.warn("๐Ÿšช No id_token available for Tanflow logout, redirecting to home");const n=`${window.location.origin}/?tanflow_logged_out=true&logout=${Date.now()}`;window.location.replace(n);return}const s=wo,a=new URL(`${_l}/protocol/openid-connect/logout`);a.searchParams.set("client_id",px),a.searchParams.set("id_token_hint",t),a.searchParams.set("post_logout_redirect_uri",s);const r=a.toString();console.log("๐Ÿšช Tanflow logout initiated",{hasIdToken:!!t,idTokenPrefix:t?t.substring(0,20)+"...":"none",postLogoutRedirectUri:s,logoutUrlBase:`${_l}/protocol/openid-connect/logout`,finalLogoutUrl:r.replace(t.substring(0,20),"***")}),sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),console.log("๐Ÿšช Redirecting to Tanflow logout endpoint..."),window.location.href=r}const gx=p.createContext(void 0);function ub({children:t}){const[s,a]=p.useState(!1),[r,n]=p.useState(!0),[i,l]=p.useState(null),[o,c]=p.useState(null),[d,m]=p.useState(!1);p.useEffect(()=>{const v=sessionStorage.getItem("__logout_in_progress__"),w=sessionStorage.getItem("__force_logout__");if(v==="true"||w==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),tt.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(k){console.error("Error clearing storage:",k)}a(!1),l(null),n(!1),c(null);return}const C=new URLSearchParams(window.location.search);if(C.has("logout")||C.has("okta_logged_out")||C.has("tanflow_logged_out")){console.log("๐Ÿšช Logout parameter detected in URL, clearing all tokens"),tt.clearAll(),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state"),sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),sessionStorage.removeItem("tanflow_logged_out"),localStorage.clear(),a(!1),l(null),n(!1);const k=new URLSearchParams;C.has("okta_logged_out")&&k.set("okta_logged_out","true"),C.has("tanflow_logged_out")&&k.set("tanflow_logged_out","true");const S=k.toString()?`/?${k.toString()}`:"/";window.history.replaceState({},document.title,S);return}window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback"||(tt.getUserData(),d?n(!1):x())},[d]),p.useEffect(()=>{if(!s)return;const v=async()=>{try{await f()}catch(k){console.error("Silent refresh failed:",k)}},w=10*60*1e3,C=setInterval(v,w);return()=>clearInterval(C)},[s]);const h=p.useRef(!1);p.useEffect(()=>{if(h.current||window.location.pathname!=="/login/callback")return;(async()=>{const w=new URLSearchParams(window.location.search);if((w.has("logout")||w.has("tanflow_logged_out")||w.has("okta_logged_out"))&&!w.get("code")){console.log("๐Ÿšช Logout redirect detected in callback, redirecting to home");const _=new URLSearchParams;w.has("tanflow_logged_out")&&_.set("tanflow_logged_out","true"),w.has("okta_logged_out")&&_.set("okta_logged_out","true"),w.has("logout")&&_.set("logout",w.get("logout")||Date.now().toString());const D=_.toString()?`/?${_.toString()}`:"/?logout="+Date.now();window.location.replace(D);return}h.current=!0;const C=w.get("code"),k=w.get("error");if(window.history.replaceState({},document.title,"/login/callback"),sessionStorage.getItem("auth_provider")==="tanflow"){h.current=!1;return}if(k){c(new Error(`Authentication error: ${k}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!C){n(!1),sessionStorage.removeItem("auth_provider");return}try{n(!0),a(!1),c(null);const _=`${window.location.origin}/login/callback`,D=await ib(C,_);l(D.user),a(!0),c(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(_){console.error("โŒ Token exchange error in AuthContext:",_),c(_),a(!1),l(null),sessionStorage.removeItem("auth_provider"),h.current=!1}finally{n(!1)}})()},[]);const x=async()=>{var w;if(d){n(!1);return}const v=!0;try{if(n(!0),v){const S=tt.getUserData();try{const _=await sn();l(_),tt.setUserData(_),a(!0)}catch(_){if(((w=_==null?void 0:_.response)==null?void 0:w.status)===401)try{await f();const D=await sn();l(D),tt.setUserData(D),a(!0)}catch{tt.clearAll(),a(!1),l(null)}else _!=null&&_.isConnectionError?S?(l(S),a(!0)):(a(!1),l(null)):(tt.clearAll(),a(!1),l(null))}return}const C=tt.getAccessToken(),k=tt.getUserData();if(!C){a(!1),l(null),n(!1);return}if(Xi(C))try{await f();const S=tt.getAccessToken();if(S&&!Xi(S)){const _=tt.getUserData();if(_)l(_),a(!0);else try{const D=await sn();l(D),tt.setUserData(D),a(!0)}catch{tt.clearAll(),a(!1),l(null)}}else tt.clearAll(),a(!1),l(null)}catch{tt.clearAll(),a(!1),l(null)}else if(k)l(k),a(!0);else try{const S=await sn();l(S),tt.setUserData(S),a(!0)}catch{tt.clearAll(),a(!1),l(null)}}catch(C){console.error("Error checking auth status:",C),c(C),tt.clearAll(),a(!1),l(null)}finally{n(!1)}},u=async()=>{try{c(null);const v="https://dev-830839.oktapreview.co",w="0oa2jgzvrpdwx2iqd0h8",C=`${window.location.origin}/login/callback`,k="code",S="openid profile email",_=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const D=new URLSearchParams(window.location.search),A=D.has("logout")||D.has("okta_logged_out")||D.has("tanflow_logged_out");let N=`${v}/oauth2/default/v1/authorize?client_id=${w}&redirect_uri=${encodeURIComponent(C)}&response_type=${k}&scope=${encodeURIComponent(S)}&state=${_}`;A&&(N+="&prompt=login"),window.location.href=N}catch(v){throw c(v),v}},g=async()=>{try{const v=tt.getIdToken(),w=sessionStorage.getItem("auth_provider")||(v&&v.includes("tanflow")?"tanflow":null)||"okta";sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),m(!0),a(!1),l(null),c(null),n(!0);try{await ob(),console.log("๐Ÿšช Backend logout API called successfully")}catch(D){console.error("๐Ÿšช Logout API error:",D),console.warn("๐Ÿšช Backend logout failed - httpOnly cookies may not be cleared")}const C=sessionStorage.getItem("__logout_in_progress__"),k=sessionStorage.getItem("__force_logout__"),S=sessionStorage.getItem("auth_provider");if(tt.clearAll(),C&&sessionStorage.setItem("__logout_in_progress__",C),k&&sessionStorage.setItem("__force_logout__",k),v&&tt.setIdToken(v),S&&sessionStorage.setItem("auth_provider",S),await new Promise(D=>setTimeout(D,100)),w==="tanflow"&&v){console.log("๐Ÿšช Initiating Tanflow logout...");try{mb(v);return}catch(D){console.error("๐Ÿšช Tanflow logout error:",D)}}console.log("๐Ÿšช Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),v&&tt.clearAll();const _=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(_)}catch(v){console.error("๐Ÿšช Logout error:",v);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const w=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(w)}catch{window.location.replace("/?logout="+Date.now())}}},b=async()=>{{if(s)return"cookie-based-auth";try{return await f(),s?"cookie-based-auth":null}catch{return null}}const v=tt.getAccessToken();if(v&&!Xi(v))return v;try{return await f(),tt.getAccessToken()}catch{return null}},f=async()=>{try{const w=await lb();return}catch(w){throw tt.clearAll(),a(!1),l(null),w}},y={isAuthenticated:s,isLoading:r,user:i,error:o,login:u,logout:g,getAccessTokenSilently:b,refreshTokenSilently:f};return e.jsx(gx.Provider,{value:y,children:t})}function xb({children:t}){return e.jsx(ub,{children:t})}function Kt(){const t=p.useContext(gx);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function lr(t){return(t==null?void 0:t.role)==="ADMIN"}function Jr(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function ki(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const Md=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,$d=Ou,fx=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return $d(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,l=Object.keys(n).map(d=>{const m=a==null?void 0:a[d],h=i==null?void 0:i[d];if(m===null)return null;const x=Md(m)||Md(h);return n[d][x]}),o=a&&Object.entries(a).reduce((d,m)=>{let[h,x]=m;return x===void 0||(d[h]=x),d},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((d,m)=>{let{class:h,className:x,...u}=m;return Object.entries(u).every(g=>{let[b,f]=g;return Array.isArray(f)?f.includes({...i,...o}[b]):{...i,...o}[b]===f})?[...d,h,x]:d},[]);return $d(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},Co="-",hb=t=>{const s=gb(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(Co);return o[0]===""&&o.length!==1&&o.shift(),bx(o,s)||pb(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},bx=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?bx(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(Co);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Od=/^\[(.+)\]$/,pb=t=>{if(Od.test(t)){const s=Od.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},gb=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return bb(Object.entries(t.classGroups),a).forEach(([i,l])=>{Ll(l,r,i,s)}),r},Ll=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:Ud(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(fb(n)){Ll(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{Ll(l,Ud(s,i),a,r)})})},Ud=(t,s)=>{let a=t;return s.split(Co).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},fb=t=>t.isThemeGetter,bb=(t,s)=>s?t.map(([a,r])=>{const n=r.map(i=>typeof i=="string"?s+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([l,o])=>[s+l,o])):i);return[a,n]}):t,yb=t=>{if(t<1)return{get:()=>{},set:()=>{}};let s=0,a=new Map,r=new Map;const n=(i,l)=>{a.set(i,l),s++,s>t&&(s=0,r=a,a=new Map)};return{get(i){let l=a.get(i);if(l!==void 0)return l;if((l=r.get(i))!==void 0)return n(i,l),l},set(i,l){a.has(i)?a.set(i,l):n(i,l)}}},yx="!",vb=t=>{const{separator:s,experimentalParseClassName:a}=t,r=s.length===1,n=s[0],i=s.length,l=o=>{const c=[];let d=0,m=0,h;for(let f=0;fm?h-m:void 0;return{modifiers:c,hasImportantModifier:u,baseClassName:g,maybePostfixModifierPosition:b}};return a?o=>a({className:o,parseClassName:l}):l},jb=t=>{if(t.length<=1)return t;const s=[];let a=[];return t.forEach(r=>{r[0]==="["?(s.push(...a.sort(),r),a=[]):a.push(r)}),s.push(...a.sort()),s},Nb=t=>({cache:yb(t.cacheSize),parseClassName:vb(t),...hb(t)}),wb=/\s+/,Cb=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(wb);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:m,hasImportantModifier:h,baseClassName:x,maybePostfixModifierPosition:u}=a(d);let g=!!u,b=r(g?x.substring(0,u):x);if(!b){if(!g){o=d+(o.length>0?" "+o:o);continue}if(b=r(x),!b){o=d+(o.length>0?" "+o:o);continue}g=!1}const f=jb(m).join(":"),y=h?f+yx:f,v=y+b;if(i.includes(v))continue;i.push(v);const w=n(b,g);for(let C=0;C0?" "+o:o)}return o};function Sb(){let t=0,s,a,r="";for(;t{if(typeof t=="string")return t;let s,a="";for(let r=0;rh(m),t());return a=Nb(d),r=a.cache.get,n=a.cache.set,i=o,o(c)}function o(c){const d=r(c);if(d)return d;const m=Cb(c,a);return n(c,m),m}return function(){return i(Sb.apply(null,arguments))}}const Et=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},jx=/^\[(?:([a-z-]+):)?(.+)\]$/i,Tb=/^\d+\/\d+$/,kb=new Set(["px","full","screen"]),Rb=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Db=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Pb=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Ib=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Eb=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Sa=t=>Er(t)||kb.has(t)||Tb.test(t),$a=t=>Vr(t,"length",Bb),Er=t=>!!t&&!Number.isNaN(Number(t)),Zi=t=>Vr(t,"number",Er),Qr=t=>!!t&&Number.isInteger(Number(t)),Fb=t=>t.endsWith("%")&&Er(t.slice(0,-1)),it=t=>jx.test(t),Oa=t=>Rb.test(t),_b=new Set(["length","size","percentage"]),Lb=t=>Vr(t,_b,Nx),Mb=t=>Vr(t,"position",Nx),$b=new Set(["image","url"]),Ob=t=>Vr(t,$b,zb),Ub=t=>Vr(t,"",Vb),qr=()=>!0,Vr=(t,s,a)=>{const r=jx.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},Bb=t=>Db.test(t)&&!Pb.test(t),Nx=()=>!1,Vb=t=>Ib.test(t),zb=t=>Eb.test(t),Hb=()=>{const t=Et("colors"),s=Et("spacing"),a=Et("blur"),r=Et("brightness"),n=Et("borderColor"),i=Et("borderRadius"),l=Et("borderSpacing"),o=Et("borderWidth"),c=Et("contrast"),d=Et("grayscale"),m=Et("hueRotate"),h=Et("invert"),x=Et("gap"),u=Et("gradientColorStops"),g=Et("gradientColorStopPositions"),b=Et("inset"),f=Et("margin"),y=Et("opacity"),v=Et("padding"),w=Et("saturate"),C=Et("scale"),k=Et("sepia"),S=Et("skew"),_=Et("space"),D=Et("translate"),A=()=>["auto","contain","none"],N=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto",it,s],R=()=>[it,s],O=()=>["",Sa,$a],F=()=>["auto",Er,it],$=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],V=()=>["solid","dashed","dotted","double","none"],T=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],j=()=>["start","end","center","between","around","evenly","stretch"],U=()=>["","0",it],I=()=>["auto","avoid","all","avoid-page","page","left","right","column"],M=()=>[Er,it];return{cacheSize:500,separator:":",theme:{colors:[qr],spacing:[Sa,$a],blur:["none","",Oa,it],brightness:M(),borderColor:[t],borderRadius:["none","","full",Oa,it],borderSpacing:R(),borderWidth:O(),contrast:M(),grayscale:U(),hueRotate:M(),invert:U(),gap:R(),gradientColorStops:[t],gradientColorStopPositions:[Fb,$a],inset:P(),margin:P(),opacity:M(),padding:R(),saturate:M(),scale:M(),sepia:U(),skew:M(),space:R(),translate:R()},classGroups:{aspect:[{aspect:["auto","square","video",it]}],container:["container"],columns:[{columns:[Oa]}],"break-after":[{"break-after":I()}],"break-before":[{"break-before":I()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...$(),it]}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],overscroll:[{overscroll:A()}],"overscroll-x":[{"overscroll-x":A()}],"overscroll-y":[{"overscroll-y":A()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[b]}],"inset-x":[{"inset-x":[b]}],"inset-y":[{"inset-y":[b]}],start:[{start:[b]}],end:[{end:[b]}],top:[{top:[b]}],right:[{right:[b]}],bottom:[{bottom:[b]}],left:[{left:[b]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Qr,it]}],basis:[{basis:P()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",it]}],grow:[{grow:U()}],shrink:[{shrink:U()}],order:[{order:["first","last","none",Qr,it]}],"grid-cols":[{"grid-cols":[qr]}],"col-start-end":[{col:["auto",{span:["full",Qr,it]},it]}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":[qr]}],"row-start-end":[{row:["auto",{span:[Qr,it]},it]}],"row-start":[{"row-start":F()}],"row-end":[{"row-end":F()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",it]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",it]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...j()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...j(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...j(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[v]}],px:[{px:[v]}],py:[{py:[v]}],ps:[{ps:[v]}],pe:[{pe:[v]}],pt:[{pt:[v]}],pr:[{pr:[v]}],pb:[{pb:[v]}],pl:[{pl:[v]}],m:[{m:[f]}],mx:[{mx:[f]}],my:[{my:[f]}],ms:[{ms:[f]}],me:[{me:[f]}],mt:[{mt:[f]}],mr:[{mr:[f]}],mb:[{mb:[f]}],ml:[{ml:[f]}],"space-x":[{"space-x":[_]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[_]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",it,s]}],"min-w":[{"min-w":[it,s,"min","max","fit"]}],"max-w":[{"max-w":[it,s,"none","full","min","max","fit","prose",{screen:[Oa]},Oa]}],h:[{h:[it,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[it,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[it,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[it,s,"auto","min","max","fit"]}],"font-size":[{text:["base",Oa,$a]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Zi]}],"font-family":[{font:[qr]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",it]}],"line-clamp":[{"line-clamp":["none",Er,Zi]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Sa,it]}],"list-image":[{"list-image":["none",it]}],"list-style-type":[{list:["none","disc","decimal",it]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[y]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...V(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Sa,$a]}],"underline-offset":[{"underline-offset":["auto",Sa,it]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:R()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",it]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",it]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[y]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...$(),Mb]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Lb]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Ob]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[u]}],"gradient-via":[{via:[u]}],"gradient-to":[{to:[u]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[y]}],"border-style":[{border:[...V(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[y]}],"divide-style":[{divide:V()}],"border-color":[{border:[n]}],"border-color-x":[{"border-x":[n]}],"border-color-y":[{"border-y":[n]}],"border-color-s":[{"border-s":[n]}],"border-color-e":[{"border-e":[n]}],"border-color-t":[{"border-t":[n]}],"border-color-r":[{"border-r":[n]}],"border-color-b":[{"border-b":[n]}],"border-color-l":[{"border-l":[n]}],"divide-color":[{divide:[n]}],"outline-style":[{outline:["",...V()]}],"outline-offset":[{"outline-offset":[Sa,it]}],"outline-w":[{outline:[Sa,$a]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:O()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[y]}],"ring-offset-w":[{"ring-offset":[Sa,$a]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Oa,Ub]}],"shadow-color":[{shadow:[qr]}],opacity:[{opacity:[y]}],"mix-blend":[{"mix-blend":[...T(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":T()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Oa,it]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[h]}],saturate:[{saturate:[w]}],sepia:[{sepia:[k]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[h]}],"backdrop-opacity":[{"backdrop-opacity":[y]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[k]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[l]}],"border-spacing-x":[{"border-spacing-x":[l]}],"border-spacing-y":[{"border-spacing-y":[l]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",it]}],duration:[{duration:M()}],ease:[{ease:["linear","in","out","in-out",it]}],delay:[{delay:M()}],animate:[{animate:["none","spin","ping","pulse","bounce",it]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[C]}],"scale-x":[{"scale-x":[C]}],"scale-y":[{"scale-y":[C]}],rotate:[{rotate:[Qr,it]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[S]}],"skew-y":[{"skew-y":[S]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",it]}],accent:[{accent:["auto",t]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",it]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":R()}],"scroll-mx":[{"scroll-mx":R()}],"scroll-my":[{"scroll-my":R()}],"scroll-ms":[{"scroll-ms":R()}],"scroll-me":[{"scroll-me":R()}],"scroll-mt":[{"scroll-mt":R()}],"scroll-mr":[{"scroll-mr":R()}],"scroll-mb":[{"scroll-mb":R()}],"scroll-ml":[{"scroll-ml":R()}],"scroll-p":[{"scroll-p":R()}],"scroll-px":[{"scroll-px":R()}],"scroll-py":[{"scroll-py":R()}],"scroll-ps":[{"scroll-ps":R()}],"scroll-pe":[{"scroll-pe":R()}],"scroll-pt":[{"scroll-pt":R()}],"scroll-pr":[{"scroll-pr":R()}],"scroll-pb":[{"scroll-pb":R()}],"scroll-pl":[{"scroll-pl":R()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",it]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Sa,$a,Zi]}],stroke:[{stroke:[t,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},Wb=Ab(Hb);function ke(...t){return Wb(Ou(t))}const gn=fx("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background text-foreground hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),E=p.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?Ru:"button";return e.jsx(l,{"data-slot":"button",className:ke(gn({variant:s,size:a,className:t})),ref:i,...n})});E.displayName="Button";function ee({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:ke("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function ge({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:ke("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 pt-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",t),...s})}function fe({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:ke("leading-none",t),...s})}function $e({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:ke("text-muted-foreground",t),...s})}function se({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:ke("px-6 [&:last-child]:pb-6",t),...s})}const Ri="/assets/Re_Logo-By51taPS.png",Bd="/assets/landing_page_image-ClTD-4qZ.jpg";function Gb(){const{login:t,isLoading:s,error:a}=Kt(),[r,n]=p.useState(!1),[i,l]=p.useState(!1);p.useEffect(()=>{const d=new Image;d.src=Bd,d.onload=()=>{l(!0)},d.complete&&l(!0)},[]);const o=async()=>{localStorage.clear(),sessionStorage.clear();try{await t()}catch(d){console.error("========================================"),console.error("OKTA LOGIN ERROR"),console.error("Error details:",d),console.error("Error message:",d==null?void 0:d.message),console.error("Error stack:",d==null?void 0:d.stack),console.error("========================================")}},c=()=>{localStorage.clear(),sessionStorage.clear(),n(!0);try{cb()}catch(d){console.error("========================================"),console.error("TANFLOW LOGIN ERROR"),console.error("Error details:",d),n(!1)}};return a&&console.error("Auth Error in Auth Component:",{message:a.message,error:a}),e.jsxs("div",{className:"min-h-screen flex items-center justify-center p-4 relative",style:{backgroundImage:i?`url(${Bd})`:"none",backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transition:"background-image 0.3s ease-in-out"},children:[!i&&e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 to-slate-800"}),e.jsx("div",{className:"absolute inset-0 bg-black/40"}),e.jsxs(ee,{className:"w-full max-w-md shadow-xl relative z-10 bg-black backdrop-blur-sm border-gray-800",children:[e.jsx(ge,{className:"space-y-1 text-center pb-6",children:e.jsxs("div",{className:"flex flex-col items-center justify-center mb-4",children:[e.jsx("img",{src:Ri,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-300 text-center truncate",children:"Approval Portal"})]})}),e.jsxs(se,{className:"space-y-4",children:[a&&e.jsxs("div",{className:"bg-red-900/50 border border-red-700 text-red-200 px-4 py-3 rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium",children:"Authentication Error"}),e.jsx("p",{className:"text-sm",children:a.message})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(E,{onClick:o,disabled:s||r,className:"w-full h-12 text-base font-semibold bg-re-red hover:bg-re-red/90 text-white",size:"lg",children:s?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Logging in..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Bf,{className:"mr-2 h-5 w-5"}),"RE Employee Login"]})}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t border-gray-700"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-gray-900 px-2 text-gray-400",children:"Or"})})]}),e.jsx(E,{onClick:c,disabled:s||r,className:"w-full h-12 text-base font-semibold bg-indigo-600 hover:bg-indigo-700 text-white",size:"lg",children:r?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Redirecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hs,{className:"mr-2 h-5 w-5"}),"Dealer Login"]})})]}),e.jsxs("div",{className:"text-center text-sm text-gray-400 mt-4",children:[e.jsx("p",{children:"Secure Single Sign-On"}),e.jsx("p",{className:"text-xs mt-1 text-gray-500",children:"Choose your authentication provider"})]})]})]})]})}function wx(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Kt(),[n,i]=p.useState("exchanging");p.useEffect(()=>{if(a){i("error");return}if(s){const c=new URLSearchParams(window.location.search).get("code");i(c&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else r&&t&&i("complete")},[t,s,a,r]);const l=()=>{switch(n){case"exchanging":return"Exchanging authorization code...";case"fetching":return"Fetching your profile...";case"complete":return"Authentication successful!";case"error":return"Authentication failed";default:return"Completing authentication..."}};return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiMxZTIxMmQiIGZpbGwtb3BhY2l0eT0iMC4wNSI+PGNpcmNsZSBjeD0iMzAiIGN5PSIzMCIgcj0iMzAiLz48L2c+PC9nPjwvc3ZnPg==')] opacity-20"}),e.jsxs("div",{className:"relative z-10 text-center px-4 max-w-md w-full",children:[e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:Ri,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-400 text-center truncate",children:"Approval Portal"})]})}),e.jsxs("div",{className:"bg-white/10 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/20",children:[e.jsx("div",{className:"mb-6 flex justify-center",children:n==="error"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(ze,{className:"w-16 h-16 text-red-500"})}),e.jsx(ze,{className:"w-16 h-16 text-red-500 relative"})]}):n==="complete"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(Ls,{className:"w-16 h-16 text-green-500"})}),e.jsx(Ls,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(lt,{className:"w-16 h-16 animate-spin text-re-red"}),e.jsx("div",{className:"absolute inset-0 border-4 rounded-full border-re-red/20"}),e.jsx("div",{className:"absolute inset-0 border-4 border-transparent border-t-re-red rounded-full animate-spin"})]})}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-white mb-2",children:n==="complete"?"Welcome Back!":n==="error"?"Authentication Error":"Authenticating"}),e.jsx("p",{className:"text-slate-300 text-sm",children:l()})]}),n!=="error"&&e.jsxs("div",{className:"space-y-3 mb-6",children:[e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="exchanging"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="exchanging"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Validating credentials"})]}),e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="fetching"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="fetching"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Loading your profile"})]}),n==="complete"&&e.jsxs("div",{className:"flex items-center gap-3 text-sm transition-all duration-500 text-white",children:[e.jsx("div",{className:"w-2 h-2 rounded-full transition-all duration-500 bg-green-500"}),e.jsx("span",{children:"Setting up your session"})]})]}),n==="error"&&a&&e.jsxs("div",{className:"mt-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx("p",{className:"text-red-400 text-sm",children:a.message||"An error occurred during authentication"}),e.jsx("button",{onClick:()=>{window.location.href="/"},className:"mt-4 text-sm text-red-400 hover:text-red-300 underline",children:"Return to login"})]}),n!=="error"&&n!=="complete"&&e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"h-1.5 bg-slate-700/50 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-re-red rounded-full animate-pulse",style:{animation:"progress 2s ease-in-out infinite"}})}),e.jsx("style",{children:` +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conclusionApi-C_Bd1V1u.js","assets/radix-vendor-CYvDqP9X.js","assets/charts-vendor-BVfwAPj-.js","assets/utils-vendor-BTBPSQfW.js","assets/ui-vendor-BFJfF1vG.js","assets/socket-vendor-TjCxX7sJ.js","assets/redux-vendor-tbZCm13o.js","assets/router-vendor-B_rK4TXr.js"])))=>i.map(i=>d[i]); +var jg=Object.defineProperty;var Ng=(t,s,a)=>s in t?jg(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var Ui=(t,s,a)=>Ng(t,typeof s!="symbol"?s+"":s,a);import{j as e,S as Ru,R as Du,I as Pu,F as Iu,a as wg,T as Cg,P as Sg,C as Ag,b as Tg,O as Eu,c as Fu,d as kg,e as Rg,f as Dg,D as Pg,g as Ig,A as Eg,h as Fg,i as _g,k as Lg,l as Mg,m as $g,n as Og,V as Ug,o as Bg,p as Vg,q as zg,r as Hg,s as Wg,t as Gg,u as Yg,v as Kg,w as Xg,x as Zg,y as Jg,z as Qg,B as qg,E as ef,G as tf,H as sf,J as af,K as rf,L as nf,M as lf,N as of,Q as _u,U as Lu,W as cf,X as Mu,Y as $u,Z as df,_ as mf,$ as uf,a0 as xf,a1 as hf,a2 as pf,a3 as gf,a4 as ff,a5 as bf,a6 as yf,a7 as vf,a8 as jf,a9 as Nf,aa as wf,ab as Cf}from"./radix-vendor-CYvDqP9X.js";import{a as Sf,r as p,c as Ou,d as Pr,B as kl,C as ei,X as ti,Y as si,T as Ir,L as ai,e as fa,P as Uu,f as Bu,g as Vu,h as Af,i as Td,j as fi,k as bi,b as Tf}from"./charts-vendor-BVfwAPj-.js";import{a as no,f as zu,s as Vs,e as io,b as kd,c as kf,d as ja,g as hn,i as lo,h as Hu,j as _s,k as Us,l as Bi,m as ka,n as Rf,o as Rl,p as Df,q as He,r as Dl,t as Pf,u as If,v as Ef,w as Ff,x as Vi,y as Rd,z as _f,A as Wu,B as Gu,C as oo,D as co,E as Lf,F as Mf,G as Yu,H as wr,I as zi,J as $f,K as Of,L as Uf}from"./utils-vendor-BTBPSQfW.js";import{L as Bf,S as hs,C as ze,a as Ls,b as lt,X as ft,H as Vf,c as Ku,U as Vt,F as Re,d as De,e as wn,P as gs,f as zf,g as Hf,B as qs,h as Va,i as Hi,j as mo,k as uo,l as yr,m as Xu,n as yi,o as Zu,p as ot,q as Ya,R as $t,I as Ur,T as Ot,r as st,s as ha,t as Wf,A as ss,u as as,M as As,v as vi,w as kt,x as Pl,D as Ct,Z as xo,y as cs,z as Gf,E as Yf,G as Kf,J as Xf,K as Zf,N as Jf,O as Qf,Q as qf,V as e0,W as Ju,Y as t0,_ as s0,$ as Ra,a0 as ji,a1 as za,a2 as ri,a3 as Dd,a4 as _n,a5 as ni,a6 as Qu,a7 as wt,a8 as a0,a9 as K,aa as ta,ab as Ns,ac as qu,ad as Gt,ae as ex,af as ht,ag as r0,ah as n0,ai as tx,aj as Ni,ak as sx,al as i0,am as l0,an as ho,ao as zs,ap as Da,aq as wi,ar as Ci,as as Rs,at as o0,au as c0,av as ax,aw as d0,ax as Wn,ay as pn,az as po,aA as Si,aB as ii,aC as rx,aD as nx,aE as ix,aF as Ai,aG as Ti,aH as m0,aI as ln,aJ as lx,aK as Il,aL as u0,aM as x0,aN as h0,aO as go,aP as fo,aQ as bo,aR as p0,aS as Pd,aT as ox,aU as g0,aV as yo,aW as f0,aX as Ln,aY as b0,aZ as Id,a_ as y0,a$ as v0,b0 as j0}from"./ui-vendor-BFJfF1vG.js";import{l as N0}from"./socket-vendor-TjCxX7sJ.js";import{c as Br,a as w0}from"./redux-vendor-tbZCm13o.js";import{u as Ks,a as Ea,b as cx,B as C0,R as S0,c as Lt,O as A0}from"./router-vendor-B_rK4TXr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function a(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=a(n);fetch(n.href,i)}})();var El={},Ed=Sf;El.createRoot=Ed.createRoot,El.hydrateRoot=Ed.hydrateRoot;var dx={exports:{}},mx={};var Cn=p;function T0(t,s){return t===s&&(t!==0||1/t===1/s)||t!==t&&s!==s}var k0=typeof Object.is=="function"?Object.is:T0,R0=Cn.useSyncExternalStore,D0=Cn.useRef,P0=Cn.useEffect,I0=Cn.useMemo,E0=Cn.useDebugValue;mx.useSyncExternalStoreWithSelector=function(t,s,a,r,n){var i=D0(null);if(i.current===null){var l={hasValue:!1,value:null};i.current=l}else l=i.current;i=I0(function(){function c(u){if(!d){if(d=!0,m=u,u=r(u),n!==void 0&&l.hasValue){var g=l.value;if(n(g,u))return h=g}return h=u}if(g=h,k0(m,u))return g;var b=r(u);return n!==void 0&&n(g,b)?(m=u,g):(m=u,h=b)}var d=!1,m,h,x=a===void 0?null:a;return[function(){return c(s())},x===null?void 0:function(){return c(x())}]},[s,a,r,n]);var o=R0(t,i[0],i[1]);return P0(function(){l.hasValue=!0,l.value=o},[o]),E0(o),o};dx.exports=mx;var F0=dx.exports;function _0(t){t()}function L0(){let t=null,s=null;return{clear(){t=null,s=null},notify(){_0(()=>{let a=t;for(;a;)a.callback(),a=a.next})},get(){const a=[];let r=t;for(;r;)a.push(r),r=r.next;return a},subscribe(a){let r=!0;const n=s={callback:a,next:null,prev:s};return n.prev?n.prev.next=n:t=n,function(){!r||t===null||(r=!1,n.next?n.next.prev=n.prev:s=n.prev,n.prev?n.prev.next=n.next:t=n.next)}}}}var Fd={notify(){},get:()=>[]};function M0(t,s){let a,r=Fd,n=0,i=!1;function l(b){m();const f=r.subscribe(b);let y=!1;return()=>{y||(y=!0,f(),h())}}function o(){r.notify()}function c(){g.onStateChange&&g.onStateChange()}function d(){return i}function m(){n++,a||(a=t.subscribe(c),r=L0())}function h(){n--,a&&n===0&&(a(),a=void 0,r.clear(),r=Fd)}function x(){i||(i=!0,m())}function u(){i&&(i=!1,h())}const g={addNestedSub:l,notifyNestedSubs:o,handleChangeWrapper:c,isSubscribed:d,trySubscribe:x,tryUnsubscribe:u,getListeners:()=>r};return g}var $0=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",O0=$0(),U0=()=>typeof navigator<"u"&&navigator.product==="ReactNative",B0=U0(),V0=()=>O0||B0?p.useLayoutEffect:p.useEffect,z0=V0(),Wi=Symbol.for("react-redux-context"),Gi=typeof globalThis<"u"?globalThis:{};function H0(){if(!p.createContext)return{};const t=Gi[Wi]??(Gi[Wi]=new Map);let s=t.get(p.createContext);return s||(s=p.createContext(null),t.set(p.createContext,s)),s}var Ha=H0();function W0(t){const{children:s,context:a,serverState:r,store:n}=t,i=p.useMemo(()=>{const c=M0(n);return{store:n,subscription:c,getServerState:r?()=>r:void 0}},[n,r]),l=p.useMemo(()=>n.getState(),[n]);z0(()=>{const{subscription:c}=i;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),l!==n.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[i,l]);const o=a||Ha;return p.createElement(o.Provider,{value:i},s)}var G0=W0;function vo(t=Ha){return function(){return p.useContext(t)}}var ux=vo();function xx(t=Ha){const s=t===Ha?ux:vo(t),a=()=>{const{store:r}=s();return r};return Object.assign(a,{withTypes:()=>a}),a}var Y0=xx();function K0(t=Ha){const s=t===Ha?Y0:xx(t),a=()=>s().dispatch;return Object.assign(a,{withTypes:()=>a}),a}var X0=K0(),Z0=(t,s)=>t===s;function J0(t=Ha){const s=t===Ha?ux:vo(t),a=(r,n={})=>{const{equalityFn:i=Z0}=typeof n=="function"?{equalityFn:n}:n,l=s(),{store:o,subscription:c,getServerState:d}=l;p.useRef(!0);const m=p.useCallback({[r.name](x){return r(x)}}[r.name],[r]),h=F0.useSyncExternalStoreWithSelector(c.addNestedSub,o.getState,d||o.getState,m,i);return p.useDebugValue(h),h};return Object.assign(a,{withTypes:()=>a}),a}var Q0=J0(),Fl=function(t,s){return Fl=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,r){a.__proto__=r}||function(a,r){for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(a[n]=r[n])},Fl(t,s)};function q0(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");Fl(t,s);function a(){this.constructor=t}t.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)}var li=function(){return li=Object.assign||function(s){for(var a,r=1,n=arguments.length;r0&&g[g.length-1])||C[0]!==6&&C[0]!==2)){f=0;continue}if(C[0]===3&&(!g||C[1]>g[0]&&C[1]0?setTimeout(u,w):u(null)}}window.addEventListener("storage",y),m.addToWaiting(y);var v=setTimeout(y,Math.max(0,h-Date.now()))})];case 1:return x.sent(),[2]}})})},m.addToWaiting=function(h){this.removeFromWaiting(h),m.waiters!==void 0&&m.waiters.push(h)},m.removeFromWaiting=function(h){m.waiters!==void 0&&(m.waiters=m.waiters.filter(function(x){return x!==h}))},m.notifyWaiters=function(){m.waiters!==void 0&&m.waiters.slice().forEach(function(h){return h()})},m.prototype.releaseLock=function(h){return a(this,void 0,void 0,function(){return r(this,function(x){switch(x.label){case 0:return[4,this.releaseLock__private__(h)];case 1:return[2,x.sent()]}})})},m.prototype.releaseLock__private__=function(h){return a(this,void 0,void 0,function(){var x,u,g,b;return r(this,function(f){switch(f.label){case 0:return x=this.storageHandler===void 0?l:this.storageHandler,u=i+"-"+h,(g=x.getItemSync(u))===null?[2]:(b=JSON.parse(g)).id!==this.id?[3,2]:[4,ir.default().lock(b.iat)];case 1:f.sent(),this.acquiredIatSet.delete(b.iat),x.removeItemSync(u),ir.default().unlock(b.iat),m.notifyWaiters(),f.label=2;case 2:return[2]}})})},m.lockCorrector=function(h){for(var x=Date.now()-5e3,u=h,g=[],b=0;;){var f=u.keySync(b);if(f===null)break;g.push(f),b++}for(var y=!1,v=0;v.")},sb=li(li({},tb),{buildAuthorizeUrl:Es,buildLogoutUrl:Es,getAccessTokenSilently:Es,getAccessTokenWithPopup:Es,getIdTokenClaims:Es,loginWithRedirect:Es,loginWithPopup:Es,connectAccountWithRedirect:Es,logout:Es,handleRedirectCallback:Es,getDpopNonce:Es,setDpopNonce:Es,generateDpopProof:Es,createFetcher:Es}),ab=p.createContext(sb);(function(t){q0(s,t);function s(a,r){var n=t.call(this,r??a)||this;return n.error=a,n.error_description=r,Object.setPrototypeOf(n,s.prototype),n}return s})(Error);var rb=function(t){return t===void 0&&(t=ab),p.useContext(t)};const Yi="idToken",Ki="userData",nb=()=>!0;class tt{static setAccessToken(s){}static getAccessToken(){return null}static setRefreshToken(s){}static getRefreshToken(){return null}static setIdToken(s){sessionStorage.setItem(Yi,s)}static getIdToken(){return sessionStorage.getItem(Yi)}static setUserData(s){localStorage.setItem(Ki,JSON.stringify(s))}static getUserData(){const s=localStorage.getItem(Ki);if(!s)return null;try{return JSON.parse(s)}catch{return null}}static clearAll(){try{sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true")}catch(s){console.warn("Could not set logout flags:",s)}try{localStorage.removeItem(Ki),sessionStorage.removeItem(Yi)}catch(s){console.warn("Error clearing user data:",s)}{try{sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true")}catch{}return}}static hasAccessToken(){return!!this.getUserData()}static hasRefreshToken(){return!!this.getUserData()}static isLocalhost(){return window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"||window.location.hostname===""}static isProduction(){return nb()}}function Xi(t,s=5){if(!t)return!0;try{const a=t.split(".");if(a.length!==3||!a[1])return!0;const n=JSON.parse(atob(a[1])).exp*1e3,i=Date.now(),l=s*60*1e3;return n-it,t=>Promise.reject(t));je.interceptors.response.use(t=>t,async t=>{var a,r;const s=t.config;if(t.code==="ERR_NETWORK"||t.code==="ECONNREFUSED"||(a=t.message)!=null&&a.includes("ERR_CONNECTION_REFUSED"),((r=t.response)==null?void 0:r.status)===401&&!s._retry){s._retry=!0;const n=!0;try{const i=tt.getRefreshToken(),l=await no.post(`${hx}/auth/refresh`,n?{}:{refreshToken:i},{withCredentials:!0}),c=(l.data.data||l.data).accessToken;return je(s)}catch(i){return tt.clearAll(),window.location.href="/",Promise.reject(i)}}return Promise.reject(t)});async function ib(t,s){var a,r;try{const n=await je.post("/auth/token-exchange",{code:t,redirectUri:s},{responseType:"json",headers:{"Content-Type":"application/json",Accept:"application/json"}});if(Array.isArray(n.data))throw console.error("โŒ Response is an array (buffer issue):",{arrayLength:n.data.length,firstFew:n.data.slice(0,10),rawResponse:n}),new Error("Invalid response format: received array instead of JSON. Check Content-Type header.");const i=n.data,l=i.data||i;return l.user&&tt.setUserData(l.user),l.idToken&&tt.setIdToken(l.idToken),l.accessToken&&l.refreshToken&&(tt.setAccessToken(l.accessToken),tt.setRefreshToken(l.refreshToken)),l}catch(n){throw console.error("โŒ Token exchange failed:",{message:n.message,response:(a=n.response)==null?void 0:a.data,status:(r=n.response)==null?void 0:r.status,code:t?`${t.substring(0,10)}...`:"MISSING",redirectUri:s}),n}}async function lb(){var r;const t={},a=(await je.post("/auth/refresh",t)).data;if((r=a.data)!=null&&r.accessToken||a.accessToken,a.success!==!1)return"cookie-based-auth";throw new Error("Failed to refresh token")}async function sn(){const s=(await je.get("/auth/me")).data;return s.data||s}async function ob(){var t,s;try{await je.post("/auth/logout",{},{withCredentials:!0})}catch(a){console.error("๐Ÿ“ก Logout API error:",a),console.error("๐Ÿ“ก Error details:",{message:a.message,status:(t=a.response)==null?void 0:t.status,data:(s=a.response)==null?void 0:s.data})}}const _l="https://ssodev.rebridge.co.in/realms/RE",px="REFLOW",wo=`${window.location.origin}/login/callback`;function cb(){const t=new URLSearchParams(window.location.search),s=t.has("logout")||t.has("tanflow_logged_out");s&&(sessionStorage.removeItem("tanflow_logged_out"),sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),console.log("๐Ÿšช Cleared logout flags before initiating Tanflow login"));const a=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","tanflow"),sessionStorage.setItem("tanflow_auth_state",a);let r=`${_l}/protocol/openid-connect/auth?client_id=${px}&response_type=code&scope=openid&redirect_uri=${encodeURIComponent(wo)}&state=${a}`;s&&(r+="&prompt=login",console.log("๐Ÿšช Adding prompt=login to force re-authentication after logout")),console.log("๐Ÿšช Initiating Tanflow login",{isAfterLogout:s,hasPrompt:s}),window.location.href=r}async function db(t,s){var r,n,i;const a="https://reflow-uat.royalenfield.com/api/v1/";try{const l=await no.post(`${a}/auth/tanflow/token-exchange`,{code:t,redirectUri:wo,state:s},{withCredentials:!0,headers:{"Content-Type":"application/json"}}),o=((r=l.data)==null?void 0:r.data)||l.data;return o.accessToken&&tt.setAccessToken(o.accessToken),o.refreshToken&&tt.setRefreshToken(o.refreshToken),o.idToken&&tt.setIdToken(o.idToken),o.user&&tt.setUserData(o.user),o}catch(l){throw console.error("โŒ Tanflow token exchange failed:",{message:l.message,response:(n=l.response)==null?void 0:n.data,status:(i=l.response)==null?void 0:i.status}),l}}function mb(t){if(!t){console.warn("๐Ÿšช No id_token available for Tanflow logout, redirecting to home");const n=`${window.location.origin}/?tanflow_logged_out=true&logout=${Date.now()}`;window.location.replace(n);return}const s=wo,a=new URL(`${_l}/protocol/openid-connect/logout`);a.searchParams.set("client_id",px),a.searchParams.set("id_token_hint",t),a.searchParams.set("post_logout_redirect_uri",s);const r=a.toString();console.log("๐Ÿšช Tanflow logout initiated",{hasIdToken:!!t,idTokenPrefix:t?t.substring(0,20)+"...":"none",postLogoutRedirectUri:s,logoutUrlBase:`${_l}/protocol/openid-connect/logout`,finalLogoutUrl:r.replace(t.substring(0,20),"***")}),sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),console.log("๐Ÿšช Redirecting to Tanflow logout endpoint..."),window.location.href=r}const gx=p.createContext(void 0);function ub({children:t}){const[s,a]=p.useState(!1),[r,n]=p.useState(!0),[i,l]=p.useState(null),[o,c]=p.useState(null),[d,m]=p.useState(!1);p.useEffect(()=>{const v=sessionStorage.getItem("__logout_in_progress__"),w=sessionStorage.getItem("__force_logout__");if(v==="true"||w==="true"){sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),tt.clearAll();try{localStorage.clear(),sessionStorage.clear()}catch(k){console.error("Error clearing storage:",k)}a(!1),l(null),n(!1),c(null);return}const C=new URLSearchParams(window.location.search);if(C.has("logout")||C.has("okta_logged_out")||C.has("tanflow_logged_out")){console.log("๐Ÿšช Logout parameter detected in URL, clearing all tokens"),tt.clearAll(),sessionStorage.removeItem("auth_provider"),sessionStorage.removeItem("tanflow_auth_state"),sessionStorage.removeItem("__logout_in_progress__"),sessionStorage.removeItem("__force_logout__"),sessionStorage.removeItem("tanflow_logged_out"),localStorage.clear(),a(!1),l(null),n(!1);const k=new URLSearchParams;C.has("okta_logged_out")&&k.set("okta_logged_out","true"),C.has("tanflow_logged_out")&&k.set("tanflow_logged_out","true");const S=k.toString()?`/?${k.toString()}`:"/";window.history.replaceState({},document.title,S);return}window.location.pathname==="/login/callback"||window.location.pathname==="/login/tanflow/callback"||(tt.getUserData(),d?n(!1):x())},[d]),p.useEffect(()=>{if(!s)return;const v=async()=>{try{await f()}catch(k){console.error("Silent refresh failed:",k)}},w=10*60*1e3,C=setInterval(v,w);return()=>clearInterval(C)},[s]);const h=p.useRef(!1);p.useEffect(()=>{if(h.current||window.location.pathname!=="/login/callback")return;(async()=>{const w=new URLSearchParams(window.location.search);if((w.has("logout")||w.has("tanflow_logged_out")||w.has("okta_logged_out"))&&!w.get("code")){console.log("๐Ÿšช Logout redirect detected in callback, redirecting to home");const _=new URLSearchParams;w.has("tanflow_logged_out")&&_.set("tanflow_logged_out","true"),w.has("okta_logged_out")&&_.set("okta_logged_out","true"),w.has("logout")&&_.set("logout",w.get("logout")||Date.now().toString());const D=_.toString()?`/?${_.toString()}`:"/?logout="+Date.now();window.location.replace(D);return}h.current=!0;const C=w.get("code"),k=w.get("error");if(window.history.replaceState({},document.title,"/login/callback"),sessionStorage.getItem("auth_provider")==="tanflow"){h.current=!1;return}if(k){c(new Error(`Authentication error: ${k}`)),n(!1),sessionStorage.removeItem("auth_provider");return}if(!C){n(!1),sessionStorage.removeItem("auth_provider");return}try{n(!0),a(!1),c(null);const _=`${window.location.origin}/login/callback`,D=await ib(C,_);l(D.user),a(!0),c(null),sessionStorage.removeItem("auth_provider"),window.history.replaceState({},document.title,"/")}catch(_){console.error("โŒ Token exchange error in AuthContext:",_),c(_),a(!1),l(null),sessionStorage.removeItem("auth_provider"),h.current=!1}finally{n(!1)}})()},[]);const x=async()=>{var w;if(d){n(!1);return}const v=!0;try{if(n(!0),v){const S=tt.getUserData();try{const _=await sn();l(_),tt.setUserData(_),a(!0)}catch(_){if(((w=_==null?void 0:_.response)==null?void 0:w.status)===401)try{await f();const D=await sn();l(D),tt.setUserData(D),a(!0)}catch{tt.clearAll(),a(!1),l(null)}else _!=null&&_.isConnectionError?S?(l(S),a(!0)):(a(!1),l(null)):(tt.clearAll(),a(!1),l(null))}return}const C=tt.getAccessToken(),k=tt.getUserData();if(!C){a(!1),l(null),n(!1);return}if(Xi(C))try{await f();const S=tt.getAccessToken();if(S&&!Xi(S)){const _=tt.getUserData();if(_)l(_),a(!0);else try{const D=await sn();l(D),tt.setUserData(D),a(!0)}catch{tt.clearAll(),a(!1),l(null)}}else tt.clearAll(),a(!1),l(null)}catch{tt.clearAll(),a(!1),l(null)}else if(k)l(k),a(!0);else try{const S=await sn();l(S),tt.setUserData(S),a(!0)}catch{tt.clearAll(),a(!1),l(null)}}catch(C){console.error("Error checking auth status:",C),c(C),tt.clearAll(),a(!1),l(null)}finally{n(!1)}},u=async()=>{try{c(null);const v="https://dev-830839.oktapreview.com",w="0oa2jgzvrpdwx2iqd0h8",C=`${window.location.origin}/login/callback`,k="code",S="openid profile email",_=Math.random().toString(36).substring(7);sessionStorage.setItem("auth_provider","okta");const D=new URLSearchParams(window.location.search),A=D.has("logout")||D.has("okta_logged_out")||D.has("tanflow_logged_out");let N=`${v}/oauth2/default/v1/authorize?client_id=${w}&redirect_uri=${encodeURIComponent(C)}&response_type=${k}&scope=${encodeURIComponent(S)}&state=${_}`;A&&(N+="&prompt=login"),window.location.href=N}catch(v){throw c(v),v}},g=async()=>{try{const v=tt.getIdToken(),w=sessionStorage.getItem("auth_provider")||(v&&v.includes("tanflow")?"tanflow":null)||"okta";sessionStorage.setItem("__logout_in_progress__","true"),sessionStorage.setItem("__force_logout__","true"),m(!0),a(!1),l(null),c(null),n(!0);try{await ob(),console.log("๐Ÿšช Backend logout API called successfully")}catch(D){console.error("๐Ÿšช Logout API error:",D),console.warn("๐Ÿšช Backend logout failed - httpOnly cookies may not be cleared")}const C=sessionStorage.getItem("__logout_in_progress__"),k=sessionStorage.getItem("__force_logout__"),S=sessionStorage.getItem("auth_provider");if(tt.clearAll(),C&&sessionStorage.setItem("__logout_in_progress__",C),k&&sessionStorage.setItem("__force_logout__",k),v&&tt.setIdToken(v),S&&sessionStorage.setItem("auth_provider",S),await new Promise(D=>setTimeout(D,100)),w==="tanflow"&&v){console.log("๐Ÿšช Initiating Tanflow logout...");try{mb(v);return}catch(D){console.error("๐Ÿšช Tanflow logout error:",D)}}console.log("๐Ÿšช Using OKTA logout flow or fallback"),sessionStorage.removeItem("auth_provider"),v&&tt.clearAll();const _=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(_)}catch(v){console.error("๐Ÿšช Logout error:",v);try{localStorage.clear(),sessionStorage.clear(),sessionStorage.setItem("__logout_in_progress__","true");const w=`${window.location.origin}/?okta_logged_out=true&logout=${Date.now()}`;window.location.replace(w)}catch{window.location.replace("/?logout="+Date.now())}}},b=async()=>{{if(s)return"cookie-based-auth";try{return await f(),s?"cookie-based-auth":null}catch{return null}}const v=tt.getAccessToken();if(v&&!Xi(v))return v;try{return await f(),tt.getAccessToken()}catch{return null}},f=async()=>{try{const w=await lb();return}catch(w){throw tt.clearAll(),a(!1),l(null),w}},y={isAuthenticated:s,isLoading:r,user:i,error:o,login:u,logout:g,getAccessTokenSilently:b,refreshTokenSilently:f};return e.jsx(gx.Provider,{value:y,children:t})}function xb({children:t}){return e.jsx(ub,{children:t})}function Kt(){const t=p.useContext(gx);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function lr(t){return(t==null?void 0:t.role)==="ADMIN"}function Jr(t){return(t==null?void 0:t.role)==="MANAGEMENT"}function ki(t){return(t==null?void 0:t.role)==="MANAGEMENT"||(t==null?void 0:t.role)==="ADMIN"}const Md=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,$d=Ou,fx=(t,s)=>a=>{var r;if((s==null?void 0:s.variants)==null)return $d(t,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:n,defaultVariants:i}=s,l=Object.keys(n).map(d=>{const m=a==null?void 0:a[d],h=i==null?void 0:i[d];if(m===null)return null;const x=Md(m)||Md(h);return n[d][x]}),o=a&&Object.entries(a).reduce((d,m)=>{let[h,x]=m;return x===void 0||(d[h]=x),d},{}),c=s==null||(r=s.compoundVariants)===null||r===void 0?void 0:r.reduce((d,m)=>{let{class:h,className:x,...u}=m;return Object.entries(u).every(g=>{let[b,f]=g;return Array.isArray(f)?f.includes({...i,...o}[b]):{...i,...o}[b]===f})?[...d,h,x]:d},[]);return $d(t,l,c,a==null?void 0:a.class,a==null?void 0:a.className)},Co="-",hb=t=>{const s=gb(t),{conflictingClassGroups:a,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:l=>{const o=l.split(Co);return o[0]===""&&o.length!==1&&o.shift(),bx(o,s)||pb(l)},getConflictingClassGroupIds:(l,o)=>{const c=a[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},bx=(t,s)=>{var l;if(t.length===0)return s.classGroupId;const a=t[0],r=s.nextPart.get(a),n=r?bx(t.slice(1),r):void 0;if(n)return n;if(s.validators.length===0)return;const i=t.join(Co);return(l=s.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Od=/^\[(.+)\]$/,pb=t=>{if(Od.test(t)){const s=Od.exec(t)[1],a=s==null?void 0:s.substring(0,s.indexOf(":"));if(a)return"arbitrary.."+a}},gb=t=>{const{theme:s,prefix:a}=t,r={nextPart:new Map,validators:[]};return bb(Object.entries(t.classGroups),a).forEach(([i,l])=>{Ll(l,r,i,s)}),r},Ll=(t,s,a,r)=>{t.forEach(n=>{if(typeof n=="string"){const i=n===""?s:Ud(s,n);i.classGroupId=a;return}if(typeof n=="function"){if(fb(n)){Ll(n(r),s,a,r);return}s.validators.push({validator:n,classGroupId:a});return}Object.entries(n).forEach(([i,l])=>{Ll(l,Ud(s,i),a,r)})})},Ud=(t,s)=>{let a=t;return s.split(Co).forEach(r=>{a.nextPart.has(r)||a.nextPart.set(r,{nextPart:new Map,validators:[]}),a=a.nextPart.get(r)}),a},fb=t=>t.isThemeGetter,bb=(t,s)=>s?t.map(([a,r])=>{const n=r.map(i=>typeof i=="string"?s+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([l,o])=>[s+l,o])):i);return[a,n]}):t,yb=t=>{if(t<1)return{get:()=>{},set:()=>{}};let s=0,a=new Map,r=new Map;const n=(i,l)=>{a.set(i,l),s++,s>t&&(s=0,r=a,a=new Map)};return{get(i){let l=a.get(i);if(l!==void 0)return l;if((l=r.get(i))!==void 0)return n(i,l),l},set(i,l){a.has(i)?a.set(i,l):n(i,l)}}},yx="!",vb=t=>{const{separator:s,experimentalParseClassName:a}=t,r=s.length===1,n=s[0],i=s.length,l=o=>{const c=[];let d=0,m=0,h;for(let f=0;fm?h-m:void 0;return{modifiers:c,hasImportantModifier:u,baseClassName:g,maybePostfixModifierPosition:b}};return a?o=>a({className:o,parseClassName:l}):l},jb=t=>{if(t.length<=1)return t;const s=[];let a=[];return t.forEach(r=>{r[0]==="["?(s.push(...a.sort(),r),a=[]):a.push(r)}),s.push(...a.sort()),s},Nb=t=>({cache:yb(t.cacheSize),parseClassName:vb(t),...hb(t)}),wb=/\s+/,Cb=(t,s)=>{const{parseClassName:a,getClassGroupId:r,getConflictingClassGroupIds:n}=s,i=[],l=t.trim().split(wb);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:m,hasImportantModifier:h,baseClassName:x,maybePostfixModifierPosition:u}=a(d);let g=!!u,b=r(g?x.substring(0,u):x);if(!b){if(!g){o=d+(o.length>0?" "+o:o);continue}if(b=r(x),!b){o=d+(o.length>0?" "+o:o);continue}g=!1}const f=jb(m).join(":"),y=h?f+yx:f,v=y+b;if(i.includes(v))continue;i.push(v);const w=n(b,g);for(let C=0;C0?" "+o:o)}return o};function Sb(){let t=0,s,a,r="";for(;t{if(typeof t=="string")return t;let s,a="";for(let r=0;rh(m),t());return a=Nb(d),r=a.cache.get,n=a.cache.set,i=o,o(c)}function o(c){const d=r(c);if(d)return d;const m=Cb(c,a);return n(c,m),m}return function(){return i(Sb.apply(null,arguments))}}const Et=t=>{const s=a=>a[t]||[];return s.isThemeGetter=!0,s},jx=/^\[(?:([a-z-]+):)?(.+)\]$/i,Tb=/^\d+\/\d+$/,kb=new Set(["px","full","screen"]),Rb=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Db=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Pb=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Ib=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Eb=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Sa=t=>Er(t)||kb.has(t)||Tb.test(t),$a=t=>Vr(t,"length",Bb),Er=t=>!!t&&!Number.isNaN(Number(t)),Zi=t=>Vr(t,"number",Er),Qr=t=>!!t&&Number.isInteger(Number(t)),Fb=t=>t.endsWith("%")&&Er(t.slice(0,-1)),it=t=>jx.test(t),Oa=t=>Rb.test(t),_b=new Set(["length","size","percentage"]),Lb=t=>Vr(t,_b,Nx),Mb=t=>Vr(t,"position",Nx),$b=new Set(["image","url"]),Ob=t=>Vr(t,$b,zb),Ub=t=>Vr(t,"",Vb),qr=()=>!0,Vr=(t,s,a)=>{const r=jx.exec(t);return r?r[1]?typeof s=="string"?r[1]===s:s.has(r[1]):a(r[2]):!1},Bb=t=>Db.test(t)&&!Pb.test(t),Nx=()=>!1,Vb=t=>Ib.test(t),zb=t=>Eb.test(t),Hb=()=>{const t=Et("colors"),s=Et("spacing"),a=Et("blur"),r=Et("brightness"),n=Et("borderColor"),i=Et("borderRadius"),l=Et("borderSpacing"),o=Et("borderWidth"),c=Et("contrast"),d=Et("grayscale"),m=Et("hueRotate"),h=Et("invert"),x=Et("gap"),u=Et("gradientColorStops"),g=Et("gradientColorStopPositions"),b=Et("inset"),f=Et("margin"),y=Et("opacity"),v=Et("padding"),w=Et("saturate"),C=Et("scale"),k=Et("sepia"),S=Et("skew"),_=Et("space"),D=Et("translate"),A=()=>["auto","contain","none"],N=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto",it,s],R=()=>[it,s],O=()=>["",Sa,$a],F=()=>["auto",Er,it],$=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],V=()=>["solid","dashed","dotted","double","none"],T=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],j=()=>["start","end","center","between","around","evenly","stretch"],U=()=>["","0",it],I=()=>["auto","avoid","all","avoid-page","page","left","right","column"],M=()=>[Er,it];return{cacheSize:500,separator:":",theme:{colors:[qr],spacing:[Sa,$a],blur:["none","",Oa,it],brightness:M(),borderColor:[t],borderRadius:["none","","full",Oa,it],borderSpacing:R(),borderWidth:O(),contrast:M(),grayscale:U(),hueRotate:M(),invert:U(),gap:R(),gradientColorStops:[t],gradientColorStopPositions:[Fb,$a],inset:P(),margin:P(),opacity:M(),padding:R(),saturate:M(),scale:M(),sepia:U(),skew:M(),space:R(),translate:R()},classGroups:{aspect:[{aspect:["auto","square","video",it]}],container:["container"],columns:[{columns:[Oa]}],"break-after":[{"break-after":I()}],"break-before":[{"break-before":I()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...$(),it]}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],overscroll:[{overscroll:A()}],"overscroll-x":[{"overscroll-x":A()}],"overscroll-y":[{"overscroll-y":A()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[b]}],"inset-x":[{"inset-x":[b]}],"inset-y":[{"inset-y":[b]}],start:[{start:[b]}],end:[{end:[b]}],top:[{top:[b]}],right:[{right:[b]}],bottom:[{bottom:[b]}],left:[{left:[b]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Qr,it]}],basis:[{basis:P()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",it]}],grow:[{grow:U()}],shrink:[{shrink:U()}],order:[{order:["first","last","none",Qr,it]}],"grid-cols":[{"grid-cols":[qr]}],"col-start-end":[{col:["auto",{span:["full",Qr,it]},it]}],"col-start":[{"col-start":F()}],"col-end":[{"col-end":F()}],"grid-rows":[{"grid-rows":[qr]}],"row-start-end":[{row:["auto",{span:[Qr,it]},it]}],"row-start":[{"row-start":F()}],"row-end":[{"row-end":F()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",it]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",it]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...j()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...j(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...j(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[v]}],px:[{px:[v]}],py:[{py:[v]}],ps:[{ps:[v]}],pe:[{pe:[v]}],pt:[{pt:[v]}],pr:[{pr:[v]}],pb:[{pb:[v]}],pl:[{pl:[v]}],m:[{m:[f]}],mx:[{mx:[f]}],my:[{my:[f]}],ms:[{ms:[f]}],me:[{me:[f]}],mt:[{mt:[f]}],mr:[{mr:[f]}],mb:[{mb:[f]}],ml:[{ml:[f]}],"space-x":[{"space-x":[_]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[_]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",it,s]}],"min-w":[{"min-w":[it,s,"min","max","fit"]}],"max-w":[{"max-w":[it,s,"none","full","min","max","fit","prose",{screen:[Oa]},Oa]}],h:[{h:[it,s,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[it,s,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[it,s,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[it,s,"auto","min","max","fit"]}],"font-size":[{text:["base",Oa,$a]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Zi]}],"font-family":[{font:[qr]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",it]}],"line-clamp":[{"line-clamp":["none",Er,Zi]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Sa,it]}],"list-image":[{"list-image":["none",it]}],"list-style-type":[{list:["none","disc","decimal",it]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[y]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...V(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Sa,$a]}],"underline-offset":[{"underline-offset":["auto",Sa,it]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:R()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",it]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",it]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[y]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...$(),Mb]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Lb]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Ob]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[u]}],"gradient-via":[{via:[u]}],"gradient-to":[{to:[u]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[y]}],"border-style":[{border:[...V(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[y]}],"divide-style":[{divide:V()}],"border-color":[{border:[n]}],"border-color-x":[{"border-x":[n]}],"border-color-y":[{"border-y":[n]}],"border-color-s":[{"border-s":[n]}],"border-color-e":[{"border-e":[n]}],"border-color-t":[{"border-t":[n]}],"border-color-r":[{"border-r":[n]}],"border-color-b":[{"border-b":[n]}],"border-color-l":[{"border-l":[n]}],"divide-color":[{divide:[n]}],"outline-style":[{outline:["",...V()]}],"outline-offset":[{"outline-offset":[Sa,it]}],"outline-w":[{outline:[Sa,$a]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:O()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[y]}],"ring-offset-w":[{"ring-offset":[Sa,$a]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Oa,Ub]}],"shadow-color":[{shadow:[qr]}],opacity:[{opacity:[y]}],"mix-blend":[{"mix-blend":[...T(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":T()}],filter:[{filter:["","none"]}],blur:[{blur:[a]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Oa,it]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[h]}],saturate:[{saturate:[w]}],sepia:[{sepia:[k]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[a]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[h]}],"backdrop-opacity":[{"backdrop-opacity":[y]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[k]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[l]}],"border-spacing-x":[{"border-spacing-x":[l]}],"border-spacing-y":[{"border-spacing-y":[l]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",it]}],duration:[{duration:M()}],ease:[{ease:["linear","in","out","in-out",it]}],delay:[{delay:M()}],animate:[{animate:["none","spin","ping","pulse","bounce",it]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[C]}],"scale-x":[{"scale-x":[C]}],"scale-y":[{"scale-y":[C]}],rotate:[{rotate:[Qr,it]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[S]}],"skew-y":[{"skew-y":[S]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",it]}],accent:[{accent:["auto",t]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",it]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":R()}],"scroll-mx":[{"scroll-mx":R()}],"scroll-my":[{"scroll-my":R()}],"scroll-ms":[{"scroll-ms":R()}],"scroll-me":[{"scroll-me":R()}],"scroll-mt":[{"scroll-mt":R()}],"scroll-mr":[{"scroll-mr":R()}],"scroll-mb":[{"scroll-mb":R()}],"scroll-ml":[{"scroll-ml":R()}],"scroll-p":[{"scroll-p":R()}],"scroll-px":[{"scroll-px":R()}],"scroll-py":[{"scroll-py":R()}],"scroll-ps":[{"scroll-ps":R()}],"scroll-pe":[{"scroll-pe":R()}],"scroll-pt":[{"scroll-pt":R()}],"scroll-pr":[{"scroll-pr":R()}],"scroll-pb":[{"scroll-pb":R()}],"scroll-pl":[{"scroll-pl":R()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",it]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Sa,$a,Zi]}],stroke:[{stroke:[t,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},Wb=Ab(Hb);function ke(...t){return Wb(Ou(t))}const gn=fx("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background text-foreground hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),E=p.forwardRef(({className:t,variant:s,size:a,asChild:r=!1,...n},i)=>{const l=r?Ru:"button";return e.jsx(l,{"data-slot":"button",className:ke(gn({variant:s,size:a,className:t})),ref:i,...n})});E.displayName="Button";function ee({className:t,...s}){return e.jsx("div",{"data-slot":"card",className:ke("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",t),...s})}function ge({className:t,...s}){return e.jsx("div",{"data-slot":"card-header",className:ke("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 pt-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",t),...s})}function fe({className:t,...s}){return e.jsx("h4",{"data-slot":"card-title",className:ke("leading-none",t),...s})}function $e({className:t,...s}){return e.jsx("p",{"data-slot":"card-description",className:ke("text-muted-foreground",t),...s})}function se({className:t,...s}){return e.jsx("div",{"data-slot":"card-content",className:ke("px-6 [&:last-child]:pb-6",t),...s})}const Ri="/assets/Re_Logo-By51taPS.png",Bd="/assets/landing_page_image-ClTD-4qZ.jpg";function Gb(){const{login:t,isLoading:s,error:a}=Kt(),[r,n]=p.useState(!1),[i,l]=p.useState(!1);p.useEffect(()=>{const d=new Image;d.src=Bd,d.onload=()=>{l(!0)},d.complete&&l(!0)},[]);const o=async()=>{localStorage.clear(),sessionStorage.clear();try{await t()}catch(d){console.error("========================================"),console.error("OKTA LOGIN ERROR"),console.error("Error details:",d),console.error("Error message:",d==null?void 0:d.message),console.error("Error stack:",d==null?void 0:d.stack),console.error("========================================")}},c=()=>{localStorage.clear(),sessionStorage.clear(),n(!0);try{cb()}catch(d){console.error("========================================"),console.error("TANFLOW LOGIN ERROR"),console.error("Error details:",d),n(!1)}};return a&&console.error("Auth Error in Auth Component:",{message:a.message,error:a}),e.jsxs("div",{className:"min-h-screen flex items-center justify-center p-4 relative",style:{backgroundImage:i?`url(${Bd})`:"none",backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transition:"background-image 0.3s ease-in-out"},children:[!i&&e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-900 to-slate-800"}),e.jsx("div",{className:"absolute inset-0 bg-black/40"}),e.jsxs(ee,{className:"w-full max-w-md shadow-xl relative z-10 bg-black backdrop-blur-sm border-gray-800",children:[e.jsx(ge,{className:"space-y-1 text-center pb-6",children:e.jsxs("div",{className:"flex flex-col items-center justify-center mb-4",children:[e.jsx("img",{src:Ri,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-300 text-center truncate",children:"Approval Portal"})]})}),e.jsxs(se,{className:"space-y-4",children:[a&&e.jsxs("div",{className:"bg-red-900/50 border border-red-700 text-red-200 px-4 py-3 rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium",children:"Authentication Error"}),e.jsx("p",{className:"text-sm",children:a.message})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(E,{onClick:o,disabled:s||r,className:"w-full h-12 text-base font-semibold bg-re-red hover:bg-re-red/90 text-white",size:"lg",children:s?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Logging in..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Bf,{className:"mr-2 h-5 w-5"}),"RE Employee Login"]})}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t border-gray-700"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-gray-900 px-2 text-gray-400",children:"Or"})})]}),e.jsx(E,{onClick:c,disabled:s||r,className:"w-full h-12 text-base font-semibold bg-indigo-600 hover:bg-indigo-700 text-white",size:"lg",children:r?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Redirecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hs,{className:"mr-2 h-5 w-5"}),"Dealer Login"]})})]}),e.jsxs("div",{className:"text-center text-sm text-gray-400 mt-4",children:[e.jsx("p",{children:"Secure Single Sign-On"}),e.jsx("p",{className:"text-xs mt-1 text-gray-500",children:"Choose your authentication provider"})]})]})]})]})}function wx(){const{isAuthenticated:t,isLoading:s,error:a,user:r}=Kt(),[n,i]=p.useState("exchanging");p.useEffect(()=>{if(a){i("error");return}if(s){const c=new URLSearchParams(window.location.search).get("code");i(c&&!r?"exchanging":r&&!t?"fetching":"exchanging")}else r&&t&&i("complete")},[t,s,a,r]);const l=()=>{switch(n){case"exchanging":return"Exchanging authorization code...";case"fetching":return"Fetching your profile...";case"complete":return"Authentication successful!";case"error":return"Authentication failed";default:return"Completing authentication..."}};return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiMxZTIxMmQiIGZpbGwtb3BhY2l0eT0iMC4wNSI+PGNpcmNsZSBjeD0iMzAiIGN5PSIzMCIgcj0iMzAiLz48L2c+PC9nPjwvc3ZnPg==')] opacity-20"}),e.jsxs("div",{className:"relative z-10 text-center px-4 max-w-md w-full",children:[e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("img",{src:Ri,alt:"Royal Enfield Logo",className:"h-10 w-auto max-w-[168px] object-contain mb-2"}),e.jsx("p",{className:"text-xs text-gray-400 text-center truncate",children:"Approval Portal"})]})}),e.jsxs("div",{className:"bg-white/10 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/20",children:[e.jsx("div",{className:"mb-6 flex justify-center",children:n==="error"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(ze,{className:"w-16 h-16 text-red-500"})}),e.jsx(ze,{className:"w-16 h-16 text-red-500 relative"})]}):n==="complete"?e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-ping opacity-75",children:e.jsx(Ls,{className:"w-16 h-16 text-green-500"})}),e.jsx(Ls,{className:"w-16 h-16 text-green-500 relative"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(lt,{className:"w-16 h-16 animate-spin text-re-red"}),e.jsx("div",{className:"absolute inset-0 border-4 rounded-full border-re-red/20"}),e.jsx("div",{className:"absolute inset-0 border-4 border-transparent border-t-re-red rounded-full animate-spin"})]})}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-xl font-semibold text-white mb-2",children:n==="complete"?"Welcome Back!":n==="error"?"Authentication Error":"Authenticating"}),e.jsx("p",{className:"text-slate-300 text-sm",children:l()})]}),n!=="error"&&e.jsxs("div",{className:"space-y-3 mb-6",children:[e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="exchanging"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="exchanging"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Validating credentials"})]}),e.jsxs("div",{className:`flex items-center gap-3 text-sm transition-all duration-500 ${n==="fetching"?"text-white":"text-slate-400"}`,children:[e.jsx("div",{className:`w-2 h-2 rounded-full transition-all duration-500 ${n==="fetching"?"bg-re-red animate-pulse":"bg-slate-600"}`}),e.jsx("span",{children:"Loading your profile"})]}),n==="complete"&&e.jsxs("div",{className:"flex items-center gap-3 text-sm transition-all duration-500 text-white",children:[e.jsx("div",{className:"w-2 h-2 rounded-full transition-all duration-500 bg-green-500"}),e.jsx("span",{children:"Setting up your session"})]})]}),n==="error"&&a&&e.jsxs("div",{className:"mt-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg",children:[e.jsx("p",{className:"text-red-400 text-sm",children:a.message||"An error occurred during authentication"}),e.jsx("button",{onClick:()=>{window.location.href="/"},className:"mt-4 text-sm text-red-400 hover:text-red-300 underline",children:"Return to login"})]}),n!=="error"&&n!=="complete"&&e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"h-1.5 bg-slate-700/50 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-re-red rounded-full animate-pulse",style:{animation:"progress 2s ease-in-out infinite"}})}),e.jsx("style",{children:` @keyframes progress { 0%, 100% { width: 20%; } 50% { width: 80%; } @@ -33,7 +33,7 @@ var jg=Object.defineProperty;var Ng=(t,s,a)=>s in t?jg(t,s,{enumerable:!0,config ${g}px !important; top: ${h}px !important; } - `),()=>{f.contains(b)&&f.removeChild(b)}},[s]),e.jsx(u1,{isPresent:s,childRef:i,sizeRef:l,children:p.cloneElement(t,{ref:c})})}const h1=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=_o(p1),m=p.useId();let h=!0,x=p.useMemo(()=>(h=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:u=>{d.set(u,!0);for(const g of d.values())if(!g)return;r&&r()},register:u=>(d.set(u,!1),()=>d.delete(u))}),[a,d,r]);return i&&h&&(x={...x}),p.useMemo(()=>{d.forEach((u,g)=>d.set(g,!1))},[a]),p.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(x1,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(Ii.Provider,{value:x,children:t})};function p1(){return new Map}function Vh(t=!0){const s=p.useContext(Ii);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=p.useId();p.useEffect(()=>{if(t)return n(i)},[t]);const l=p.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const Un=t=>t.key||"";function ym(t){const s=[];return p.Children.forEach(t,a=>{p.isValidElement(a)&&s.push(a)}),s}const Ei=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",root:c})=>{const[d,m]=Vh(l),h=p.useMemo(()=>ym(t),[t]),x=l&&!d?[]:h.map(Un),u=p.useRef(!0),g=p.useRef(h),b=_o(()=>new Map),[f,y]=p.useState(h),[v,w]=p.useState(h);Jx(()=>{u.current=!1,g.current=h;for(let S=0;S{const _=Un(S),D=l&&!d?!1:h===v||x.includes(_),A=()=>{if(b.has(_))b.set(_,!0);else return;let N=!0;b.forEach(P=>{P||(N=!1)}),N&&(k==null||k(),w(g.current),l&&(m==null||m()),r&&r())};return e.jsx(h1,{isPresent:D,initial:!u.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:D?void 0:A,anchorX:o,children:S},_)})})},zh=p.createContext({strict:!1}),vm={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},$r={};for(const t in vm)$r[t]={isEnabled:s=>vm[t].some(a=>!!s[a])};function g1(t){for(const s in t)$r[s]={...$r[s],...t[s]}}const f1=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function ui(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||f1.has(t)}let Hh=t=>!ui(t);function b1(t){typeof t=="function"&&(Hh=s=>s.startsWith("on")?!ui(s):t(s))}try{b1(require("@emotion/is-prop-valid").default)}catch{}function y1(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(Hh(n)||a===!0&&ui(n)||!s&&!ui(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Fi=p.createContext({});function _i(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function vn(t){return typeof t=="string"||Array.isArray(t)}const nc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ic=["initial",...nc];function Li(t){return _i(t.animate)||ic.some(s=>vn(t[s]))}function Wh(t){return!!(Li(t)||t.variants)}function v1(t,s){if(Li(t)){const{initial:a,animate:r}=t;return{initial:a===!1||vn(a)?a:void 0,animate:vn(r)?r:void 0}}return t.inherit!==!1?s:{}}function j1(t){const{initial:s,animate:a}=v1(t,p.useContext(Fi));return p.useMemo(()=>({initial:s,animate:a}),[jm(s),jm(a)])}function jm(t){return Array.isArray(t)?t.join(" "):t}const jn={};function N1(t){for(const s in t)jn[s]=t[s],Ho(s)&&(jn[s].isCSSVariable=!0)}function Gh(t,{layout:s,layoutId:a}){return Yr.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!jn[t]||t==="opacity")}const w1={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},C1=Gr.length;function S1(t,s,a){let r="",n=!0;for(let i=0;i({style:{},transform:{},transformOrigin:{},vars:{}});function Yh(t,s,a){for(const r in s)!js(s[r])&&!Gh(r,a)&&(t[r]=s[r])}function A1({transformTemplate:t},s){return p.useMemo(()=>{const a=oc();return lc(a,s,t),Object.assign({},a.vars,a.style)},[s])}function T1(t,s){const a=t.style||{},r={};return Yh(r,a,t),Object.assign(r,A1(t,s)),r}function k1(t,s){const a={},r=T1(t,s);return t.drag&&t.dragListener!==!1&&(a.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(a.tabIndex=0),a.style=r,a}const R1={offset:"stroke-dashoffset",array:"stroke-dasharray"},D1={offset:"strokeDashoffset",array:"strokeDasharray"};function P1(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?R1:D1;t[i.offset]=Je.transform(-r);const l=Je.transform(s),o=Je.transform(a);t[i.array]=`${l} ${o}`}function Kh(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(lc(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:h,style:x}=t;h.transform&&(x.transform=h.transform,delete h.transform),(x.transform||h.transformOrigin)&&(x.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),x.transform&&(x.transformBox=(m==null?void 0:m.transformBox)??"fill-box",delete h.transformBox),s!==void 0&&(h.x=s),a!==void 0&&(h.y=a),r!==void 0&&(h.scale=r),n!==void 0&&P1(h,n,i,l,!1)}const Xh=()=>({...oc(),attrs:{}}),Zh=t=>typeof t=="string"&&t.toLowerCase()==="svg";function I1(t,s,a,r){const n=p.useMemo(()=>{const i=Xh();return Kh(i,s,Zh(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};Yh(i,t.style,t),n.style={...i,...n.style}}return n}const E1=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function cc(t){return typeof t!="string"||t.includes("-")?!1:!!(E1.indexOf(t)>-1||/[A-Z]/u.test(t))}function F1(t,s,a,{latestValues:r},n,i=!1){const o=(cc(t)?I1:k1)(s,r,n,t),c=y1(s,typeof t=="string",i),d=t!==p.Fragment?{...c,...o,ref:a}:{},{children:m}=s,h=p.useMemo(()=>js(m)?m.get():m,[m]);return p.createElement(t,{...d,children:h})}function Nm(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function dc(t,s,a,r){if(typeof s=="function"){const[n,i]=Nm(r);s=s(a!==void 0?a:t.custom,n,i)}if(typeof s=="string"&&(s=t.variants&&t.variants[s]),typeof s=="function"){const[n,i]=Nm(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Jn(t){return js(t)?t.get():t}function _1({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:L1(a,r,n,t),renderState:s()}}function L1(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=Jn(i[x]);let{initial:l,animate:o}=t;const c=Li(t),d=Wh(t);s&&d&&!c&&t.inherit!==!1&&(l===void 0&&(l=s.initial),o===void 0&&(o=s.animate));let m=a?a.initial===!1:!1;m=m||l===!1;const h=m?o:l;if(h&&typeof h!="boolean"&&!_i(h)){const x=Array.isArray(h)?h:[h];for(let u=0;u(s,a)=>{const r=p.useContext(Fi),n=p.useContext(Ii),i=()=>_1(t,s,r,n);return a?i():_o(i)};function mc(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(js(r[l])||s.style&&js(s.style[l])||Gh(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const M1=Jh({scrapeMotionValuesFromProps:mc,createRenderState:oc});function Qh(t,s,a){const r=mc(t,s,a);for(const n in t)if(js(t[n])||js(s[n])){const i=Gr.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const $1=Jh({scrapeMotionValuesFromProps:Qh,createRenderState:Xh}),O1=Symbol.for("motionComponentSymbol");function Tr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function U1(t,s,a){return p.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):Tr(a)&&(a.current=r))},[s])}const uc=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),B1="framerAppearId",qh="data-"+uc(B1),ep=p.createContext({});function V1(t,s,a,r,n){var b,f;const{visualElement:i}=p.useContext(Fi),l=p.useContext(zh),o=p.useContext(Ii),c=p.useContext(rc).reducedMotion,d=p.useRef(null);r=r||l.renderer,!d.current&&r&&(d.current=r(t,{visualState:s,parent:i,props:a,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:c}));const m=d.current,h=p.useContext(ep);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&z1(d.current,a,n,h);const x=p.useRef(!1);p.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const u=a[qh],g=p.useRef(!!u&&!((b=window.MotionHandoffIsComplete)!=null&&b.call(window,u))&&((f=window.MotionHasOptimisedAnimation)==null?void 0:f.call(window,u)));return Jx(()=>{m&&(x.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),p.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,u)}),g.current=!1),m.enteringChildren=void 0)}),m}function z1(t,s,a,r){const{layoutId:n,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:tp(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&Tr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function tp(t){if(t)return t.options.allowProjection!==!1?t.projection:tp(t.parent)}function ul(t,{forwardMotionProps:s=!1}={},a,r){a&&g1(a);const n=cc(t)?$1:M1;function i(o,c){let d;const m={...p.useContext(rc),...o,layoutId:H1(o)},{isStatic:h}=m,x=j1(o),u=n(o,h);if(!h&&Lo){W1();const g=G1(m);d=g.MeasureLayout,x.visualElement=V1(t,u,m,r,g.ProjectionNode)}return e.jsxs(Fi.Provider,{value:x,children:[d&&x.visualElement?e.jsx(d,{visualElement:x.visualElement,...m}):null,F1(t,o,U1(u,x.visualElement,c),u,h,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=p.forwardRef(i);return l[O1]=t,l}function H1({layoutId:t}){const s=p.useContext(Fo).id;return s&&t!==void 0?s+"-"+t:t}function W1(t,s){p.useContext(zh).strict}function G1(t){const{drag:s,layout:a}=$r;if(!s&&!a)return{};const r={...s,...a};return{MeasureLayout:s!=null&&s.isEnabled(t)||a!=null&&a.isEnabled(t)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function Y1(t,s){if(typeof Proxy>"u")return ul;const a=new Map,r=(i,l)=>ul(i,l,t,s),n=(i,l)=>r(i,l);return new Proxy(n,{get:(i,l)=>l==="create"?r:(a.has(l)||a.set(l,ul(l,void 0,t,s)),a.get(l))})}function sp({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function K1({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function X1(t,s){if(!s)return t;const a=s({x:t.left,y:t.top}),r=s({x:t.right,y:t.bottom});return{top:a.y,left:a.x,bottom:r.y,right:r.x}}function xl(t){return t===void 0||t===1}function Jl({scale:t,scaleX:s,scaleY:a}){return!xl(t)||!xl(s)||!xl(a)}function or(t){return Jl(t)||ap(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function ap(t){return wm(t.x)||wm(t.y)}function wm(t){return t&&t!=="0%"}function xi(t,s,a){const r=t-a,n=s*r;return a+n}function Cm(t,s,a,r,n){return n!==void 0&&(t=xi(t,n,r)),xi(t,a,r)+s}function Ql(t,s=0,a=1,r,n){t.min=Cm(t.min,s,a,r,n),t.max=Cm(t.max,s,a,r,n)}function rp(t,{x:s,y:a}){Ql(t.x,s.translate,s.scale,s.originPoint),Ql(t.y,a.translate,a.scale,a.originPoint)}const Sm=.999999999999,Am=1.0000000000001;function Z1(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,l;for(let o=0;oSm&&(s.x=1),s.ySm&&(s.y=1)}function kr(t,s){t.min=t.min+s,t.max=t.max+s}function Tm(t,s,a,r,n=.5){const i=zt(t.min,t.max,n);Ql(t,s,a,i,r)}function Rr(t,s){Tm(t.x,s.x,s.scaleX,s.scale,s.originX),Tm(t.y,s.y,s.scaleY,s.scale,s.originY)}function np(t,s){return sp(X1(t.getBoundingClientRect(),s))}function J1(t,s,a){const r=np(t,a),{scroll:n}=s;return n&&(kr(r.x,n.offset.x),kr(r.y,n.offset.y)),r}const km=()=>({translate:0,scale:1,origin:0,originPoint:0}),Dr=()=>({x:km(),y:km()}),Rm=()=>({min:0,max:0}),Yt=()=>({x:Rm(),y:Rm()}),ql={current:null},ip={current:!1};function Q1(){if(ip.current=!0,!!Lo)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>ql.current=t.matches;t.addEventListener("change",s),s()}else ql.current=!1}const q1=new WeakMap;function eC(t,s,a){for(const r in s){const n=s[r],i=a[r];if(js(n))t.addValue(r,n);else if(js(i))t.addValue(r,Mr(n,{owner:t}));else if(i!==n)if(t.hasValue(r)){const l=t.getValue(r);l.liveStyle===!0?l.jump(n):l.hasAnimated||l.set(n)}else{const l=t.getStaticValue(r);t.addValue(r,Mr(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Dm=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class tC{scrapeMotionValuesFromProps(s,a,r){return{}}constructor({parent:s,props:a,presenceContext:r,reducedMotionConfig:n,blockInitialAnimation:i,visualState:l},o={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=qo,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const x=$s.now();this.renderScheduledAtthis.bindToMotionValue(n,r)),ip.current||Q1(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ql.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),Wa(this.notifyUpdate),Wa(this.render),this.valueSubscriptions.forEach(a=>a()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(s=this.parent)==null||s.removeChild(this);for(const a in this.events)this.events[a].clear();for(const a in this.features){const r=this.features[a];r&&(r.unmount(),r.isMounted=!1)}this.current=null}addChild(s){this.children.add(s),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(s)}removeChild(s){this.children.delete(s),this.enteringChildren&&this.enteringChildren.delete(s)}bindToMotionValue(s,a){this.valueSubscriptions.has(s)&&this.valueSubscriptions.get(s)();const r=Yr.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&Mt.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,s,a)),this.valueSubscriptions.set(s,()=>{n(),i&&i(),a.owner&&a.stop()})}sortNodePosition(s){return!this.current||!this.sortInstanceNodePosition||this.type!==s.type?0:this.sortInstanceNodePosition(this.current,s.current)}updateFeatures(){let s="animation";for(s in $r){const a=$r[s];if(!a)continue;const{isEnabled:r,Feature:n}=a;if(!this.features[s]&&n&&r(this.props)&&(this.features[s]=new n(this)),this.features[s]){const i=this.features[s];i.isMounted?i.update():(i.mount(),i.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):Yt()}getStaticValue(s){return this.latestValues[s]}setStaticValue(s,a){this.latestValues[s]=a}update(s,a){(s.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=s,this.prevPresenceContext=this.presenceContext,this.presenceContext=a;for(let r=0;ra.variantChildren.delete(s)}addValue(s,a){const r=this.values.get(s);a!==r&&(r&&this.removeValue(s),this.bindToMotionValue(s,a),this.values.set(s,a),this.latestValues[s]=a.get())}removeValue(s){this.values.delete(s);const a=this.valueSubscriptions.get(s);a&&(a(),this.valueSubscriptions.delete(s)),delete this.latestValues[s],this.removeValueFromRenderState(s,this.renderState)}hasValue(s){return this.values.has(s)}getValue(s,a){if(this.props.values&&this.props.values[s])return this.props.values[s];let r=this.values.get(s);return r===void 0&&a!==void 0&&(r=Mr(a===null?void 0:a,{owner:this}),this.addValue(s,r)),r}readValue(s,a){let r=this.latestValues[s]!==void 0||!this.current?this.latestValues[s]:this.getBaseTargetFromProps(this.props,s)??this.readValueFromInstance(this.current,s,this.options);return r!=null&&(typeof r=="string"&&(Qx(r)||eh(r))?r=parseFloat(r):!c1(r)&&Ga.test(a)&&(r=_h(s,a)),this.setBaseTarget(s,js(r)?r.get():r)),js(r)?r.get():r}setBaseTarget(s,a){this.baseTarget[s]=a}getBaseTarget(s){var i;const{initial:a}=this.props;let r;if(typeof a=="string"||typeof a=="object"){const l=dc(this.props,a,(i=this.presenceContext)==null?void 0:i.custom);l&&(r=l[s])}if(a&&r!==void 0)return r;const n=this.getBaseTargetFromProps(this.props,s);return n!==void 0&&!js(n)?n:this.initialValues[s]!==void 0&&r===void 0?void 0:this.baseTarget[s]}on(s,a){return this.events[s]||(this.events[s]=new Bo),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){sc.render(this.render)}}class lp extends tC{constructor(){super(...arguments),this.KeyframeResolver=Jw}sortInstanceNodePosition(s,a){return s.compareDocumentPosition(a)&2?1:-1}getBaseTargetFromProps(s,a){return s.style?s.style[a]:void 0}removeValueFromRenderState(s,{vars:a,style:r}){delete a[s],delete r[s]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:s}=this.props;js(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function op(t,{style:s,vars:a},r,n){const i=t.style;let l;for(l in s)i[l]=s[l];n==null||n.applyProjectionStyles(i,r);for(l in a)i.setProperty(l,a[l])}function sC(t){return window.getComputedStyle(t)}class aC extends lp{constructor(){super(...arguments),this.type="html",this.renderInstance=op}readValueFromInstance(s,a){var r;if(Yr.has(a))return(r=this.projection)!=null&&r.isProjecting?Hl(a):gw(s,a);{const n=sC(s),i=(Ho(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return np(s,a)}build(s,a,r){lc(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return mc(s,a,r)}}const cp=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function rC(t,s,a,r){op(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(cp.has(n)?n:uc(n),s.attrs[n])}class nC extends lp{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Yt}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Yr.has(a)){const r=Fh(a);return r&&r.default||0}return a=cp.has(a)?a:uc(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return Qh(s,a,r)}build(s,a,r){Kh(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){rC(s,a,r,n)}mount(s){this.isSVGTag=Zh(s.tagName),super.mount(s)}}const iC=(t,s)=>cc(t)?new nC(s):new aC(s,{allowProjection:t!==p.Fragment});function _r(t,s,a){const r=t.getProps();return dc(r,s,a!==void 0?a:r.custom,t)}const eo=t=>Array.isArray(t);function lC(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,Mr(a))}function oC(t){return eo(t)?t[t.length-1]||0:t}function cC(t,s){const a=_r(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=oC(i[l]);lC(t,l,o)}}function dC(t){return!!(js(t)&&t.add)}function to(t,s){const a=t.getValue("willChange");if(dC(a))return a.add(s);if(!a&&Ia.WillChange){const r=new Ia.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function dp(t){return t.props[qh]}const mC=t=>t!==null;function uC(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(mC),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const xC={type:"spring",stiffness:500,damping:25,restSpeed:10},hC=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),pC={type:"keyframes",duration:.8},gC={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},fC=(t,{keyframes:s})=>s.length>2?pC:Yr.has(t)?t.startsWith("scale")?hC(s[1]):xC:gC;function bC({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:l,repeatDelay:o,from:c,elapsed:d,...m}){return!!Object.keys(m).length}const xc=(t,s,a,r={},n,i)=>l=>{const o=ec(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-ya(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-d,onUpdate:x=>{s.set(x),o.onUpdate&&o.onUpdate(x)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:t,motionValue:s,element:i?void 0:n};bC(o)||Object.assign(m,fC(t,m)),m.duration&&(m.duration=ya(m.duration)),m.repeatDelay&&(m.repeatDelay=ya(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let h=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(Xl(m),m.delay===0&&(h=!0)),(Ia.instantAnimations||Ia.skipAnimations)&&(h=!0,Xl(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,h&&!i&&s.get()!==void 0){const x=uC(m.keyframes,o);if(x!==void 0){Mt.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new Qo(m):new Ow(m)};function yC({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function mp(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in o){const h=t.getValue(m,t.latestValues[m]??null),x=o[m];if(x===void 0||d&&yC(d,m))continue;const u={delay:a,...ec(i||{},m)},g=h.get();if(g!==void 0&&!h.isAnimating&&!Array.isArray(x)&&x===g&&!u.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const y=dp(t);if(y){const v=window.MotionHandoffAnimation(y,m,Mt);v!==null&&(u.startTime=v,b=!0)}}to(t,m),h.start(xc(m,h,x,t.shouldReduceMotion&&Ph.has(m)?{type:!1}:u,t,b));const f=h.animation;f&&c.push(f)}return l&&Promise.all(c).then(()=>{Mt.update(()=>{l&&cC(t,l)})}),c}function up(t,s,a,r=0,n=1){const i=Array.from(t).sort((d,m)=>d.sortNodePosition(m)).indexOf(s),l=t.size,o=(l-1)*r;return typeof a=="function"?a(i,l):n===1?i*r:o-i*r}function so(t,s,a={}){var c;const r=_r(t,s,a.type==="exit"?(c=t.presenceContext)==null?void 0:c.custom:void 0);let{transition:n=t.getDefaultTransition()||{}}=r||{};a.transitionOverride&&(n=a.transitionOverride);const i=r?()=>Promise.all(mp(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:h,staggerDirection:x}=n;return vC(t,s,d,m,h,x,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[d,m]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function vC(t,s,a=0,r=0,n=0,i=1,l){const o=[];for(const c of t.variantChildren)c.notify("AnimationStart",s),o.push(so(c,s,{...l,delay:a+(typeof r=="function"?0:r)+up(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function jC(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>so(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=so(t,s,a);else{const n=typeof s=="function"?_r(t,s,a.custom):s;r=Promise.all(mp(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function xp(t,s){if(!Array.isArray(s))return!1;const a=s.length;if(a!==t.length)return!1;for(let r=0;rPromise.all(s.map(({animation:a,options:r})=>jC(t,a,r)))}function AC(t){let s=SC(t),a=Pm(),r=!0;const n=c=>(d,m)=>{var x;const h=_r(t,m,c==="exit"?(x=t.presenceContext)==null?void 0:x.custom:void 0);if(h){const{transition:u,transitionEnd:g,...b}=h;d={...d,...b,...g}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=hp(t.parent)||{},h=[],x=new Set;let u={},g=1/0;for(let f=0;fg&&C,A=!1;const N=Array.isArray(w)?w:[w];let P=N.reduce(n(y),{});k===!1&&(P={});const{prevResolvedValues:R={}}=v,O={...R,...P},F=T=>{D=!0,x.has(T)&&(A=!0,x.delete(T)),v.needsAnimating[T]=!0;const j=t.getValue(T);j&&(j.liveStyle=!1)};for(const T in O){const j=P[T],U=R[T];if(u.hasOwnProperty(T))continue;let I=!1;eo(j)&&eo(U)?I=!xp(j,U):I=j!==U,I?j!=null?F(T):x.add(T):j!==void 0&&x.has(T)?F(T):v.protectedKeys[T]=!0}v.prevProp=w,v.prevResolvedValues=P,v.isActive&&(u={...u,...P}),r&&t.blockInitialAnimation&&(D=!1);const $=S&&_;D&&(!$||A)&&h.push(...N.map(T=>{const j={type:y};if(typeof T=="string"&&r&&!$&&t.manuallyAnimateOnMount&&t.parent){const{parent:U}=t,I=_r(U,T);if(U.enteringChildren&&I){const{delayChildren:M}=I.transition||{};j.delay=up(U.enteringChildren,t,M)}}return{animation:T,options:j}}))}if(x.size){const f={};if(typeof d.initial!="boolean"){const y=_r(t,Array.isArray(d.initial)?d.initial[0]:d.initial);y&&y.transition&&(f.transition=y.transition)}x.forEach(y=>{const v=t.getBaseTarget(y),w=t.getValue(y);w&&(w.liveStyle=!0),f[y]=v??null}),h.push({animation:f})}let b=!!h.length;return r&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(b=!1),r=!1,b?s(h):Promise.resolve()}function o(c,d){var h;if(a[c].isActive===d)return Promise.resolve();(h=t.variantChildren)==null||h.forEach(x=>{var u;return(u=x.animationState)==null?void 0:u.setActive(c,d)}),a[c].isActive=d;const m=l(c);for(const x in a)a[x].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=Pm()}}}function TC(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!xp(s,t):!1}function nr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Pm(){return{animate:nr(!0),whileInView:nr(),whileHover:nr(),whileTap:nr(),whileDrag:nr(),whileFocus:nr(),exit:nr()}}class Ka{constructor(s){this.isMounted=!1,this.node=s}update(){}}class kC extends Ka{constructor(s){super(s),s.animationState||(s.animationState=AC(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();_i(s)&&(this.unmountControls=s.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:s}=this.node.getProps(),{animate:a}=this.node.prevProps||{};s!==a&&this.updateAnimationControlsSubscription()}unmount(){var s;this.node.animationState.reset(),(s=this.unmountControls)==null||s.call(this)}}let RC=0;class DC extends Ka{constructor(){super(...arguments),this.id=RC++}update(){if(!this.node.presenceContext)return;const{isPresent:s,onExitComplete:a}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||s===r)return;const n=this.node.animationState.setActive("exit",!s);a&&!s&&n.then(()=>{a(this.id)})}mount(){const{register:s,onExitComplete:a}=this.node.presenceContext||{};a&&a(this.id),s&&(this.unmount=s(this.id))}unmount(){}}const PC={animation:{Feature:kC},exit:{Feature:DC}};function Nn(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function En(t){return{point:{x:t.pageX,y:t.pageY}}}const IC=t=>s=>ac(s)&&t(s,En(s));function mn(t,s,a,r){return Nn(t,s,IC(a),r)}const pp=1e-4,EC=1-pp,FC=1+pp,gp=.01,_C=0-gp,LC=0+gp;function Ss(t){return t.max-t.min}function MC(t,s,a){return Math.abs(t-s)<=a}function Im(t,s,a,r=.5){t.origin=r,t.originPoint=zt(s.min,s.max,t.origin),t.scale=Ss(a)/Ss(s),t.translate=zt(a.min,a.max,t.origin)-t.originPoint,(t.scale>=EC&&t.scale<=FC||isNaN(t.scale))&&(t.scale=1),(t.translate>=_C&&t.translate<=LC||isNaN(t.translate))&&(t.translate=0)}function un(t,s,a,r){Im(t.x,s.x,a.x,r?r.originX:void 0),Im(t.y,s.y,a.y,r?r.originY:void 0)}function Em(t,s,a){t.min=a.min+s.min,t.max=t.min+Ss(s)}function $C(t,s,a){Em(t.x,s.x,a.x),Em(t.y,s.y,a.y)}function Fm(t,s,a){t.min=s.min-a.min,t.max=t.min+Ss(s)}function xn(t,s,a){Fm(t.x,s.x,a.x),Fm(t.y,s.y,a.y)}function Qs(t){return[t("x"),t("y")]}const fp=({current:t})=>t?t.ownerDocument.defaultView:null,_m=(t,s)=>Math.abs(t-s);function OC(t,s){const a=_m(t.x,s.x),r=_m(t.y,s.y);return Math.sqrt(a**2+r**2)}class bp{constructor(s,a,{transformPagePoint:r,contextWindow:n=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const x=pl(this.lastMoveEventInfo,this.history),u=this.startEvent!==null,g=OC(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!u&&!g)return;const{point:b}=x,{timestamp:f}=xs;this.history.push({...b,timestamp:f});const{onStart:y,onMove:v}=this.handlers;u||(y&&y(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,x)},this.handlePointerMove=(x,u)=>{this.lastMoveEvent=x,this.lastMoveEventInfo=hl(u,this.transformPagePoint),Mt.update(this.updatePoint,!0)},this.handlePointerUp=(x,u)=>{this.end();const{onEnd:g,onSessionEnd:b,resumeAnimation:f}=this.handlers;if(this.dragSnapToOrigin&&f&&f(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=pl(x.type==="pointercancel"?this.lastMoveEventInfo:hl(u,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,y),b&&b(x,y)},!ac(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=En(s),c=hl(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=xs;this.history=[{...d,timestamp:m}];const{onSessionStart:h}=a;h&&h(s,pl(c,this.history)),this.removeListeners=Dn(mn(this.contextWindow,"pointermove",this.handlePointerMove),mn(this.contextWindow,"pointerup",this.handlePointerUp),mn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),Wa(this.updatePoint)}}function hl(t,s){return s?{point:s(t.point)}:t}function Lm(t,s){return{x:t.x-s.x,y:t.y-s.y}}function pl({point:t},s){return{point:t,delta:Lm(t,yp(s)),offset:Lm(t,UC(s)),velocity:BC(s,.1)}}function UC(t){return t[0]}function yp(t){return t[t.length-1]}function BC(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=yp(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>ya(s)));)a--;if(!r)return{x:0,y:0};const i=ea(n.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const l={x:(n.x-r.x)/i,y:(n.y-r.y)/i};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function VC(t,{min:s,max:a},r){return s!==void 0&&ta&&(t=r?zt(a,t,r.max):Math.min(t,a)),t}function Mm(t,s,a){return{min:s!==void 0?t.min+s:void 0,max:a!==void 0?t.max+a-(t.max-t.min):void 0}}function zC(t,{top:s,left:a,bottom:r,right:n}){return{x:Mm(t.x,a,n),y:Mm(t.y,s,r)}}function $m(t,s){let a=s.min-t.min,r=s.max-t.max;return s.max-s.minr?a=fn(s.min,s.max-r,t.min):r>n&&(a=fn(t.min,t.max-n,s.min)),Pa(0,1,a)}function GC(t,s){const a={};return s.min!==void 0&&(a.min=s.min-t.min),s.max!==void 0&&(a.max=s.max-t.min),a}const ao=.35;function YC(t=ao){return t===!1?t=0:t===!0&&(t=ao),{x:Om(t,"left","right"),y:Om(t,"top","bottom")}}function Om(t,s,a){return{min:Um(t,s),max:Um(t,a)}}function Um(t,s){return typeof t=="number"?t:t[s]||0}const KC=new WeakMap;class XC{constructor(s){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Yt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:a=!1,distanceThreshold:r}={}){const{presenceContext:n}=this.visualElement;if(n&&n.isPresent===!1)return;const i=h=>{const{dragSnapToOrigin:x}=this.getProps();x?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(En(h).point)},l=(h,x)=>{const{drag:u,dragPropagation:g,onDragStart:b}=this.getProps();if(u&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=t1(u),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=x,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Qs(y=>{let v=this.getAxisMotionValue(y).get()||0;if(va.test(v)){const{projection:w}=this.visualElement;if(w&&w.layout){const C=w.layout.layoutBox[y];C&&(v=Ss(C)*(parseFloat(v)/100))}}this.originPoint[y]=v}),b&&Mt.postRender(()=>b(h,x)),to(this.visualElement,"transform");const{animationState:f}=this.visualElement;f&&f.setActive("whileDrag",!0)},o=(h,x)=>{this.latestPointerEvent=h,this.latestPanInfo=x;const{dragPropagation:u,dragDirectionLock:g,onDirectionLock:b,onDrag:f}=this.getProps();if(!u&&!this.openDragLock)return;const{offset:y}=x;if(g&&this.currentDirection===null){this.currentDirection=ZC(y),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",x.point,y),this.updateAxis("y",x.point,y),this.visualElement.render(),f&&f(h,x)},c=(h,x)=>{this.latestPointerEvent=h,this.latestPanInfo=x,this.stop(h,x),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>Qs(h=>{var x;return this.getAnimationState(h)==="paused"&&((x=this.getAxisMotionValue(h).animation)==null?void 0:x.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new bp(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:fp(this.visualElement)})}stop(s,a){const r=s||this.latestPointerEvent,n=a||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!n||!r)return;const{velocity:l}=n;this.startAnimation(l);const{onDragEnd:o}=this.getProps();o&&Mt.postRender(()=>o(r,n))}cancel(){this.isDragging=!1;const{projection:s,animationState:a}=this.visualElement;s&&(s.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),a&&a.setActive("whileDrag",!1)}updateAxis(s,a,r){const{drag:n}=this.getProps();if(!r||!Bn(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=VC(l,this.constraints[s],this.elastic[s])),i.set(l)}resolveConstraints(){var i;const{dragConstraints:s,dragElastic:a}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(i=this.visualElement.projection)==null?void 0:i.layout,n=this.constraints;s&&Tr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=zC(r.layoutBox,s):this.constraints=!1,this.elastic=YC(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&Qs(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=GC(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!Tr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=J1(r,n.root,this.visualElement.getTransformPagePoint());let l=HC(n.layout.layoutBox,i);if(a){const o=a(K1(l));this.hasMutatedConstraints=!!o,o&&(l=sp(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=Qs(m=>{if(!Bn(m,a,this.currentDirection))return;let h=c&&c[m]||{};l&&(h={min:0,max:0});const x=n?200:1e6,u=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:x,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return to(this.visualElement,s),r.start(xc(s,r,0,a,this.visualElement,!1))}stopAnimation(){Qs(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Qs(s=>{var a;return(a=this.getAxisMotionValue(s).animation)==null?void 0:a.pause()})}getAnimationState(s){var a;return(a=this.getAxisMotionValue(s).animation)==null?void 0:a.state}getAxisMotionValue(s){const a=`_drag${s.toUpperCase()}`,r=this.visualElement.getProps(),n=r[a];return n||this.visualElement.getValue(s,(r.initial?r.initial[s]:void 0)||0)}snapToCursor(s){Qs(a=>{const{drag:r}=this.getProps();if(!Bn(a,r,this.currentDirection))return;const{projection:n}=this.visualElement,i=this.getAxisMotionValue(a);if(n&&n.layout){const{min:l,max:o}=n.layout.layoutBox[a];i.set(s[a]-zt(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!Tr(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};Qs(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=WC({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),Qs(l=>{if(!Bn(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(zt(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;KC.set(this.visualElement,this);const s=this.visualElement.current,a=mn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();Tr(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,i=n.addEventListener("measure",r);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),Mt.read(r);const l=Nn(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(Qs(m=>{const h=this.getAxisMotionValue(m);h&&(this.originPoint[m]+=c[m].translate,h.set(h.get()+c[m].translate))}),this.visualElement.render())});return()=>{l(),a(),i(),o&&o()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:l=ao,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Bn(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function ZC(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class JC extends Ka{constructor(s){super(s),this.removeGroupControls=aa,this.removeListeners=aa,this.controls=new XC(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||aa}unmount(){this.removeGroupControls(),this.removeListeners()}}const Bm=t=>(s,a)=>{t&&Mt.postRender(()=>t(s,a))};class QC extends Ka{constructor(){super(...arguments),this.removePointerDownListener=aa}onPointerDown(s){this.session=new bp(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:fp(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Bm(s),onStart:Bm(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&Mt.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=mn(this.node.current,"pointerdown",s=>this.onPointerDown(s))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const Qn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Vm(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const en={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(Je.test(t))t=parseFloat(t);else return t;const a=Vm(t,s.target.x),r=Vm(t,s.target.y);return`${a}% ${r}%`}},qC={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=Ga.parse(t);if(n.length>5)return r;const i=Ga.createTransformer(t),l=typeof n[0]!="number"?1:0,o=a.x.scale*s.x,c=a.y.scale*s.y;n[0+l]/=o,n[1+l]/=c;const d=zt(o,c,.5);return typeof n[2+l]=="number"&&(n[2+l]/=d),typeof n[3+l]=="number"&&(n[3+l]/=d),i(n)}};let gl=!1;class e2 extends p.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;N1(t2),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),gl&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Qn.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,gl=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||Mt.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),sc.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;gl=!0,n&&(n.scheduleCheckAfterUnmount(),a&&a.group&&a.group.remove(n),r&&r.deregister&&r.deregister(n))}safeToRemove(){const{safeToRemove:s}=this.props;s&&s()}render(){return null}}function vp(t){const[s,a]=Vh(),r=p.useContext(Fo);return e.jsx(e2,{...t,layoutGroup:r,switchLayoutGroup:p.useContext(ep),isPresent:s,safeToRemove:a})}const t2={borderRadius:{...en,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:en,borderTopRightRadius:en,borderBottomLeftRadius:en,borderBottomRightRadius:en,boxShadow:qC};function s2(t,s,a){const r=js(t)?t:Mr(t);return r.start(xc("",r,s,a)),r.animation}const a2=(t,s)=>t.depth-s.depth;class r2{constructor(){this.children=[],this.isDirty=!1}add(s){Mo(this.children,s),this.isDirty=!0}remove(s){$o(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(a2),this.isDirty=!1,this.children.forEach(s)}}function n2(t,s){const a=$s.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(Wa(r),t(i-s))};return Mt.setup(r,!0),()=>Wa(r)}const jp=["TopLeft","TopRight","BottomLeft","BottomRight"],i2=jp.length,zm=t=>typeof t=="string"?parseFloat(t):t,Hm=t=>typeof t=="number"||Je.test(t);function l2(t,s,a,r,n,i){n?(t.opacity=zt(0,a.opacity??1,o2(r)),t.opacityExit=zt(s.opacity??1,0,c2(r))):i&&(t.opacity=zt(s.opacity??1,a.opacity??1,r));for(let l=0;lrs?1:a(fn(t,s,r))}function Gm(t,s){t.min=s.min,t.max=s.max}function Js(t,s){Gm(t.x,s.x),Gm(t.y,s.y)}function Ym(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function Km(t,s,a,r,n){return t-=s,t=xi(t,1/a,r),n!==void 0&&(t=xi(t,1/n,r)),t}function d2(t,s=0,a=1,r=.5,n,i=t,l=t){if(va.test(s)&&(s=parseFloat(s),s=zt(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=zt(i.min,i.max,r);t===i&&(o-=s),t.min=Km(t.min,s,a,o,n),t.max=Km(t.max,s,a,o,n)}function Xm(t,s,[a,r,n],i,l){d2(t,s[a],s[r],s[n],s.scale,i,l)}const m2=["x","scaleX","originX"],u2=["y","scaleY","originY"];function Zm(t,s,a,r){Xm(t.x,s,m2,a?a.x:void 0,r?r.x:void 0),Xm(t.y,s,u2,a?a.y:void 0,r?r.y:void 0)}function Jm(t){return t.translate===0&&t.scale===1}function wp(t){return Jm(t.x)&&Jm(t.y)}function Qm(t,s){return t.min===s.min&&t.max===s.max}function x2(t,s){return Qm(t.x,s.x)&&Qm(t.y,s.y)}function qm(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function Cp(t,s){return qm(t.x,s.x)&&qm(t.y,s.y)}function eu(t){return Ss(t.x)/Ss(t.y)}function tu(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class h2{constructor(){this.members=[]}add(s){Mo(this.members,s),s.scheduleRender()}remove(s){if($o(this.members,s),s===this.prevLead&&(this.prevLead=void 0),s===this.lead){const a=this.members[this.members.length-1];a&&this.promote(a)}}relegate(s){const a=this.members.findIndex(n=>s===n);if(a===0)return!1;let r;for(let n=a;n>=0;n--){const i=this.members[n];if(i.isPresent!==!1){r=i;break}}return r?(this.promote(r),!0):!1}promote(s,a){const r=this.lead;if(s!==r&&(this.prevLead=r,this.lead=s,s.show(),r)){r.instance&&r.scheduleRender(),s.scheduleRender(),s.resumeFrom=r,a&&(s.resumeFrom.preserveOpacity=!0),r.snapshot&&(s.snapshot=r.snapshot,s.snapshot.latestValues=r.animationValues||r.latestValues),s.root&&s.root.isUpdating&&(s.isLayoutDirty=!0);const{crossfade:n}=s.options;n===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(s=>{const{options:a,resumingFrom:r}=s;a.onExitComplete&&a.onExitComplete(),r&&r.options.onExitComplete&&r.options.onExitComplete()})}scheduleRender(){this.members.forEach(s=>{s.instance&&s.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function p2(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,l=(a==null?void 0:a.z)||0;if((n||i||l)&&(r=`translate3d(${n}px, ${i}px, ${l}px) `),(s.x!==1||s.y!==1)&&(r+=`scale(${1/s.x}, ${1/s.y}) `),a){const{transformPerspective:d,rotate:m,rotateX:h,rotateY:x,skewX:u,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),h&&(r+=`rotateX(${h}deg) `),x&&(r+=`rotateY(${x}deg) `),u&&(r+=`skewX(${u}deg) `),g&&(r+=`skewY(${g}deg) `)}const o=t.x.scale*s.x,c=t.y.scale*s.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const fl=["","X","Y","Z"],g2=1e3;let f2=0;function bl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Sp(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=dp(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",Mt,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Sp(r)}function Ap({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=f2++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(v2),this.nodes.forEach(C2),this.nodes.forEach(S2),this.nodes.forEach(j2)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=l,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let c=0;cthis.root.updateBlockedByResize=!1;Mt.read(()=>{h=window.innerWidth}),t(l,()=>{const u=window.innerWidth;u!==h&&(h=u,this.root.updateBlockedByResize=!0,m&&m(),m=n2(x,250),Qn.hasAnimatedSinceResize&&(Qn.hasAnimatedSinceResize=!1,this.nodes.forEach(ru)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:h,hasRelativeLayoutChanged:x,layout:u})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||D2,{onLayoutAnimationStart:b,onLayoutAnimationComplete:f}=d.getProps(),y=!this.targetLayout||!Cp(this.targetLayout,u),v=!h&&x;if(this.options.layoutRoot||this.resumeFrom||v||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...ec(g,"layout"),onPlay:b,onComplete:f};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(m,v)}else h||ru(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=u})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Wa(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(A2),this.animationId++)}getTransformTemplate(){const{visualElement:l}=this.options;return l&&l.getProps().transformTemplate}willUpdate(l=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Sp(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let m=0;m{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ss(this.snapshot.measuredBox.x)&&!Ss(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c{const k=C/1e3;nu(h.x,l.x,k),nu(h.y,l.y,k),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(xn(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),k2(this.relativeTarget,this.relativeTargetOrigin,x,k),w&&x2(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=Yt()),Js(w,this.relativeTarget)),b&&(this.animationValues=m,l2(m,d,this.latestValues,k,v,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=k},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(Wa(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Mt.update(()=>{Qn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Mr(0)),this.currentAnimation=s2(this.motionValue,[0,1e3],{...l,velocity:0,isSync:!0,onUpdate:m=>{this.mixTargetDelta(m),l.onUpdate&&l.onUpdate(m)},onStop:()=>{},onComplete:()=>{l.onComplete&&l.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const l=this.getStack();l&&l.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(g2),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:m}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&Tp(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Yt();const h=Ss(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const x=Ss(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+x}Js(o,c),Rr(o,m),un(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new h2),this.sharedNodes.get(l).add(o);const d=o.options.initialPromotionConfig;o.promote({transition:d?d.transition:void 0,preserveFollowOpacity:d&&d.shouldPreserveFollowOpacity?d.shouldPreserveFollowOpacity(o):void 0})}isLead(){const l=this.getStack();return l?l.lead===this:!0}getLead(){var o;const{layoutId:l}=this.options;return l?((o=this.getStack())==null?void 0:o.lead)||this:this}getPrevLead(){var o;const{layoutId:l}=this.options;return l?(o=this.getStack())==null?void 0:o.prevLead:void 0}getStack(){const{layoutId:l}=this.options;if(l)return this.root.sharedNodes.get(l)}promote({needsReset:l,transition:o,preserveFollowOpacity:c}={}){const d=this.getStack();d&&d.promote(this,c),l&&(this.projectionDelta=void 0,this.needsReset=!0),o&&this.setOptions({transition:o})}relegate(){const l=this.getStack();return l?l.relegate(this):!1}resetSkewAndRotation(){const{visualElement:l}=this.options;if(!l)return;let o=!1;const{latestValues:c}=l;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(o=!0),!o)return;const d={};c.z&&bl("z",l,d,this.animationValues);for(let m=0;m{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(su),this.root.sharedNodes.clear()}}}function b2(t){t.updateLayout()}function y2(t){var a;const s=((a=t.resumeFrom)==null?void 0:a.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&s&&t.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:n}=t.layout,{animationType:i}=t.options,l=s.source!==t.layout.source;i==="size"?Qs(h=>{const x=l?s.measuredBox[h]:s.layoutBox[h],u=Ss(x);x.min=r[h].min,x.max=x.min+u}):Tp(i,s.layoutBox,r)&&Qs(h=>{const x=l?s.measuredBox[h]:s.layoutBox[h],u=Ss(r[h]);x.max=x.min+u,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[h].max=t.relativeTarget[h].min+u)});const o=Dr();un(o,r,s.layoutBox);const c=Dr();l?un(c,t.applyTransform(n,!0),s.measuredBox):un(c,r,s.layoutBox);const d=!wp(o);let m=!1;if(!t.resumeFrom){const h=t.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:x,layout:u}=h;if(x&&u){const g=Yt();xn(g,s.layoutBox,x.layoutBox);const b=Yt();xn(b,r,u.layoutBox),Cp(g,b)||(m=!0),h.options.layoutRoot&&(t.relativeTarget=b,t.relativeTargetOrigin=g,t.relativeParent=h)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function v2(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=!!(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function j2(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function N2(t){t.clearSnapshot()}function su(t){t.clearMeasurements()}function au(t){t.isLayoutDirty=!1}function w2(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function ru(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function C2(t){t.resolveTargetDelta()}function S2(t){t.calcProjection()}function A2(t){t.resetSkewAndRotation()}function T2(t){t.removeLeadSnapshot()}function nu(t,s,a){t.translate=zt(s.translate,0,a),t.scale=zt(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function iu(t,s,a,r){t.min=zt(s.min,a.min,r),t.max=zt(s.max,a.max,r)}function k2(t,s,a,r){iu(t.x,s.x,a.x,r),iu(t.y,s.y,a.y,r)}function R2(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const D2={duration:.45,ease:[.4,0,.1,1]},lu=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),ou=lu("applewebkit/")&&!lu("chrome/")?Math.round:aa;function cu(t){t.min=ou(t.min),t.max=ou(t.max)}function P2(t){cu(t.x),cu(t.y)}function Tp(t,s,a){return t==="position"||t==="preserve-aspect"&&!MC(eu(s),eu(a),.2)}function I2(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const E2=Ap({attachResizeListener:(t,s)=>Nn(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),yl={current:void 0},kp=Ap({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!yl.current){const t=new E2({});t.mount(window),t.setOptions({layoutScroll:!0}),yl.current=t}return yl.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),F2={pan:{Feature:QC},drag:{Feature:JC,ProjectionNode:kp,MeasureLayout:vp}};function du(t,s,a){const{props:r}=t;t.animationState&&r.whileHover&&t.animationState.setActive("whileHover",a==="Start");const n="onHover"+a,i=r[n];i&&Mt.postRender(()=>i(s,En(s)))}class _2 extends Ka{mount(){const{current:s}=this.node;s&&(this.unmount=s1(s,(a,r)=>(du(this.node,r,"Start"),n=>du(this.node,n,"End"))))}unmount(){}}class L2 extends Ka{constructor(){super(...arguments),this.isActive=!1}onFocus(){let s=!1;try{s=this.node.current.matches(":focus-visible")}catch{s=!0}!s||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Dn(Nn(this.node.current,"focus",()=>this.onFocus()),Nn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function mu(t,s,a){const{props:r}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&r.whileTap&&t.animationState.setActive("whileTap",a==="Start");const n="onTap"+(a==="End"?"":a),i=r[n];i&&Mt.postRender(()=>i(s,En(s)))}class M2 extends Ka{mount(){const{current:s}=this.node;s&&(this.unmount=i1(s,(a,r)=>(mu(this.node,r,"Start"),(n,{success:i})=>mu(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const ro=new WeakMap,vl=new WeakMap,$2=t=>{const s=ro.get(t.target);s&&s(t)},O2=t=>{t.forEach($2)};function U2({root:t,...s}){const a=t||document;vl.has(a)||vl.set(a,{});const r=vl.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(O2,{root:t,...s})),r[n]}function B2(t,s,a){const r=U2(s);return ro.set(t,a),r.observe(t),()=>{ro.delete(t),r.unobserve(t)}}const V2={some:0,all:1};class z2 extends Ka{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:a,margin:r,amount:n="some",once:i}=s,l={root:a?a.current:void 0,rootMargin:r,threshold:typeof n=="number"?n:V2[n]},o=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:h}=this.node.getProps(),x=d?m:h;x&&x(c)};return B2(this.node.current,l,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:s,prevProps:a}=this.node;["amount","margin","root"].some(H2(s,a))&&this.startObserver()}unmount(){}}function H2({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const W2={inView:{Feature:z2},tap:{Feature:M2},focus:{Feature:L2},hover:{Feature:_2}},G2={layout:{ProjectionNode:kp,MeasureLayout:vp}},Y2={...PC,...W2,...F2,...G2},ts=Y1(Y2,iC),tn=[{id:"claim-management",name:"Claim Management",description:"End-to-end dealer claim processing workflow with automatic IO generation and budget blocking",category:"Dealer Operations",icon:Gt,color:"from-blue-500 to-indigo-600",estimatedTime:"5-7 days",steps:7,features:["Automatic IO confirmation","Budget blocking","Document verification","E-invoice generation","Credit note issuance"],disabled:!1},{id:"vendor-payment",name:"Vendor Payment",description:"Streamlined vendor payment approval with PO validation and financial controls",category:"Finance",icon:ex,color:"from-green-500 to-emerald-600",estimatedTime:"3-5 days",steps:5,features:["PO matching","Invoice verification","Multi-level approvals","Payment scheduling"],disabled:!0,comingSoon:!0}];function K2({open:t,onClose:s,onSelectTemplate:a}){var d,m,h;const[r,n]=p.useState(null),[i,l]=p.useState(!1);p.useEffect(()=>{const x=tt.getUserData();l((x==null?void 0:x.jobTitle)==="Dealer")},[]);const o=x=>{if(i)return;const u=tn.find(g=>g.id===x);u!=null&&u.disabled||n(x)},c=()=>{r&&(a(r),s())};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"!fixed !inset-0 !top-0 !left-0 !right-0 !bottom-0 !w-screen !h-screen !max-w-none !translate-x-0 !translate-y-0 p-0 gap-0 border-0 !rounded-none bg-gradient-to-br from-gray-50 to-white [&>button]:hidden !m-0",children:[e.jsx(mt,{className:"sr-only",children:"Select a Template"}),e.jsx(Dt,{className:"sr-only",children:"Choose from pre-configured templates with predefined workflows and approval chains for faster processing."}),e.jsx("button",{onClick:s,className:"!flex absolute top-6 left-6 z-50 w-10 h-10 rounded-full bg-white shadow-lg hover:shadow-xl border border-gray-200 items-center justify-center transition-all hover:scale-110","aria-label":"Go back",children:e.jsx(Ns,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsxs("div",{className:"min-h-full flex flex-col items-center justify-center px-6 py-12",children:[e.jsxs(ts.div,{initial:{opacity:0,y:-20},animate:{opacity:1,y:0},className:"text-center mb-12 max-w-3xl",children:[e.jsx("div",{className:"w-20 h-20 bg-gradient-to-br from-blue-500 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-6",children:e.jsx(qu,{className:"w-10 h-10 text-white"})}),e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4",children:"Choose Your Template"}),e.jsx("p",{className:"text-lg text-gray-600",children:"Select from pre-configured templates with predefined workflows and approval chains for faster processing."})]}),e.jsx("div",{className:"w-full max-w-5xl grid grid-cols-1 md:grid-cols-2 gap-6 mb-8",children:tn.map((x,u)=>{const g=x.icon,b=r===x.id,f=i||x.disabled;return e.jsx(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:u*.1},whileHover:f?{}:{scale:1.03},whileTap:f?{}:{scale:.98},children:e.jsxs(ee,{className:`h-full transition-all duration-300 border-2 ${f?"opacity-50 cursor-not-allowed border-gray-200":b?"cursor-pointer border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"cursor-pointer border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>o(x.id),children:[e.jsxs(ge,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl bg-gradient-to-br ${x.color} flex items-center justify-center shadow-md`,children:e.jsx(g,{className:"w-7 h-7 text-white"})}),b&&e.jsx(ts.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center shadow-md",children:e.jsx(yr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(fe,{className:"text-xl mb-2",children:x.name}),e.jsx($e,{className:"text-sm leading-relaxed",children:x.description}),i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-amber-50 border border-amber-200 rounded-lg",children:[e.jsx(ze,{className:"w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-amber-800",children:"Not accessible for Dealers"})]}),x.comingSoon&&!i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-blue-50 border border-blue-200 rounded-lg",children:[e.jsx(ze,{className:"w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-blue-800 font-semibold",children:"Coming Soon"})]})]})]}),e.jsxs(se,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(ne,{variant:"secondary",className:"text-xs",children:x.category})}),e.jsx(Ts,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(st,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:x.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ot,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[x.steps," steps"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx("p",{className:"text-xs text-gray-500 font-semibold",children:"Key Features:"}),e.jsxs("div",{className:"space-y-1.5",children:[x.features.slice(0,3).map((y,v)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(De,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:y})]},v)),x.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",x.features.length-3," more features"]})]})]})]})]})},x.id)})}),e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"flex flex-col sm:flex-row justify-center gap-4 mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(E,{onClick:c,disabled:!r||i||((d=tn.find(x=>x.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=tn.find(x=>x.id===r))!=null&&m.disabled)?"bg-blue-600 hover:bg-blue-700":"bg-gray-400 cursor-not-allowed"}`,children:["Continue with Template",e.jsx(ss,{className:"w-4 h-4"})]})]}),e.jsx(Ei,{children:r&&e.jsx(ts.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},className:"mt-6 text-center",children:e.jsxs("p",{className:"text-sm text-gray-600",children:["Selected: ",e.jsx("span",{className:"font-semibold text-blue-600",children:(h=tn.find(x=>x.id===r))==null?void 0:h.name})]})})})]})})]})})}function jr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=p.useState(100),[m,h]=p.useState(0),[x,u]=p.useState(null),[g,b]=p.useState(!1),[f,y]=p.useState(null),v=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),w=s.toLowerCase().includes("pdf"),C=v||w;p.useEffect(()=>{if(!l||!C||!a){u(null);return}return(async()=>{b(!0),y(null);try{let R=a;a.startsWith("/")&&!a.startsWith("//")&&(R=`${window.location.origin}${a}`);const F=await fetch(R,{headers:{Accept:w?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!F.ok){const T=await F.text().catch(()=>"");throw new Error(`Failed to load file: ${F.status} ${F.statusText}. ${T}`)}const $=await F.blob();if($.size===0)throw new Error("File is empty or could not be loaded");w&&!$.type.includes("pdf")&&$.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${$.type}`);const V=window.URL.createObjectURL($);u(V)}catch(N){console.error("Failed to load file for preview:",N),y(N instanceof Error?N.message:"Failed to load file for preview")}finally{b(!1)}})(),()=>{x&&(window.URL.revokeObjectURL(x),u(null))}},[l,a,C,w]);const k=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},S=()=>d(A=>Math.min(A+25,200)),_=()=>d(A=>Math.max(A-25,50)),D=()=>h(A=>(A+90)%360);return e.jsx(pt,{open:l,onOpenChange:o,children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(gt,{className:"pb-4 flex-shrink-0 pr-8",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(ht,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`โ€ข ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[v&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:_,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(r0,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[c,"%"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:S,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(n0,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:D,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(tx,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(E,{variant:"outline",size:"sm",onClick:k,className:"gap-2 h-9",children:[e.jsx(Ct,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})]})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:g?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[e.jsx(lt,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):f?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(ft,{className:"w-10 h-10 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Failed"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:f}),i&&n&&e.jsxs(E,{onClick:k,className:"gap-2",children:[e.jsx(Ct,{className:"h-4 w-4"}),"Download ",t]})]}):C&&x?e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:x,alt:t,style:{transform:`scale(${c/100}) rotate(${m}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),w&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:x,className:"w-full h-full rounded-lg border-0",title:t,style:{minHeight:"70vh",height:"100%"},onError:()=>{y("Failed to load PDF preview")}})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(ht,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),i&&n&&e.jsxs(E,{onClick:k,className:"gap-2",children:[e.jsx(Ct,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function Fn({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following policy violations were detected:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:a.map((n,i)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:n.type}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:n.message}),n.currentValue!==void 0&&n.maxValue!==void 0&&e.jsxs("p",{className:"text-xs text-red-600 mt-1 font-semibold",children:["Current: ",n.currentValue," / Maximum: ",n.maxValue]})]},i))}),r&&e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"System Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[r.maxApprovalLevels!==void 0&&e.jsxs("li",{children:["Maximum approval levels: ",r.maxApprovalLevels]}),r.maxParticipants!==void 0&&e.jsxs("li",{children:["Maximum participants per request: ",r.maxParticipants]}),r.allowSpectators!==void 0&&e.jsxs("li",{children:["Allow adding spectators: ",r.allowSpectators?"Yes":"No"]}),r.maxSpectators!==void 0&&e.jsxs("li",{children:["Maximum spectators per request: ",r.maxSpectators]})]})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const Ys=async t=>{const s=t?{category:t}:{};return(await je.get("/users/configurations",{params:s})).data.data},X2=async t=>{const s={};return(await je.get("/admin/configurations",{params:s})).data.data},Z2=async(t,s)=>{await je.put(`/admin/configurations/${t}`,{configValue:s})},J2=async t=>{await je.post(`/admin/configurations/${t}/reset`)},Q2=async t=>{const s=t?{year:t}:{};return(await je.get("/admin/holidays",{params:s})).data.data},q2=async t=>(await je.post("/admin/holidays",t)).data.data,eS=async(t,s)=>(await je.put(`/admin/holidays/${t}`,s)).data.data,tS=async t=>{await je.delete(`/admin/holidays/${t}`)},sS=async()=>(await je.get("/config/activity-types")).data.data,aS=async t=>{const s={activeOnly:t.toString()};return(await je.get("/admin/activity-types",{params:s})).data.data},rS=async t=>(await je.post("/admin/activity-types",t)).data.data,nS=async(t,s)=>(await je.put(`/admin/activity-types/${t}`,s)).data.data,iS=async t=>{await je.delete(`/admin/activity-types/${t}`)},lS={template:"",title:"",description:"",category:"",priority:"",urgency:"",businessImpact:"",amount:"",currency:"USD",vendor:"",timeline:"",slaTemplate:"",slaHours:0,customSlaHours:0,slaEndDate:void 0,expectedCompletionDate:void 0,breachEscalation:!0,reminderSchedule:"50",workflowType:"sequential",requiresAllApprovals:!0,escalationEnabled:!0,reminderEnabled:!0,minimumLevel:1,maxLevel:1,approvers:[],approverCount:1,spectators:[],ccList:[],invitedUsers:[],allowComments:!0,allowDocumentUpload:!0,documents:[],tags:[],relatedRequests:[],costCenter:"",project:""};function oS(t,s,a){const[r,n]=p.useState(lS),[i,l]=p.useState(null),[o,c]=p.useState(t),[d,m]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[h,x]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[u,g]=p.useState([]);return p.useEffect(()=>{(async()=>{var y;try{const v=await Ys("DOCUMENT_POLICY"),w={};v.forEach(P=>{w[P.configKey]=P.configValue});const C=parseInt(w.MAX_FILE_SIZE_MB||"10"),S=(w.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(P=>P.trim().toLowerCase());x({maxFileSizeMB:C,allowedFileTypes:S});const _=await Ys("SYSTEM_SETTINGS"),D=await Ys("WORKFLOW_SHARING"),A=[..._,...D],N={};A.forEach(P=>{N[P.configKey]=P.configValue}),m({maxApprovalLevels:parseInt(N.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(N.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((y=N.ALLOW_ADD_SPECTATOR)==null?void 0:y.toLowerCase())==="true",maxSpectators:parseInt(N.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(v){console.error("Failed to load policies:",v)}})()},[]),p.useEffect(()=>{if(!t||!s)return;let f=!0;return(async()=>{try{c(!0);const y=await vs(s);if(!f||!y)return;const v=y.workflow||{},w=Array.isArray(y.approvals)?y.approvals:[],C=Array.isArray(y.participants)?y.participants:[],k=Array.isArray(y.documents)?y.documents.filter(R=>!R.isDeleted):[];g(k);const S=(v.priority||"").toString().toLowerCase(),_={standard:"standard",express:"express"},D=v.templateType==="TEMPLATE"?"existing-template":"custom",A=a.find(R=>R.id===D)||a[0]||null;l(A);const N=w.sort((R,O)=>(R.levelNumber||0)-(O.levelNumber||0)).map(R=>{const O=Number(R.tatHours||24),F=Math.floor(O/24),$=O%24;return{id:R.approverId||`temp-${R.levelNumber}`,name:R.approverName||R.approverEmail||"",email:R.approverEmail||"",role:R.levelName||`Level ${R.levelNumber}`,department:"",avatar:(R.approverName||R.approverEmail||"XX").substring(0,2).toUpperCase(),level:R.levelNumber||1,canClose:!1,tat:F>0?F:$,tatType:F>0?"days":"hours",userId:R.approverId}}),P=C.filter(R=>(R.participantType||R.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(R.userEmail||R.user_email||R.email):!1).map((R,O)=>{const F=R.userId||R.user_id||R.id,$=R.userName||R.user_name||R.name||"",V=R.userEmail||R.user_email||R.email||"",j=($||V||"XX").split(" ").map(U=>U[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:F||`spectator-${s}-${O}-${Date.now()}`,userId:F,name:$||V||"Spectator",email:V,role:"Spectator",department:R.department||"",avatar:j,level:1,canClose:!1}});n(R=>({...R,template:D,title:v.title||"",description:v.description||"",priority:_[S]||"standard",approvers:N,approverCount:N.length||1,spectators:P,maxLevel:Math.max(...N.map(O=>O.level||1),1)}))}catch(y){console.error("Failed to load draft:",y)}finally{f&&c(!1)}})(),()=>{f=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(f,y)=>{n(v=>({...v,[f]:y}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:d,documentPolicy:h,existingDocuments:u,setExistingDocuments:g}}const uu=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function cS(t,s,a){const[r,n]=p.useState(t?2:1),i=uu.length,l=h=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(h),o=()=>{switch(r){case 1:return s!==null;case 2:return a.title.trim()!==""&&a.description.trim()!==""&&a.priority!=="";case 3:return(a.approverCount||1)>0&&a.approvers.length===(a.approverCount||1)&&a.approvers.every(h=>{if(!h||!h.email||!l(h.email))return!1;if(!h.userId)return!0;const x=h.tatType||"hours";return x==="hours"?h.tat&&h.tat>0&&h.tat<=720:x==="days"?h.tat&&h.tat>0&&h.tat<=30:!1});case 4:return!0;case 5:return!0;case 6:return!0;default:return!1}};return{currentStep:r,setCurrentStep:n,totalSteps:i,stepNames:uu,isStepValid:o,nextStep:()=>{o()&&(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),r{r>1&&(n(r-1),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}))},goToStep:h=>{h>=1&&h<=i&&n(h)},validateEmail:l}}function dS(){const[t,s]=p.useState({open:!1,type:"error",email:"",message:""}),[a,r]=p.useState({open:!1,violations:[]}),[n,i]=p.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(x,u,g="")=>{s({open:!0,type:x,email:u,message:g})},closeValidationModal:()=>{s(x=>({...x,open:!1}))},openPolicyViolationModal:x=>{r({open:!0,violations:x})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:x=>{i({open:!0,errors:x})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function mS(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function uS(t,s,a){var n;const r=mS(t.tat||24,t.tatType||"hours");return{levelNumber:s,levelName:`Level ${s}`,approverId:t.userId||"",approverEmail:t.email||"",approverName:t.name||((n=t.email)==null?void 0:n.split("@")[0])||`Approver ${s}`,tatHours:r,isFinalApprover:a}}function xS(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return uS(a,n,n===s)})}function xu(t,s,a,r=!1){return{templateId:(s==null?void 0:s.id)||null,templateType:(s==null?void 0:s.id)==="custom"?"CUSTOM":"TEMPLATE",title:t.title,description:t.description,priorityUi:t.priority==="express"?"express":"standard",approverCount:t.approverCount||1,approvers:(t.approvers||[]).map(n=>({userId:(n==null?void 0:n.userId)||"",email:(n==null?void 0:n.email)||"",name:n==null?void 0:n.name,tat:(n==null?void 0:n.tat)||24,tatType:(n==null?void 0:n.tatType)||"hours"})),spectators:(t.spectators||[]).map(n=>({userId:(n==null?void 0:n.userId)||"",name:(n==null?void 0:n.name)||"",email:(n==null?void 0:n.email)||""})),ccList:[],participants:[],isDraft:r}}function hu(t,s,a,r=!1){const n=xS(t.approvers||[],t.approverCount||1);return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:n,participants:[],deleteDocumentIds:a.length>0?a:void 0,isDraft:r}}function hS(t,s){const a=t.slice(0,s);if(a.some(l=>!(l!=null&&l.email)||!l.email.trim()))return{valid:!1,message:"Please provide email addresses for all approvers."};const n=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return a.some(l=>!n.test((l==null?void 0:l.email)||""))?{valid:!1,message:"Please provide valid email addresses for all approvers."}:{valid:!0}}async function pu(t,s){return{id:(await Io(t,s||[],"SUPPORTING")).id}}async function gu(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await sN(t,s,a||[],r):await tN(t,s)}function pS({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=p.useState(!1),[m,h]=p.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var b,f;if(c||m)return;const g=hS(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const y=hu(t,n,r,!1);await gu(l,y,a,r),K.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been submitted and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const y=xu(t,s,n,!1),v=await pu(y,a);K.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been created and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:v.id,template:s})}}catch(y){console.error("Failed to submit workflow:",y),K.error("Failed to Submit Request",{description:((f=(b=y==null?void 0:y.response)==null?void 0:b.data)==null?void 0:f.message)||(y==null?void 0:y.message)||"An error occurred while submitting the request.",duration:5e3}),d(!1)}},handleSaveDraft:async()=>{var g,b;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||m)){h(!0);try{if(i&&l){const f=hu(t,n,r,!0);await gu(l,f,a,r),K.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const f=xu(t,s,n,!0),y=await pu(f,a);K.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:y.id,template:s})}}catch(f){console.error("Failed to save draft:",f),K.error("Failed to Save Draft",{description:((b=(g=f==null?void 0:f.response)==null?void 0:g.data)==null?void 0:b.message)||(f==null?void 0:f.message)||"An error occurred while saving the draft.",duration:5e3}),h(!1)}}}}}async function ia(t,s=10,a="default"){return await je.get("/users/search",{params:{q:t,limit:s,source:a}})}async function ra(t){var a;const s=await je.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function gS(t,s){return await je.post("/admin/users/assign-role",{email:t,role:s})}async function fS(t,s){return await je.put(`/admin/users/${t}/role`,{role:s})}async function bS(t,s=1,a=10){return await je.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function yS(){return await je.get("/admin/users/role-statistics")}async function vS(t){var a;const s=await je.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function jS(){var s,a;return((a=(s=(await je.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const dr={searchUsers:ia,getUserById:vS,ensureUserExists:ra,assignRole:gS,updateUserRole:fS,getUsersByRole:bS,getRoleStatistics:yS,getAllUsers:jS};async function NS(t,s){var a;if(t.email.toLowerCase()===s.toLowerCase())return{success:!1,error:{type:"self-assign",email:t.email,message:""}};try{const n=((a=(await ia(t.email,1)).data)==null?void 0:a.data)||[];if(n.length===0)return{success:!1,error:{type:"not-found",email:t.email,message:""}};const i=n[0];return i?(await ra({userId:i.userId,email:i.email,displayName:i.displayName,firstName:i.firstName,lastName:i.lastName,department:i.department,phone:i.phone,mobilePhone:i.mobilePhone,designation:i.designation,jobTitle:i.jobTitle,manager:i.manager,employeeId:i.employeeId,employeeNumber:i.employeeNumber,secondEmail:i.secondEmail,location:i.location}),{success:!0}):{success:!1,error:{type:"error",email:t.email,message:"Could not retrieve user details. Please try again."}}}catch(r){return console.error(`Failed to validate approver ${t.email}:`,r),{success:!1,error:{type:"error",email:t.email,message:"Failed to validate user. Please try again or select a different user."}}}}async function wS(t,s){var n;if(t.filter(i=>i&&i.email&&!i.userId).length===0)return{success:!0,validatedApprovers:t};const r=[...t];for(let i=0;i{s(D),a("template",D.id),a("category",D.category),a("priority",D.priority);const A=new Date;A.setDate(A.getDate()+D.suggestedSLA),a("slaEndDate",A),D.id!=="custom"&&D.id!=="existing-template"&&u(`/create-admin-request/${D.id}`)},handleTemplateSelection:D=>{D==="claim-management"?u("/claim-management"):D==="vendor-payment"?u("/vendor-payment"):x&&x({templateType:D})},nextStep:async()=>{var D;if(i()){if(n===1&&(t==null?void 0:t.id)==="existing-template"){b(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&h){const P=r.approverCount||1;if(P>m.maxApprovalLevels){h([{type:"Maximum Approval Levels Exceeded",message:`The request has ${P} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:P,maxValue:m.maxApprovalLevels}]);return}}const A=((D=c==null?void 0:c.email)==null?void 0:D.toLowerCase())||"",N=await wS(r.approvers,A);if(!N.success&&N.error){d(N.error.type,N.error.email,N.error.message);return}N.validatedApprovers&&a("approvers",N.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(D,A)=>{if(A){const N=D.documentId||D.document_id||"";y({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:Hr(N),fileSize:Number(D.fileSize||D.file_size||0),documentId:N})}else{const N=URL.createObjectURL(D);y({fileName:D.name,fileType:D.type||"application/octet-stream",fileUrl:N,fileSize:D.size,file:D})}},closePreview:()=>{f!=null&&f.fileUrl&&(f!=null&&f.file)&&URL.revokeObjectURL(f.fileUrl),y(null)}}}const fu=[{id:"custom",name:"Non-Templatized",description:"Create a custom request for unique business needs with full flexibility to define your own workflow and requirements",category:"General",icon:Ni,estimatedTime:"Variable",commonApprovers:[],suggestedSLA:3,priority:"medium",fields:{}},{id:"existing-template",name:"Existing Template",description:"Use a pre-configured template with predefined approval workflows, timelines, and requirements for faster processing",category:"Templates",icon:Re,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let br=null;const bu=()=>br,SS=async t=>{const a=(await je.post("/templates",t)).data.data,r={id:a.templateId||a.id,name:a.templateName||a.name,description:a.templateDescription||a.description,category:a.templateCategory||a.category,priority:a.priority||"medium",estimatedTime:a.estimatedTime||"Variable",approvers:a.approvalLevelsConfig||a.approvers||[],suggestedSLA:a.defaultTatHours||a.suggestedSLA||24,isActive:a.isActive,fields:a.userFieldMappings||a.fields};return br&&br.push(r),r},Mi=async()=>{var r;const a=(((r=(await je.get("/templates")).data)==null?void 0:r.data)||[]).map(n=>({id:n.templateId||n.id,name:n.templateName||n.name,description:n.templateDescription||n.description,category:n.templateCategory||n.category,priority:n.priority||"medium",estimatedTime:n.estimatedTime||"Variable",approvers:n.approvalLevelsConfig||n.approvers||[],suggestedSLA:n.defaultTatHours||n.suggestedSLA||24,isActive:n.isActive,fields:n.userFieldMappings||n.fields}));return br=a,a},AS=async(t,s)=>{const r=(await je.put(`/templates/${t}`,s)).data.data,n={id:r.templateId||r.id,name:r.templateName||r.name,description:r.templateDescription||r.description,category:r.templateCategory||r.category,priority:r.priority||"medium",estimatedTime:r.estimatedTime||"Variable",approvers:r.approvalLevelsConfig||r.approvers||[],suggestedSLA:r.defaultTatHours||r.suggestedSLA||24,isActive:r.isActive,fields:r.userFieldMappings||r.fields};return br&&(br=br.map(i=>i.id===t?n:i)),n};function Rp({currentStep:t,totalSteps:s,stepNames:a}){const r=Math.round(t/s*100),n=a.length<=3?"max-w-xl":"max-w-6xl";return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-2 sm:py-3 flex-shrink-0","data-testid":"wizard-stepper",children:e.jsxs("div",{className:`${n} mx-auto`,children:[e.jsxs("div",{className:"block sm:hidden","data-testid":"wizard-stepper-mobile",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-green-600 text-white flex items-center justify-center text-xs font-semibold","data-testid":"wizard-stepper-mobile-current-step",children:t}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-900","data-testid":"wizard-stepper-mobile-step-name",children:a[t-1]}),e.jsxs("p",{className:"text-xs text-gray-600","data-testid":"wizard-stepper-mobile-step-info",children:["Step ",t," of ",s]})]})]}),e.jsx("div",{className:"text-right",children:e.jsxs("p",{className:"text-xs font-medium text-green-600","data-testid":"wizard-stepper-mobile-progress",children:[r,"%"]})})]}),e.jsx("div",{className:"w-full bg-gray-200 h-1.5 rounded-full overflow-hidden","data-testid":"wizard-stepper-mobile-progress-bar",children:e.jsx("div",{className:"bg-green-600 h-full transition-all duration-300",style:{width:`${r}%`},"data-testid":"wizard-stepper-mobile-progress-fill"})})]}),e.jsxs("div",{className:"hidden sm:block","data-testid":"wizard-stepper-desktop",children:[e.jsx("div",{className:"flex items-center justify-center gap-4 mb-2","data-testid":"wizard-stepper-desktop-steps",children:a.map((i,l)=>e.jsxs("div",{className:"flex items-center flex-1 last:flex-none","data-testid":`wizard-stepper-desktop-step-${l+1}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-xs font-semibold flex-shrink-0 ${l+1e.jsx("span",{className:`${l+1===t?"font-semibold text-green-600":""}`,"data-testid":`wizard-stepper-desktop-label-${l+1}`,children:i},l))})]})]})})}function TS({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:l,submitting:o,savingDraft:c,loadingDraft:d,isEditing:m}){return e.jsx("div",{className:"fixed sm:relative bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0 shadow-lg sm:shadow-none z-50","data-testid":"wizard-footer",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2 sm:gap-4 max-w-6xl mx-auto",children:[e.jsxs(E,{variant:"outline",onClick:r,disabled:t===1,size:"sm",className:"sm:size-lg order-2 sm:order-1","data-testid":"wizard-footer-prev-button",children:[e.jsx(Ns,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Previous"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 order-1 sm:order-2","data-testid":"wizard-footer-actions",children:[e.jsx(E,{variant:"outline",onClick:l,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:d||o||c,"data-testid":"wizard-footer-save-draft-button",children:c?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),e.jsx("span",{children:m?"Updating...":"Saving..."})]}):e.jsx("span",{children:m?"Update Draft":"Save Draft"})}),t===s?e.jsx(E,{onClick:i,disabled:!a||d||o||c,size:"sm",className:"sm:size-lg bg-green-600 hover:bg-green-700 flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-submit-button",children:o?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(sx,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(E,{onClick:n,disabled:!a,size:"sm",className:"sm:size-lg flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-next-button",children:[e.jsx("span",{className:"hidden sm:inline",children:"Next Step"}),e.jsx("span",{className:"sm:hidden",children:"Next"}),e.jsx(ss,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const yu=t=>{switch(t){case"high":return e.jsx(ha,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Ot,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(ta,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Ot,{className:"w-4 h-4 text-gray-600"})}};function kS({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=p.useState("main"),l=Ks(),o=m=>{m.id==="admin-templates-category"?i("admin"):n==="admin"?l(`/create-admin-request/${m.id}`):a(m)},c=n==="main"?[...t]:r;return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"min-h-full flex flex-col items-center justify-center py-8","data-testid":"template-selection-step",children:[e.jsxs("div",{className:"text-center mb-12 max-w-3xl","data-testid":"template-selection-header",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4","data-testid":"template-selection-title",children:n==="main"?"Choose Your Request Type":"Organization Templates"}),e.jsx("p",{className:"text-lg text-gray-600","data-testid":"template-selection-description",children:n==="main"?"Start with a pre-built template for faster approvals, or create a custom request tailored to your needs.":"Select a pre-configured workflow template defined by your organization."})]}),n==="admin"&&e.jsx("div",{className:"w-full max-w-6xl mb-6 flex justify-start",children:e.jsxs(E,{variant:"ghost",className:"gap-2",onClick:()=>i("main"),children:[e.jsx(Ns,{className:"w-4 h-4"}),"Back to All Types"]})}),e.jsx("div",{className:"w-full max-w-6xl grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8","data-testid":"template-selection-grid",children:c.length===0&&n==="admin"?e.jsxs("div",{className:"col-span-full text-center py-12 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed border-gray-200",children:[e.jsx(i0,{className:"w-12 h-12 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No admin templates available yet."})]}):c.map(m=>{var g;const x=m.id==="admin-templates-category",u=(s==null?void 0:s.id)===m.id;return e.jsx(ts.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${m.id}`,children:e.jsxs(ee,{className:`h-full transition-all duration-300 border-2 ${u?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200 cursor-pointer":x?"border-blue-200 bg-blue-50/30 hover:border-blue-400 hover:shadow-lg cursor-pointer":"border-gray-200 hover:border-blue-300 hover:shadow-lg cursor-pointer"}`,onClick:()=>o(m),"data-testid":`template-card-${m.id}-clickable`,children:[e.jsxs(ge,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl flex items-center justify-center ${u||x?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${m.id}-icon`,children:e.jsx(m.icon,{className:`w-7 h-7 ${u||x?"text-blue-600":"text-gray-600"}`})}),u&&e.jsx(ts.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},"data-testid":`template-card-${m.id}-selected-indicator`,children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center",children:e.jsx(yr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsx(fe,{className:"text-xl","data-testid":`template-card-${m.id}-name`,children:m.name}),!1]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),yu(m.priority)]})]})]}),e.jsxs(se,{className:"pt-0 space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed line-clamp-2","data-testid":`template-card-${m.id}-description`,children:m.description}),!x&&e.jsxs(e.Fragment,{children:[e.jsx(Ts,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-estimated-time`,children:[e.jsx(st,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:m.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-approvers-count`,children:[e.jsx(cs,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[((g=m.commonApprovers)==null?void 0:g.length)||0," approvers"]})]})]})]}),x&&e.jsx("div",{className:"pt-2",children:e.jsx("p",{className:"text-xs text-blue-600 font-medium flex items-center gap-1",children:"Click to browse templates โ†’"})})]})]})},m.id)})}),e.jsx(Ei,{children:s&&e.jsx(ts.div,{initial:{opacity:0,y:20,height:0},animate:{opacity:1,y:0,height:"auto"},exit:{opacity:0,y:-20,height:0},transition:{duration:.3},className:"w-full max-w-6xl","data-testid":"template-details-card",children:e.jsxs(ee,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Ur,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-sla",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Suggested SLA"}),e.jsxs("p",{className:"text-blue-700 mt-1",children:[s.suggestedSLA," hours"]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-priority",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[yu(s.priority),e.jsx("span",{className:"text-blue-700 capitalize",children:s.priority})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-duration",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Estimated Duration"}),e.jsx("p",{className:"text-blue-700 mt-1",children:s.estimatedTime})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-approvers",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((d=s.commonApprovers)==null?void 0:d.length)>0?s.commonApprovers.map((m,h)=>e.jsx(ne,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${h}`,children:m},`${s.id}-approver-${h}-${m}`)):e.jsx("span",{className:"text-sm text-gray-500 italic",children:"No specific approvers defined"})})]})]})]})})})]})}function Oe({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:ke("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground flex h-9 w-full min-w-0 rounded-md border border-gray-400 bg-white px-3 py-1 text-base text-gray-900 transition-all outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-re-light-green focus-visible:ring-0 focus-visible:outline-none","hover:border-gray-500","aria-invalid:ring-destructive/20 aria-invalid:border-destructive",t),...a})}function RS({className:t,...s}){return e.jsx(uf,{"data-slot":"radio-group",className:ke("grid gap-3",t),...s})}function vu({className:t,...s}){return e.jsx(xf,{"data-slot":"radio-group-item",className:ke("border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(hf,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(l0,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function DS({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"basic-information-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"basic-information-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-green-500 to-blue-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(Re,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"basic-information-title",children:"Basic Information"}),e.jsxs("p",{className:"text-gray-600","data-testid":"basic-information-description",children:["Provide the essential details for your ",(s==null?void 0:s.name)||"request","."]})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"basic-information-form",children:[e.jsxs("div",{"data-testid":"basic-information-title-field",children:[e.jsx(re,{htmlFor:"title",className:"text-base font-semibold",children:"Request Title *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"Be specific and descriptive. This will be visible to all participants."}),e.jsx(Oe,{id:"title",placeholder:"e.g., Approval on new office location",value:t.title,onChange:r=>a("title",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-title-input"})]}),e.jsxs("div",{"data-testid":"basic-information-description-field",children:[e.jsx(re,{htmlFor:"description",className:"text-base font-semibold",children:"Detailed Description *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"๐Ÿ’ก Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(Rn,{value:t.description||"",onChange:r=>a("description",r),placeholder:"Provide comprehensive details about your request including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px","data-testid":"basic-information-description-textarea"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6","data-testid":"basic-information-priority-section",children:e.jsxs("div",{"data-testid":"basic-information-priority-field",children:[e.jsx(re,{className:"text-base font-semibold",children:"Priority Level *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"select priority for your request"}),e.jsxs(RS,{value:t.priority||"",onValueChange:r=>a("priority",r),"data-testid":"basic-information-priority-radio-group",children:[e.jsxs("div",{className:`flex items-center space-x-3 p-3 rounded-lg border-2 cursor-pointer transition-all ${t.priority==="express"?"border-red-500 bg-red-100":"border-red-200 bg-red-50 hover:bg-red-100"}`,onClick:()=>a("priority","express"),"data-testid":"basic-information-priority-express-option",children:[e.jsx(vu,{value:"express",id:"express"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(xo,{className:"w-4 h-4 text-red-600"}),e.jsx(re,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(ne,{variant:"destructive",className:"text-xs",children:"URGENT"})]}),e.jsx("p",{className:"text-xs text-red-700",children:"Includes calendar days in TAT - faster processing timeline"})]})]}),e.jsxs("div",{className:`flex items-center space-x-3 p-3 rounded-lg border cursor-pointer transition-all ${t.priority==="standard"?"border-blue-500 bg-blue-50":"border-gray-200 hover:bg-gray-50"}`,onClick:()=>a("priority","standard"),"data-testid":"basic-information-priority-standard-option",children:[e.jsx(vu,{value:"standard",id:"standard"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(st,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(ne,{variant:"secondary",className:"text-xs",children:"DEFAULT"})]}),e.jsx("p",{className:"text-xs text-gray-600",children:"Includes working days in TAT - regular processing timeline"})]})]})]})]})}),((s==null?void 0:s.fields.amount)||(s==null?void 0:s.fields.vendor)||(s==null?void 0:s.fields.timeline)||(s==null?void 0:s.fields.impact))&&e.jsxs("div",{className:"border-t pt-6","data-testid":"basic-information-additional-details",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Additional Details"}),e.jsxs("div",{className:"space-y-6",children:[(s==null?void 0:s.fields.amount)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4","data-testid":"basic-information-amount-field",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(Oe,{id:"amount",placeholder:"Enter amount",value:t.amount,onChange:r=>a("amount",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-amount-input"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(We,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Ye,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"USD",children:"USD ($)"}),e.jsx(Y,{value:"EUR",children:"EUR (โ‚ฌ)"}),e.jsx(Y,{value:"GBP",children:"GBP (ยฃ)"}),e.jsx(Y,{value:"INR",children:"INR (โ‚น)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(re,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(Oe,{id:"vendor",placeholder:"Enter vendor or supplier name",value:t.vendor,onChange:r=>a("vendor",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-vendor-input"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{"data-testid":"basic-information-cost-center-field",children:[e.jsx(re,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(Oe,{id:"costCenter",placeholder:"e.g., Marketing, IT, Operations",value:t.costCenter,onChange:r=>a("costCenter",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-cost-center-input"})]}),e.jsxs("div",{"data-testid":"basic-information-project-field",children:[e.jsx(re,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(Oe,{id:"project",placeholder:"Associated project name or code",value:t.project,onChange:r=>a("project",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-project-input"})]})]})]})]})]})]})}function Dp(){const[t,s]=p.useState([]),[a,r]=p.useState(!1),n=p.useRef(null);return{searchResults:t,searchLoading:a,searchUsersDebounced:async(c,d=10)=>{if(n.current&&clearTimeout(n.current),!c||!c.startsWith("@")||c.length<2){s([]),r(!1);return}r(!0),n.current=setTimeout(async()=>{var m;try{const h=c.slice(1),u=((m=(await ia(h,d)).data)==null?void 0:m.data)||[];s(u)}catch(h){console.error("User search failed:",h),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await ra({userId:c.userId,email:c.email,displayName:c.displayName,firstName:c.firstName,lastName:c.lastName,department:c.department,phone:c.phone,mobilePhone:c.mobilePhone,designation:c.designation,jobTitle:c.jobTitle,manager:c.manager,employeeId:c.employeeId,employeeNumber:c.employeeNumber,secondEmail:c.secondEmail,location:c.location})}catch(d){throw console.error("Failed to ensure user exists:",d),d}}}}function Pp(){const[t,s]=p.useState({}),[a,r]=p.useState({}),n=p.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(o,c,d=10)=>{if(n.current[o]&&clearTimeout(n.current[o]),!c||!c.startsWith("@")||c.length<2){s(m=>({...m,[o]:[]})),r(m=>({...m,[o]:!1}));return}r(m=>({...m,[o]:!0})),n.current[o]=setTimeout(async()=>{var m;try{const h=c.slice(1),u=((m=(await ia(h,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:u}))}catch(h){console.error(`User search failed for index ${o}:`,h),s(x=>({...x,[o]:[]}))}finally{r(h=>({...h,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function PS({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var h;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=Pp();p.useEffect(()=>{const x=t.approverCount||1,u=t.approvers||[];if(u.lengthx&&s("approvers",u.slice(0,x))},[t.approverCount,s]);const d=(x,u)=>{var y,v,w,C,k;const g=[...t.approvers],f=((y=g[x])==null?void 0:y.email)!==u;if(g[x]={...g[x],email:u,level:x+1,userId:f||(v=g[x])==null?void 0:v.userId,name:f||(w=g[x])==null?void 0:w.name,department:f||(C=g[x])==null?void 0:C.department,avatar:f||(k=g[x])==null?void 0:k.avatar},s("approvers",g),!u||!u.startsWith("@")||u.length<2){c(x);return}o(x,u,10)},m=async(x,u)=>{var g,b;try{if((g=t.approvers)==null?void 0:g.some((C,k)=>{var S,_;return k!==x&&(C.userId===u.userId||((S=C.email)==null?void 0:S.toLowerCase())===((_=u.email)==null?void 0:_.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((b=t.spectators)==null?void 0:b.some(C=>{var k,S;return C.userId===u.userId||((k=C.email)==null?void 0:k.toLowerCase())===((S=u.email)==null?void 0:S.toLowerCase())})){a({type:"error",email:u.email,message:"This user is already added as a spectator. A user cannot be both an approver and a spectator."});return}const v=await ra({userId:u.userId,email:u.email,displayName:u.displayName,firstName:u.firstName,lastName:u.lastName,department:u.department,phone:u.phone,mobilePhone:u.mobilePhone,designation:u.designation,jobTitle:u.jobTitle,manager:u.manager,employeeId:u.employeeId,employeeNumber:u.employeeNumber,secondEmail:u.secondEmail,location:u.location}),w=[...t.approvers];w[x]={...w[x],email:u.email,name:u.displayName||[u.firstName,u.lastName].filter(Boolean).join(" "),userId:v.userId,level:x+1},s("approvers",w),c(x)}catch(f){console.error("Failed to ensure user exists:",f),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"approval-workflow-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"approval-workflow-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-orange-500 to-red-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(cs,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"approval-workflow-title",children:"Approval Workflow"}),e.jsx("p",{className:"text-gray-600","data-testid":"approval-workflow-description",children:"Define the approval hierarchy and assign approvers by email ID."})]}),e.jsxs("div",{className:"max-w-4xl mx-auto space-y-8","data-testid":"approval-workflow-content",children:[e.jsxs(ee,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(Va,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx($e,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(se,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(re,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const x=t.approverCount||1,u=Math.max(1,x-1);s("approverCount",u),t.approvers.length>u&&s("approvers",t.approvers.slice(0,u))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(ho,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-2xl font-semibold w-12 text-center","data-testid":"approval-workflow-count-display",children:t.approverCount||1}),e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const u=(t.approverCount||1)+1;if(u>r.maxApprovalLevels){n([{type:"Maximum Approval Levels Exceeded",message:`Cannot add more than ${r.maxApprovalLevels} approval levels. Please remove an approver level or contact your administrator.`,currentValue:u,maxValue:r.maxApprovalLevels}]);return}s("approverCount",u)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(gs,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Maximum ",r.maxApprovalLevels," approver",r.maxApprovalLevels!==1?"s":""," allowed. Each approver will review sequentially."]})]})})]}),e.jsxs(ee,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(hs,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs($e,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsx("div",{className:"p-4 rounded-lg border-2 border-blue-200 bg-blue-50","data-testid":"approval-workflow-initiator-card",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center",children:e.jsx(Vt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-blue-900",children:"Request Initiator"}),e.jsx(ne,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-sm text-blue-700",children:"Creates and submits the request"})]})]})}),Array.from({length:t.approverCount||1},(x,u)=>{var y,v;const g=u+1,b=g===(t.approverCount||1),f=t.approvers[u]||{email:"",tat:""};return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${g}`,children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-6 bg-gray-300"})}),e.jsx("div",{className:`p-4 rounded-lg border-2 transition-all ${f.email?"border-green-200 bg-green-50":"border-gray-200 bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${f.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:g})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",g]}),b&&e.jsx(ne,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(re,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),f.email&&f.userId&&e.jsxs(ne,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Oe,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:f.email||"",onChange:w=>d(u,w.target.value),className:"h-10 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full","data-testid":`approval-workflow-approver-${g}-email-input`}),(l[u]||(((y=i[u])==null?void 0:y.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:l[u]?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:(v=i[u])==null?void 0:v.map(w=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(u,w),"data-testid":`approval-workflow-approver-${g}-search-result-${w.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:w.displayName||w.email}),e.jsx("div",{className:"text-xs text-gray-600",children:w.email})]},w.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-tat-field`,children:[e.jsx(re,{htmlFor:`tat-${g}`,className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Oe,{id:`tat-${g}`,type:"number",placeholder:f.tatType==="days"?"7":"24",min:"1",max:f.tatType==="days"?"30":"720",value:f.tat||"",onChange:w=>{const C=[...t.approvers];C[u]={...C[u],tat:parseInt(w.target.value)||"",level:g,tatType:f.tatType||"hours"},s("approvers",C)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(We,{value:f.tatType||"hours",onValueChange:w=>{const C=[...t.approvers];C[u]={...C[u],tatType:w,level:g,tat:""},s("approvers",C)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(Ye,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},g)})]})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ur,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900 mb-1",children:"Approval Flow Summary"}),e.jsxs("p",{className:"text-sm text-blue-700",children:["Your request will follow this sequence: ",e.jsx("strong",{children:"You (Initiator)"})," โ†’ ",Array.from({length:t.approverCount||1},(x,u)=>`Level ${u+1} Approver`).join(" โ†’ "),". The final approver can close the request."]})]})]})}),e.jsx("div",{className:"p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-lg border border-emerald-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(st,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const y=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+y:b+y/24},0))||0,u=Math.ceil(x);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[u," ",u===1?"Day":"Days"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Duration"})]})})()})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:(h=t.approvers)==null?void 0:h.map((x,u)=>{const g=Number(x.tat||0),f=(x.tatType||"hours")==="days"?g*24:g;return g?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",u+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[f," ",f===1?"hour":"hours"]})]})},u):null})}),(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const y=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+y*24:b+y},0))||0,u=Math.ceil(x/8);return x===0?null:e.jsxs("div",{className:"bg-white/80 p-3 rounded border border-emerald-200",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[x,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children:u}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Working Days*"})]})]}),e.jsx("p",{className:"text-xs text-emerald-600 mt-2 text-center",children:"*Based on 8-hour working days"})]})})()]})]})]})})]})]})]})}function IS({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=p.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=Dp(),h=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},x=async g=>{var b,f;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(w=>{var C,k;return w.userId===g.userId||((C=w.email)==null?void 0:C.toLowerCase())===((k=g.email)==null?void 0:k.toLowerCase())}),v=(b=t.approvers)==null?void 0:b.some(w=>{var C,k;return w.userId===g.userId||((C=w.email)==null?void 0:C.toLowerCase())===((k=g.email)==null?void 0:k.toLowerCase())});if(y){a({type:"error",email:g.email,message:"This user is already added as a spectator."});return}if(v){a({type:"error",email:g.email,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}try{const w=await m(g),C={id:w.userId,userId:w.userId,name:w.displayName||g.email.split("@")[0],email:w.email,avatar:(w.displayName||w.email).substring(0,2).toUpperCase(),role:"Spectator",department:w.department||"",level:1,canClose:!1},k=[...t.spectators,C];s("spectators",k),i(""),d()}catch{a({type:"error",email:g.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(w=>{var C;return((C=w.email)==null?void 0:C.toLowerCase())===n.toLowerCase()}),v=(f=t.approvers)==null?void 0:f.some(w=>{var C;return((C=w.email)==null?void 0:C.toLowerCase())===n.toLowerCase()});if(y){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(v){a({type:"error",email:n,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}}},u=g=>{const b=t.spectators.filter(f=>f.id!==g);s("spectators",b)};return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"participants-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"participants-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-teal-500 to-green-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(ht,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"participants-title",children:"Participants & Access"}),e.jsx("p",{className:"text-gray-600","data-testid":"participants-description",children:"Configure additional participants and visibility settings for your request."})]}),e.jsx("div",{className:"max-w-3xl mx-auto space-y-8","data-testid":"participants-content",children:e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:e.jsxs(ee,{"data-testid":"participants-spectators-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center justify-between text-base","data-testid":"participants-spectators-title",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ht,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(ne,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx($e,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2","data-testid":"participants-spectators-add-section",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-full",children:[e.jsx(Oe,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>h(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.preventDefault(),await x())},className:"text-sm w-full","data-testid":"participants-spectators-email-input"}),(o||l.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:o?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:l.map(g=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>x(g),"data-testid":`participants-spectators-search-result-${g.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:g.displayName||g.email}),e.jsx("div",{className:"text-xs text-gray-600",children:g.email})]},g.userId))})})]}),e.jsx(E,{size:"sm",onClick:()=>x(),disabled:!n||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n),"data-testid":"participants-spectators-add-button",children:"Add"})]}),e.jsxs("p",{className:"text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded p-2 flex items-center gap-1",children:[e.jsx(Ur,{className:"w-3 h-3 flex-shrink-0"}),e.jsxs("span",{children:["Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users, or type email directly (will be validated against organization directory)"]})]})]}),e.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto","data-testid":"participants-spectators-list",children:t.spectators.map(g=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-teal-50 rounded-lg","data-testid":`participants-spectator-${g.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zt,{className:"h-6 w-6",children:e.jsx(Jt,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(ft,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function ES({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:c,onDocumentErrors:d,fileInputRef:m}){const h=b=>{const f=Array.from(b.target.files||[]);if(f.length===0)return;const y=t.maxFileSizeMB*1024*1024,v=[],w=[];f.forEach(C=>{if(C.size>y){v.push({fileName:C.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(C.size/1048576).toFixed(2)}MB`});return}const k=C.name.toLowerCase(),S=k.substring(k.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(S)){v.push({fileName:C.name,reason:`File type "${S}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}w.push(C)}),w.length>0&&i([...a,...w]),v.length>0&&d&&d(v),b.target&&(b.target.value="")},x=b=>{const f=a.filter((y,v)=>v!==b);i(f)},u=b=>{o([...n,b])},g=(b,f=!1)=>{if(f){const y=(b.fileType||b.file_type||"").toLowerCase(),v=(b.originalFileName||b.fileName||"").toLowerCase();return y.includes("image")||y.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}else{const y=(b.type||"").toLowerCase(),v=(b.name||"").toLowerCase();return y.includes("image")||y.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}};return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"documents-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"documents-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(zs,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"documents-title",children:"Documents & Attachments"}),e.jsx("p",{className:"text-gray-600","data-testid":"documents-description",children:"Upload supporting documents, files, and any additional materials for your request."})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"documents-content",children:[e.jsxs(ee,{"data-testid":"documents-upload-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs($e,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(se,{children:e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-gray-400 transition-colors","data-testid":"documents-upload-area",children:[e.jsx(zs,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"click to browse"}),e.jsx("input",{type:"file",multiple:!0,accept:t.allowedFileTypes.map(b=>`.${b}`).join(","),onChange:h,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(E,{variant:"outline",size:"lg",type:"button",onClick:()=>{var b;return(b=m.current)==null?void 0:b.click()},"data-testid":"documents-browse-button",children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Browse Files"]}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Supported formats: ",t.allowedFileTypes.map(b=>b.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(ee,{"data-testid":"documents-existing-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ne,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length," file",r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length!==1?"s":""]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(b=>{const f=b.documentId||b.document_id||"";return n.includes(f)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${f}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.originalFileName||b.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:b.fileSize?(Number(b.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!0)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>c(b,!0),"data-testid":`documents-existing-${f}-preview`,children:e.jsx(ht,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(f),"data-testid":`documents-existing-${f}-delete`,children:e.jsx(ft,{className:"h-4 w-4 text-red-600"})})]})]},f)})})})]}),a.length>0&&e.jsxs(ee,{"data-testid":"documents-new-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ne,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((b,f)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${f}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(b.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!1)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>c(b,!1),"data-testid":`documents-new-${f}-preview`,children:e.jsx(ht,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>x(f),"data-testid":`documents-new-${f}-remove`,children:e.jsx(ft,{className:"h-4 w-4"})})]})]},f))})})]})]})]})}const FS=t=>{switch(t){case"high":return e.jsx(ha,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Ot,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(ta,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Ot,{className:"w-4 h-4 text-gray-600"})}};function _S({formData:t,selectedTemplate:s}){return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"review-submit-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"review-submit-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-green-500 to-teal-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(De,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"review-submit-title",children:"Review & Submit"}),e.jsx("p",{className:"text-gray-600","data-testid":"review-submit-description",children:"Please review all details before submitting your request for approval."})]}),e.jsxs("div",{className:"max-w-5xl mx-auto space-y-8","data-testid":"review-submit-content",children:[e.jsxs(ee,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(sx,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6","data-testid":"review-submit-overview-grid",children:[e.jsxs("div",{"data-testid":"review-submit-overview-type",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Request Type"}),e.jsx("p",{className:"text-green-800 mt-1",children:s==null?void 0:s.name}),e.jsx(ne,{variant:"outline",className:"mt-2 text-xs border-green-300 text-green-700",children:s==null?void 0:s.category})]}),e.jsxs("div",{"data-testid":"review-submit-overview-priority",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[FS(t.priority),e.jsx("span",{className:"text-green-800 capitalize",children:t.priority})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-workflow",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Workflow Type"}),e.jsx("p",{className:"text-green-800 mt-1 capitalize",children:t.workflowType}),e.jsxs("p",{className:"text-sm text-green-700",children:[t.approverCount||1," Level",(t.approverCount||1)>1?"s":""]})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-title",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Request Title"}),e.jsx("p",{className:"text-green-800 font-medium mt-1 text-lg",children:t.title})]})]})]}),e.jsxs(ee,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(re,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(sa,{content:t.description||""})})]}),t.amount&&e.jsxs("div",{className:"p-3 bg-blue-50 rounded-lg border border-blue-200","data-testid":"review-submit-basic-info-financial",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Da,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{className:"font-semibold text-blue-900",children:"Financial Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Amount"}),e.jsxs("p",{className:"font-semibold text-blue-900",children:[t.amount," ",t.currency]})]}),t.costCenter&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Cost Center"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.costCenter})]})]})]})]})]}),e.jsxs(ee,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(cs,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx($e,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(se,{className:"space-y-6",children:e.jsx("div",{className:"space-y-4","data-testid":"review-submit-approval-levels",children:Array.from({length:t.approverCount||1},(a,r)=>{const n=r+1,i=n===(t.approverCount||1),l=t.approvers[r];return e.jsx("div",{className:"p-4 bg-white rounded-lg border border-orange-200","data-testid":`review-submit-approval-level-${n}`,children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${l!=null&&l.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:n})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",n]}),i&&e.jsx(ne,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Email Address"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:(l==null?void 0:l.email)||"Not assigned"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"TAT (Turn Around Time)"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l!=null&&l.tat?`${l.tat} ${l.tatType==="days"?"day":"hour"}${l.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(ee,{"data-testid":"review-submit-participants-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(ht,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(se,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(re,{className:"font-semibold text-sm",children:["Spectators (",t.spectators.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:t.spectators.map(a=>e.jsxs(ne,{variant:"outline",className:"text-xs","data-testid":`review-submit-spectator-${a.id}`,children:[a.name," (",a.email,")"]},a.id))})]})})]}),t.documents.length>0&&e.jsxs(ee,{"data-testid":"review-submit-documents-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(zs,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs($e,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"review-submit-documents-list",children:t.documents.map((a,r)=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-gray-50 rounded-lg border","data-testid":`review-submit-document-${r}`,children:[e.jsx(Re,{className:"w-5 h-5 text-gray-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.name}),e.jsx("div",{className:"flex items-center gap-3 text-xs text-gray-500 mt-1",children:e.jsxs("span",{children:[(a.size/(1024*1024)).toFixed(2)," MB"]})})]})]},r))})})]}),e.jsx(ee,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(se,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(De,{className:"w-6 h-6 text-blue-600 mt-1 flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-blue-900 mb-2","data-testid":"review-submit-confirmation-title",children:"Ready to Submit Request"}),e.jsx("p",{className:"text-sm text-blue-700 mb-4","data-testid":"review-submit-confirmation-message",children:"Once submitted, your request will enter the approval workflow and notifications will be sent to all relevant participants."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 text-sm","data-testid":"review-submit-confirmation-summary",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-700",children:"Request Type:"}),e.jsx("p",{className:"font-medium text-blue-900",children:s==null?void 0:s.name})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-700",children:"Approval Levels:"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.approverCount||1})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-700",children:"Documents:"}),e.jsxs("p",{className:"font-medium text-blue-900",children:[t.documents.length," attached"]})]})]})]})]})})})]})]})}function LS({isEditing:t,currentStep:s,totalSteps:a,stepNames:r,onBack:n}){return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0","data-testid":"create-request-header",children:e.jsxs("div",{className:"flex items-center justify-between max-w-6xl mx-auto gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-1 min-w-0",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"create-request-back-button",children:e.jsx(Ns,{className:"h-4 w-4 sm:h-5 sm:w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-base sm:text-xl md:text-2xl font-bold text-gray-900 truncate","data-testid":"create-request-title",children:t?"Edit Draft":"New Request"}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600 hidden sm:block","data-testid":"create-request-step-info",children:["Step ",s," of ",a,": ",r[s-1]]})]})]}),e.jsx("div",{className:"hidden md:flex items-center gap-4","data-testid":"create-request-progress-info",children:e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-900",children:[Math.round(s/a*100),"% Complete"]}),e.jsxs("p",{className:"text-xs text-gray-600",children:[a-s," steps remaining"]})]})})]})})}function MS({children:t}){return e.jsx("div",{className:"flex-1 overflow-y-auto pb-24 sm:pb-4","data-testid":"create-request-content",children:e.jsx("div",{className:"max-w-6xl mx-auto p-3 sm:p-6 pb-6 sm:pb-6",children:e.jsx(Ei,{mode:"wait",children:t})})})}function $S({modal:t,onClose:s}){return e.jsx(pt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["You cannot add yourself (",e.jsx("strong",{children:t.email}),") as an approver."]}),e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-amber-800",children:[e.jsx("strong",{children:"Why?"})," The initiator creates the request and cannot approve their own request. Please select a different user."]})})]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:t.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Ni,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use"," ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," ","sign to search and select users from the directory for guaranteed results."]})})]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:[t.email&&e.jsxs(e.Fragment,{children:["Failed to validate ",e.jsx("strong",{children:t.email}),"."]}),!t.email&&e.jsx(e.Fragment,{children:"An error occurred during validation."})]}),t.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:t.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function OS({modal:t,documentPolicy:s,onClose:a}){return e.jsx(pt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:t.errors.map((r,n)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3","data-testid":`document-error-${n}`,children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:r.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:r.reason})]},n))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",s.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types:"," ",s.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function ju({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Ea(),i=Ks(),l=n.requestId||a||"",o=r&&!!l,{user:c}=Kt(),[d,m]=p.useState([]);p.useEffect(()=>{(async()=>{try{const rt=(await Mi()).map(ut=>({id:ut.id,name:ut.name,description:ut.description,category:ut.category,icon:Re,estimatedTime:ut.estimatedTime,commonApprovers:ut.approvers.map(nt=>nt.name),workflowApprovers:ut.approvers,suggestedSLA:ut.suggestedSLA,priority:ut.priority,fields:ut.fields||{}}));m(rt)}catch(_e){console.error("Failed to fetch admin templates:",_e)}})()},[]);const h=p.useMemo(()=>[...fu,...d],[d]),{formData:x,updateFormData:u,selectedTemplate:g,setSelectedTemplate:b,loadingDraft:f,systemPolicy:y,documentPolicy:v,existingDocuments:w,setExistingDocuments:C}=oS(o,l,h),{currentStep:k,totalSteps:S,stepNames:_,isStepValid:D,nextStep:A,prevStep:N}=cS(o,g,x),[P,R]=p.useState([]),[O,F]=p.useState([]),$=p.useRef(null),{validationModal:V,policyViolationModal:T,documentErrorModal:j,openValidationModal:U,closeValidationModal:I,openPolicyViolationModal:M,closePolicyViolationModal:W,openDocumentErrorModal:G,closeDocumentErrorModal:ce}=dS(),{submitting:te,savingDraft:L,handleSubmit:z,handleSaveDraft:H}=pS({formData:x,selectedTemplate:g,documents:P,documentsToDelete:O,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:ye,setShowTemplateModal:ae,previewDocument:me,selectTemplate:Q,handleTemplateSelection:oe,nextStep:Ce,prevStep:Ee,handlePreviewDocument:be,closePreview:q}=CS({selectedTemplate:g,setSelectedTemplate:b,updateFormData:u,formData:x,currentStep:k,isStepValid:D,wizardNextStep:A,wizardPrevStep:N,user:c,openValidationModal:U,systemPolicy:y,onPolicyViolation:M,onSubmit:s}),ue=p.useCallback(()=>{if(k===1){i("/dashboard",{replace:!0});return}k===3||k===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Ee()},[k,t,i,Ee]),Ae=p.useRef(!0),Ue=p.useRef(!1);p.useEffect(()=>{Ae.current&&x.documents&&x.documents.length>0&&!Ue.current&&(R(x.documents),Ue.current=!0),Ae.current=!1},[x.documents]);const Z=p.useRef(!1),Te=p.useRef(P);p.useEffect(()=>{if(Z.current){Z.current=!1,Te.current=P;return}Te.current!==P&&(u("documents",P),Te.current=P)},[P]);const Xe=()=>{switch(k){case 1:return e.jsx(kS,{templates:fu,selectedTemplate:g,onSelectTemplate:Q,adminTemplates:d});case 2:return e.jsx(DS,{formData:x,selectedTemplate:g,updateFormData:u});case 3:return e.jsx(PS,{formData:x,updateFormData:u,systemPolicy:y,onValidationError:pe=>U(pe.type,pe.email,pe.message),onPolicyViolation:M});case 4:return e.jsx(IS,{formData:x,updateFormData:u,onValidationError:pe=>U(pe.type,pe.email,pe.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(ES,{documentPolicy:v,isEditing:o,documents:P,existingDocuments:w,documentsToDelete:O,onDocumentsChange:R,onExistingDocumentsChange:C,onDocumentsToDeleteChange:F,onPreviewDocument:be,onDocumentErrors:pe=>G(pe),fileInputRef:$});case 6:return e.jsx(_S,{formData:x,selectedTemplate:g});default:return null}};return f?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center","data-testid":"create-request-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading draft..."})]})}):e.jsxs("div",{className:"h-full flex flex-col bg-gradient-to-br from-gray-50 to-white","data-testid":"create-request",children:[e.jsx(LS,{isEditing:o,currentStep:k,totalSteps:S,stepNames:_,onBack:ue}),e.jsx(Rp,{currentStep:k,totalSteps:S,stepNames:_}),e.jsx(MS,{children:Xe()}),e.jsx(TS,{currentStep:k,totalSteps:S,isStepValid:D(),onPrev:Ee,onNext:Ce,onSubmit:z,onSaveDraft:H,submitting:te,savingDraft:L,loadingDraft:f,isEditing:o}),e.jsx(K2,{open:ye,onClose:()=>ae(!1),onSelectTemplate:oe}),me&&e.jsx(jr,{fileName:me.fileName,fileType:me.fileType,fileUrl:me.fileUrl,fileSize:me.fileSize,open:!!me,onClose:q,onDownload:async()=>{if(me.file){const pe=document.createElement("a");pe.href=me.fileUrl,pe.download=me.fileName,document.body.appendChild(pe),pe.click(),document.body.removeChild(pe)}else me.documentId&&await ps(me.documentId)},attachmentId:me.documentId}),e.jsx($S,{modal:V,onClose:I}),e.jsx(OS,{modal:j,documentPolicy:v,onClose:ce}),e.jsx(Fn,{open:T.open,onClose:W,violations:T.violations,policyDetails:{maxApprovalLevels:y.maxApprovalLevels,maxParticipants:y.maxParticipants,allowSpectators:y.allowSpectators,maxSpectators:y.maxSpectators}})]})}function $i({className:t,...s}){return e.jsx(pf,{"data-slot":"tabs",className:ke("flex flex-col gap-2",t),...s})}function Oi({className:t,...s}){return e.jsx(gf,{"data-slot":"tabs-list",className:ke("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function qt({className:t,...s}){return e.jsx(ff,{"data-slot":"tabs-trigger",className:ke("data-[state=active]:bg-card dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-xl border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}function es({className:t,...s}){return e.jsx(bf,{"data-slot":"tabs-content",className:ke("flex-1 outline-none",t),...s})}function hc(t,s=[],a){const[r,n]=p.useState(null),[i,l]=p.useState(!1),[o,c]=p.useState(!0),[d,m]=p.useState(null),[h,x]=p.useState(null),[u,g]=p.useState(!1),b=(k,S)=>(k||S||"NA").toString().split(" ").map(D=>D[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),f=k=>{const S=(k||"").toUpperCase();return S==="IN_PROGRESS"?"in-review":S==="PENDING"?"pending":S==="APPROVED"?"approved":S==="REJECTED"?"rejected":S==="CLOSED"?"closed":S==="SKIPPED"?"skipped":(k||"").toLowerCase()},y=p.useCallback(async()=>{var k,S,_,D,A,N,P,R,O,F,$,V,T;l(!0);try{const j=await ks.getWorkflowDetails(t);if(!j){console.warn("[useRequestDetails] No details returned from API");return}const U=j.workflow||{},I=Array.isArray(j.approvals)?j.approvals:[],M=Array.isArray(j.participants)?j.participants:[],W=Array.isArray(j.documents)?j.documents:[],G=j.summary||{},ce=Array.isArray(j.tatAlerts)?j.tatAlerts:[];ce.length>0;const te=(G==null?void 0:G.currentLevel)||U.currentLevel||1,L=I.map(Z=>{const Te=Z.levelNumber||0,Xe=(Z.status||"").toString().toUpperCase(),pe=Z.levelId||Z.level_id;let _e=f(Z.status);Te>te&&Xe!=="APPROVED"&&Xe!=="REJECTED"?_e="waiting":Te===te&&Xe==="PENDING"&&(_e="pending");const rt=ce.filter(ut=>ut.levelId===pe);return{step:Te,levelId:pe,role:Z.levelName||Z.approverName||"Approver",status:_e,approver:Z.approverName||Z.approverEmail,approverId:Z.approverId||Z.approver_id,approverEmail:Z.approverEmail,tatHours:Number(Z.tatHours||0),elapsedHours:Number(Z.elapsedHours||0),remainingHours:Number(Z.remainingHours||0),tatPercentageUsed:Number(Z.tatPercentageUsed||0),actualHours:Z.levelEndTime&&Z.levelStartTime?Math.max(0,(new Date(Z.levelEndTime).getTime()-new Date(Z.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:Z.comments||void 0,timestamp:Z.actionDate||void 0,levelStartTime:Z.levelStartTime||Z.tatStartTime,tatAlerts:rt,skipReason:Z.skipReason||void 0,isSkipped:Xe==="SKIPPED"||Z.isSkipped||!1}}),z=M.filter(Z=>(Z.participantType||Z.participant_type||"").toUpperCase()==="SPECTATOR").map(Z=>({name:Z.userName||Z.user_name||Z.userEmail||Z.user_email,role:"Spectator",email:Z.userEmail||Z.user_email,avatar:b(Z.userName||Z.user_name,Z.userEmail||Z.user_email)})),H=Z=>{var Xe,pe;if(!Z)return;const Te=M.find(_e=>_e.userId===Z||_e.user_id===Z);return Te!=null&&Te.userName||Te!=null&&Te.user_name?Te.userName||Te.user_name:U.initiatorId===Z?((Xe=U.initiator)==null?void 0:Xe.displayName)||((pe=U.initiator)==null?void 0:pe.email):Z},ye=W.map(Z=>{const Te=Number(Z.fileSize||Z.file_size||0),Xe=(Te/(1024*1024)).toFixed(2)+" MB";return{documentId:Z.documentId||Z.document_id,name:Z.originalFileName||Z.fileName||Z.file_name,fileType:Z.fileType||Z.file_type||"",size:Xe,sizeBytes:Te,uploadedBy:H(Z.uploadedBy||Z.uploaded_by),uploadedAt:Z.uploadedAt||Z.uploaded_at}}),ae=Array.isArray(j.activities)?j.activities.filter(Z=>(Z.type||"").toLowerCase()!=="sla_warning"):[];let me=null;if(U.isPaused||!1)try{me=await Zd(U.requestId)}catch{}let oe=null,Ce=null,Ee=null,be=null;if(U.workflowType==="CLAIM_MANAGEMENT"||U.templateType==="claim-management")try{const Z=await je.get(`/dealer-claims/${U.requestId}`),Te=((k=Z.data)==null?void 0:k.data)||Z.data;if(Te){oe=Te.claimDetails||Te.claim_details,Ce=Te.proposalDetails||Te.proposal_details,Ee=Te.completionDetails||Te.completion_details,be=Te.internalOrder||Te.internal_order||null;const Xe=Te.budgetTracking||Te.budget_tracking||null,pe=Te.invoice||null,_e=Te.creditNote||Te.credit_note||null,rt=Te.completionExpenses||Te.completion_expenses||null;oe&&(oe.budgetTracking=Xe,oe.invoice=pe,oe.creditNote=_e,oe.completionExpenses=rt)}else console.warn("[useRequestDetails] No claimData found in response")}catch(Z){console.error("[useRequestDetails] Error fetching claim details:",{error:(Z==null?void 0:Z.message)||Z,status:(S=Z==null?void 0:Z.response)==null?void 0:S.status,statusText:(_=Z==null?void 0:Z.response)==null?void 0:_.statusText,responseData:(D=Z==null?void 0:Z.response)==null?void 0:D.data,requestId:U.requestId})}const q={...U,id:U.requestNumber||U.requestId,requestId:U.requestId,requestNumber:U.requestNumber,title:U.title,description:U.description,status:f(U.status),priority:(U.priority||"").toString().toLowerCase(),workflowType:U.workflowType||(U.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:L,approvals:I,participants:M,documents:ye,spectators:z,summary:G,sla:(G==null?void 0:G.sla)||U.sla||null,initiator:{name:((A=U.initiator)==null?void 0:A.displayName)||((N=U.initiator)==null?void 0:N.email),role:((P=U.initiator)==null?void 0:P.designation)||void 0,department:((R=U.initiator)==null?void 0:R.department)||void 0,email:((O=U.initiator)==null?void 0:O.email)||void 0,phone:((F=U.initiator)==null?void 0:F.phone)||void 0,avatar:b(($=U.initiator)==null?void 0:$.displayName,(V=U.initiator)==null?void 0:V.email)},createdAt:U.createdAt,updatedAt:U.updatedAt,totalSteps:U.totalLevels||1,currentStepRaw:(G==null?void 0:G.currentLevel)||U.currentLevel||1,currentStep:Math.min(Math.max(1,(G==null?void 0:G.currentLevel)||U.currentLevel||1),U.totalLevels||1),auditTrail:ae,conclusionRemark:U.conclusionRemark||null,closureDate:U.closureDate||null,pauseInfo:me||null,claimDetails:oe||null,proposalDetails:Ce||null,completionDetails:Ee||null,internalOrder:be||null,budgetTracking:(oe==null?void 0:oe.budgetTracking)||null,invoice:(oe==null?void 0:oe.invoice)||null,creditNote:(oe==null?void 0:oe.creditNote)||null,completionExpenses:(oe==null?void 0:oe.completionExpenses)||null};n(q);const ue=(T=a==null?void 0:a.email)==null?void 0:T.toLowerCase(),Ae=I.find(Z=>{const Te=(Z.status||"").toString().toUpperCase(),Xe=(Z.approverEmail||"").toLowerCase(),pe=Z.levelNumber||0;return(Te==="PENDING"||Te==="IN_PROGRESS"||Te==="PAUSED")&&Xe===ue&&pe===te});x(Ae||null);const Ue=a==null?void 0:a.userId;if(Ue){const Z=M.some(Te=>(Te.participantType||Te.participant_type||"").toUpperCase()==="SPECTATOR"&&(Te.userId||Te.user_id)===Ue);g(Z)}else g(!1)}catch(j){console.error("[useRequestDetails] Error refreshing details:",j),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);p.useEffect(()=>{if(!t){c(!1);return}let k=!0;return c(!0),m(null),(async()=>{var S,_,D,A,N,P,R,O,F,$,V,T,j,U;try{const I=await ks.getWorkflowDetails(t);if(!k||!I){k&&c(!1);return}const M=I.workflow||{},W=Array.isArray(I.approvals)?I.approvals:[],G=Array.isArray(I.participants)?I.participants:[],ce=Array.isArray(I.documents)?I.documents:[],te=I.summary||{},L=Array.isArray(I.tatAlerts)?I.tatAlerts:[],z=(M.priority||"").toString().toLowerCase(),H=(te==null?void 0:te.currentLevel)||M.currentLevel||1,ye=W.map(pe=>{const _e=pe.levelNumber||0,rt=(pe.status||"").toString().toUpperCase(),ut=pe.levelId||pe.level_id;let nt=f(pe.status);rt==="PAUSED"?nt="paused":_e>H&&rt!=="APPROVED"&&rt!=="REJECTED"?nt="waiting":_e===H&&(rt==="PENDING"||rt==="IN_PROGRESS")&&(nt=rt==="IN_PROGRESS"?"in-review":"pending");const Ps=L.filter(Xs=>Xs.levelId===ut);return{step:_e,levelId:ut,role:pe.levelName||pe.approverName||"Approver",status:nt,approver:pe.approverName||pe.approverEmail,approverId:pe.approverId||pe.approver_id,approverEmail:pe.approverEmail,tatHours:Number(pe.tatHours||0),elapsedHours:Number(pe.elapsedHours||0),remainingHours:Number(pe.remainingHours||0),tatPercentageUsed:Number(pe.tatPercentageUsed||0),actualHours:pe.elapsedHours!==void 0&&pe.elapsedHours!==null?Number(pe.elapsedHours):void 0,comment:pe.comments||void 0,timestamp:pe.actionDate||void 0,levelStartTime:pe.levelStartTime||pe.tatStartTime,tatAlerts:Ps}}),ae=G.filter(pe=>(pe.participantType||"").toUpperCase()==="SPECTATOR").map(pe=>({name:pe.userName||pe.userEmail,role:"Spectator",avatar:b(pe.userName,pe.userEmail)})),me=pe=>{var rt,ut;if(!pe)return;const _e=G.find(nt=>nt.userId===pe);return _e!=null&&_e.userName?_e.userName:M.initiatorId===pe?((rt=M.initiator)==null?void 0:rt.displayName)||((ut=M.initiator)==null?void 0:ut.email):pe},Q=ce.map(pe=>{const _e=Number(pe.fileSize||0),rt=(_e/(1024*1024)).toFixed(2)+" MB";return{documentId:pe.documentId||pe.document_id,name:pe.originalFileName||pe.fileName,fileType:pe.fileType||pe.file_type||"",size:rt,sizeBytes:_e,uploadedBy:me(pe.uploadedBy),uploadedAt:pe.uploadedAt}}),oe=Array.isArray(I.activities)?I.activities.filter(pe=>(pe.type||"").toLowerCase()!=="sla_warning"):[];let Ce=null;if(M.isPaused||!1)try{Ce=await Zd(M.requestId)}catch{}let be=null,q=null,ue=null,Ae=null;if(M.workflowType==="CLAIM_MANAGEMENT"||M.templateType==="claim-management")try{const pe=await je.get(`/dealer-claims/${M.requestId}`),_e=((S=pe.data)==null?void 0:S.data)||pe.data;if(_e){be=_e.claimDetails||_e.claim_details,q=_e.proposalDetails||_e.proposal_details,ue=_e.completionDetails||_e.completion_details,Ae=_e.internalOrder||_e.internal_order||null;const rt=_e.budgetTracking||_e.budget_tracking||null,ut=_e.invoice||null,nt=_e.creditNote||_e.credit_note||null,Ps=_e.completionExpenses||_e.completion_expenses||null;be&&(be.budgetTracking=rt,be.invoice=ut,be.creditNote=nt,be.completionExpenses=Ps)}}catch(pe){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(pe==null?void 0:pe.message)||pe,status:(_=pe==null?void 0:pe.response)==null?void 0:_.status,requestId:M.requestId})}const Ue={id:M.requestNumber||M.requestId,requestId:M.requestId,title:M.title,description:M.description,priority:z,status:f(M.status),workflowType:M.workflowType||(M.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:te,initiator:{name:((D=M.initiator)==null?void 0:D.displayName)||((A=M.initiator)==null?void 0:A.email),role:((N=M.initiator)==null?void 0:N.designation)||void 0,department:((P=M.initiator)==null?void 0:P.department)||void 0,email:((R=M.initiator)==null?void 0:R.email)||void 0,phone:((O=M.initiator)==null?void 0:O.phone)||void 0,avatar:b((F=M.initiator)==null?void 0:F.displayName,($=M.initiator)==null?void 0:$.email)},createdAt:M.createdAt,updatedAt:M.updatedAt,totalSteps:M.totalLevels||1,currentStepRaw:(te==null?void 0:te.currentLevel)||M.currentLevel||1,currentStep:Math.min(Math.max(1,(te==null?void 0:te.currentLevel)||M.currentLevel||1),M.totalLevels||1),approvalFlow:ye,approvals:W,documents:Q,spectators:ae,auditTrail:oe,conclusionRemark:M.conclusionRemark||null,closureDate:M.closureDate||null,pauseInfo:Ce||null,claimDetails:be||null,proposalDetails:q||null,completionDetails:ue||null,internalOrder:Ae||null,budgetTracking:(be==null?void 0:be.budgetTracking)||null,invoice:(be==null?void 0:be.invoice)||null,creditNote:(be==null?void 0:be.creditNote)||null,completionExpenses:(be==null?void 0:be.completionExpenses)||null};n(Ue);const Z=(V=a==null?void 0:a.email)==null?void 0:V.toLowerCase(),Te=W.find(pe=>{const _e=(pe.status||"").toString().toUpperCase(),rt=(pe.approverEmail||"").toLowerCase(),ut=pe.levelNumber||0;return(_e==="PENDING"||_e==="IN_PROGRESS"||_e==="PAUSED")&&rt===Z&&ut===H});x(Te||null);const Xe=a==null?void 0:a.userId;if(Xe){const pe=G.some(_e=>(_e.participantType||"").toUpperCase()==="SPECTATOR"&&_e.userId===Xe);g(pe)}else g(!1)}catch(I){if(console.error("[useRequestDetails] Error loading request details:",I),k){if(((T=I==null?void 0:I.response)==null?void 0:T.status)===403){const M=((U=(j=I==null?void 0:I.response)==null?void 0:j.data)==null?void 0:U.message)||"You do not have permission to view this request. Access is restricted to the initiator, approvers, and spectators of this request.";m({denied:!0,message:M})}n(null)}}finally{k&&c(!1)}})(),()=>{k=!1}},[t,a]);const v=p.useMemo(()=>{if(r)return r;const k=s.find(S=>S.id===t||S.requestNumber===t||S.request_number===t);return k||null},[t,s,r]),w=p.useMemo(()=>{var _,D,A;if(!v||!a)return!1;const k=(_=a==null?void 0:a.email)==null?void 0:_.toLowerCase(),S=(A=(D=v.initiator)==null?void 0:D.email)==null?void 0:A.toLowerCase();return k===S},[v,a]),C=p.useMemo(()=>{var S;if(!v)return[];const k=[];return(S=v.initiator)!=null&&S.email&&k.push({email:v.initiator.email.toLowerCase(),participantType:"INITIATOR",name:v.initiator.name}),v.approvalFlow&&Array.isArray(v.approvalFlow)&&v.approvalFlow.forEach(_=>{_.approverEmail&&k.push({email:_.approverEmail.toLowerCase(),participantType:"APPROVER",name:_.approver})}),v.spectators&&Array.isArray(v.spectators)&&v.spectators.forEach(_=>{_.email&&k.push({email:_.email.toLowerCase(),participantType:"SPECTATOR",name:_.name})}),v.participants&&Array.isArray(v.participants)&&v.participants.forEach(_=>{const D=(_.userEmail||_.email||"").toLowerCase(),A=(_.participantType||_.participant_type||"").toUpperCase(),N=_.userName||_.user_name||_.name;D&&A&&!k.find(P=>P.email===D)&&k.push({email:D,participantType:A,name:N})}),k},[v]);return p.useEffect(()=>{if(!t||!r)return;const k=Lr();if(!k)return;const S=_=>{((_==null?void 0:_.requestId)===r.requestId||(_==null?void 0:_.requestNumber)===t)&&y()};return k.on("request:updated",S),()=>{k.off("request:updated",S)}},[t,r,y]),{request:v,apiRequest:r,loading:o,refreshing:i,refreshDetails:y,currentApprovalLevel:h,isSpectator:u,isInitiator:w,existingParticipants:C,accessDenied:d}}function Ip(t,s,a,r){const[n,i]=p.useState([]),[l,o]=p.useState(0),[c,d]=p.useState([]);return p.useEffect(()=>{if(!t){console.warn("[useRequestSocket] No requestIdentifier, cannot join socket room");return}let m=!0,h=t;return(async()=>{var b;try{const f=await ks.getWorkflowDetails(t);(b=f==null?void 0:f.workflow)!=null&&b.requestId&&m&&(h=f.workflow.requestId)}catch(f){console.error("[useRequestSocket] Failed to resolve UUID:",f)}if(!m)return;const x=Lr();if(!x){console.error("[useRequestSocket] Socket not available");return}const u=r==null?void 0:r.userId,g=()=>{Ml(x,h,u)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),Ax(x,h))}})(),()=>{m=!1}},[t,r]),p.useEffect(()=>{!t||!s||(async()=>{try{const m=await Fr(t),h=s.auditTrail||[],x=[...m,...h];x.sort((u,g)=>{const b=new Date(u.createdAt||u.created_at||u.timestamp||0).getTime(),f=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return b-f}),i(x)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),p.useEffect(()=>{if(!t)return;const m=Lr();if(!m)return;const h=u=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await Fr(t),b=(s==null?void 0:s.auditTrail)||[],f=[...g,...b].sort((y,v)=>{const w=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime(),C=new Date(v.createdAt||v.created_at||v.timestamp||0).getTime();return w-C});i(f)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},x=u=>{const g=u.type==="breach"?"โฐ":u.type==="threshold2"?"โš ๏ธ":"โณ";(async()=>{try{const b=await ks.getWorkflowDetails(t);b&&(Array.isArray(b.tatAlerts)&&b.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:u.message,icon:"/favicon.ico",tag:`tat-${u.requestId}-${u.type}`,requireInteraction:!1}))}catch(b){console.error("[useRequestSocket] Failed to refresh after TAT alert:",b)}})()};return m.on("noteHandler",h),m.on("worknote:new",h),m.on("tat:alert",x),()=>{m.off("noteHandler",h),m.off("worknote:new",h),m.off("tat:alert",x)}},[t,a,s]),p.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function nn(t,s,a="SUPPORTING"){var l;const r=new FormData;r.append("file",t),r.append("requestId",s),r.append("category",a);const n=await je.post("/documents",r,{headers:{"Content-Type":"multipart/form-data"}}),i=((l=n.data)==null?void 0:l.data)||n.data;return{documentId:(i==null?void 0:i.documentId)||(i==null?void 0:i.document_id)||"",storageUrl:(i==null?void 0:i.storageUrl)||(i==null?void 0:i.storage_url),fileName:(i==null?void 0:i.fileName)||(i==null?void 0:i.file_name)||t.name,originalFileName:(i==null?void 0:i.originalFileName)||(i==null?void 0:i.original_file_name)||t.name}}function Ep(t,s){const[a,r]=p.useState(!1),[n,i]=p.useState(null),[l,o]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=p.useState({show:!1,errors:[]});p.useEffect(()=>{(async()=>{try{const g=await Ys("DOCUMENT_POLICY"),b={};g.forEach(w=>{b[w.configKey]=w.configValue});const f=parseInt(b.MAX_FILE_SIZE_MB||"10"),v=(b.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(w=>w.trim().toLowerCase());o({maxFileSizeMB:f,allowedFileTypes:v})}catch(g){console.error("Failed to load document policy:",g)}})()},[]);const m=u=>{const g=l.maxFileSizeMB*1024*1024;if(u.size>g)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${l.maxFileSizeMB}MB. Current size: ${(u.size/(1024*1024)).toFixed(2)}MB`};const b=u.name.toLowerCase(),f=b.substring(b.lastIndexOf(".")+1);return l.allowedFileTypes.includes(f)?{valid:!0}:{valid:!1,reason:`File type "${f}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},h=async u=>{var v,w;const g=u.target.files;if(!g||g.length===0)return;const b=Array.from(g),f=[],y=[];if(b.forEach(C=>{const k=m(C);k.valid?y.push(C):f.push({fileName:C.name,reason:k.reason||"Unknown validation error"})}),f.length>0&&d({show:!0,errors:f}),y.length===0){u.target&&(u.target.value="");return}r(!0);try{const C=y[0],k=t==null?void 0:t.requestId;if(!k){K.error("Request ID not found");return}C&&await nn(C,k,"SUPPORTING"),await s(),y.length{const u=document.createElement("input");u.type="file",u.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),u.onchange=h,u.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}const US="modulepreload",BS=function(t){return"/"+t},Nu={},jl=function(s,a,r){let n=Promise.resolve();if(a&&a.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));n=Promise.allSettled(a.map(c=>{if(c=BS(c),c in Nu)return;Nu[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":US,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((x,u)=>{h.addEventListener("load",x),h.addEventListener("error",()=>u(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return n.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};function Fp(t,s,a,r,n,i,l){const[o,c]=p.useState(""),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(!1),[b,f]=p.useState(0),[y,v]=p.useState(!1),[w,C]=p.useState(!1),[k,S]=p.useState(0),_=async()=>{var R;const N=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),P=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(N||P){c(N||P),g(!!P);return}try{const{getConclusion:O}=await jl(async()=>{const{getConclusion:$}=await import("./conclusionApi-CzJL-0h7.js");return{getConclusion:$}},__vite__mapDeps([0,1,2,3,4,5,6,7])),F=await O(t.requestId||s);F&&(F.aiGeneratedRemark||F.finalRemark)&&(c(F.finalRemark||F.aiGeneratedRemark||""),g(!!F.aiGeneratedRemark))}catch(O){((R=O==null?void 0:O.response)==null?void 0:R.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",O)}},D=async()=>{if(!w)try{m(!0),v(!1);const{generateConclusion:N}=await jl(async()=>{const{generateConclusion:F}=await import("./conclusionApi-CzJL-0h7.js");return{generateConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7])),P=await N(t.requestId||s),R=b+1;if(f(R),!(P!=null&&P.aiGeneratedRemark)||P.aiGeneratedRemark.toLowerCase().includes("unable to generate")||P.aiGeneratedRemark.toLowerCase().includes("sorry")){const F=k+1;S(F),F>=2?(C(!0),i==null||i({success:!1,title:"AI Generation Limit Reached",message:"We're unable to process a conclusion remark at this time after 2 attempts. Please proceed with a manual approach using the editor below."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process a conclusion remark at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0),c((P==null?void 0:P.aiGeneratedRemark)||""),g(!1);return}c(P.aiGeneratedRemark),g(!0),S(0),R>=2&&(C(!0),i==null||i({success:!0,title:"Maximum Attempts Reached",message:"You've reached the maximum of 2 regeneration attempts. Feel free to manually edit the current suggestion to fit your specific needs."}),l==null||l(!0))}catch(N){console.error("[useConclusionRemark] AI generation failed:",N);const P=k+1;S(P),g(!1),P>=2?(C(!0),i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. Since the maximum of 2 attempts is reached, please proceed with a manual approach."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0)}finally{m(!1)}},A=async()=>{var P,R;const N=o.replace(/<[^>]*>/g,"").trim();if(!N){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),l==null||l(!0);return}if(N.length>2e3){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark exceeds 2000 characters limit"}),l==null||l(!0);return}try{x(!0);const{finalizeConclusion:O}=await jl(async()=>{const{finalizeConclusion:F}=await import("./conclusionApi-CzJL-0h7.js");return{finalizeConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await O(t.requestId||s,o),i==null||i({success:!0,title:"Request Closed with Successful Completion",message:"The request has been finalized and moved to Closed Requests."}),l==null||l(!0),await r(),setTimeout(()=>{n?(n(),setTimeout(()=>{window.location.hash="#/closed-requests"},100)):window.location.hash="#/closed-requests"},2e3)}catch(O){i==null||i({success:!1,title:"Error",message:((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{x(!1)}};return p.useEffect(()=>{var F;const N=(F=t==null?void 0:t.status)==null?void 0:F.toLowerCase();if(!((N==="approved"||N==="rejected"||N==="closed")&&a&&!o))return;const R=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),O=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);R||O?(c(R||O),g(!!O)):_()},[t==null?void 0:t.status,t==null?void 0:t.conclusionRemark,t==null?void 0:t.aiGeneratedConclusion,a,o]),{conclusionRemark:o,setConclusionRemark:c,conclusionLoading:d,conclusionSubmitting:h,aiGenerated:u,handleGenerateConclusion:D,handleFinalizeConclusion:A,generationAttempts:b,generationFailed:y,maxAttemptsReached:w}}function _p(t,s,a){const[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState(!1),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(!1),[b,f]=p.useState(null),[y,v]=p.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:h,setShowSkipApproverModal:x,showActionStatusModal:u,setShowActionStatusModal:g,skipApproverData:b,setSkipApproverData:f,actionStatus:y,setActionStatus:v,handleApproveConfirm:async D=>{var N,P;const A=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!A){alert("Approval level not found");return}await an(t,A,D||""),await new Promise(R=>setTimeout(R,500)),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Approved successfully")},handleRejectConfirm:async D=>{var N,P;if(!(D!=null&&D.trim())){alert("Comments & remarks are required");return}const A=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!A){alert("Approval level not found");return}await Sr(t,A,D.trim(),D.trim()),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Rejected successfully")},handleAddApprover:async(D,A,N)=>{var P,R;try{await Vx(t,D,A,N),await a(),c(!1),v==null||v({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${A}h TAT`}),g==null||g(!0)}catch(O){throw v==null||v({success:!1,title:"Failed to Add Approver",message:((R=(P=O==null?void 0:O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to add approver. Please try again."}),g==null||g(!0),O}},handleSkipApprover:async D=>{var A,N;if(b)try{await Zj(t,b.levelId,D),await a(),x(!1),f(null),v==null||v({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),g==null||g(!0)}catch(P){throw v==null||v({success:!1,title:"Failed to Skip Approver",message:((N=(A=P==null?void 0:P.response)==null?void 0:A.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),P}},handleAddSpectator:async D=>{var A,N;try{await zx(t,D),await a(),m(!1),v==null||v({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),g==null||g(!0)}catch(P){throw v==null||v({success:!1,title:"Failed to Add Spectator",message:((N=(A=P==null?void 0:P.response)==null?void 0:A.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),P}}}}const VS=t=>{const s=(t||"").toLowerCase();return s.includes("image")||s.includes("pdf")||s.includes("jpg")||s.includes("jpeg")||s.includes("png")||s.includes("gif")};function Or({document:t,onPreview:s,onDownload:a,showPreview:r=!0,testId:n="document-card"}){return e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors","data-testid":`${n}-${t.documentId}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Re,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900","data-testid":`${n}-name`,children:t.name}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${n}-metadata`,children:[t.size&&e.jsxs("span",{children:[t.size," โ€ข "]}),t.uploadedBy&&e.jsxs("span",{children:["Uploaded by ",t.uploadedBy," on "]}),Qt(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&VS(t.fileType)&&s&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>s({fileName:t.name,fileType:t.fileType,documentId:t.documentId,fileSize:t.sizeBytes}),title:"Preview file","data-testid":`${n}-preview-btn`,children:e.jsx(ht,{className:"w-4 h-4"})}),a&&e.jsx(E,{variant:"ghost",size:"sm",onClick:async()=>{if(!t.documentId){alert("Document ID not available");return}try{await a(t.documentId)}catch{alert("Failed to download document")}},title:"Download file","data-testid":`${n}-download-btn`,children:e.jsx(Ct,{className:"w-4 h-4"})})]})]})}function zS({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l}){return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(ee,{children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx($e,{className:"text-xs sm:text-sm mt-1",children:"Documents attached while creating the request"})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsxs(E,{size:"sm",onClick:n,disabled:a||t.status==="closed",className:"gap-1 sm:gap-2 h-8 sm:h-9 text-xs sm:text-sm shrink-0","data-testid":"upload-document-btn",children:[e.jsx(zs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a?"Uploading...":t.status==="closed"?"Closed":"Upload",e.jsx("span",{className:"hidden sm:inline",children:t.status==="closed"?"":"Document"})]}),e.jsxs("p",{className:"text-xs text-gray-500 whitespace-nowrap",children:["Max ",r.maxFileSizeMB,"MB"]})]})]})}),e.jsx(se,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((o,c)=>e.jsx(Or,{document:o,onPreview:d=>i(d),onDownload:l,testId:"request-document"},c))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-documents",children:"No documents uploaded yet"})})]}),e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(As,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(se,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((o,c)=>e.jsx(Or,{document:{documentId:o.attachmentId||"",name:o.name,fileType:o.type||"",size:o.size?`${(o.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:o.size,uploadedBy:o.uploadedBy,uploadedAt:o.uploadedAt},onPreview:d=>i(d),onDownload:async d=>{const{downloadWorkNoteAttachment:m}=require("@/services/workflowApi");await m(d)},testId:"worknote-attachment"},o.attachmentId||c))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-attachments",children:"No files shared in work notes yet"})})]})]})}const HS=t=>{switch(t){case"express":case"urgent":return{color:"bg-red-100 text-red-800 border-red-200",label:"urgent priority"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"standard priority"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"normal priority"}}},WS=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending"};case"paused":return{color:"bg-gray-400 text-gray-100 border-gray-500",label:"paused"};case"in-review":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"in-review"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-300",label:"closed"};case"skipped":return{color:"bg-orange-100 text-orange-800 border-orange-200",label:"skipped"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t}}},GS=t=>{switch(t){case"approval":case"approved":return e.jsx(De,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(wt,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(As,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx($t,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(wi,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Re,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(st,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(vi,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(as,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(kt,{className:"w-5 h-5 text-gray-600"})}};function YS({request:t}){return e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(kt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(se,{children:e.jsx("div",{className:"space-y-4 sm:space-y-6",children:t.auditTrail&&t.auditTrail.length>0?t.auditTrail.map((s,a)=>e.jsxs("div",{className:"flex items-start gap-4","data-testid":`activity-item-${a}`,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center",children:GS(s.type)})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4 shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-gray-900",children:s.action}),e.jsx("span",{className:"text-xs text-gray-500 whitespace-nowrap ml-4",children:Qt(s.timestamp)})]}),e.jsx("div",{className:"text-sm text-gray-600 leading-relaxed",children:e.jsx("p",{className:"whitespace-pre-line break-words",children:s.details})})]})})]},a)):e.jsxs("div",{className:"text-center py-12","data-testid":"no-activity",children:[e.jsx(kt,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No activity recorded yet"}),e.jsx("p",{className:"text-xs text-gray-400 mt-2",children:"Actions and updates will appear here"})]})})})]})}function Lp({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsx(gt,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[a?e.jsx(De,{className:"w-5 h-5 text-green-600"}):e.jsx(ze,{className:"w-5 h-5 text-red-600"}),r||(a?"Success":"Error")]})}),e.jsx("div",{className:"py-6",children:e.jsx("div",{className:"flex flex-col items-center text-center",children:a?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mb-4",children:e.jsx(De,{className:"w-8 h-8 text-green-600"})}),e.jsx("p",{className:"text-sm text-gray-700",children:n||"Operation completed successfully!"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-red-100 flex items-center justify-center mb-4",children:e.jsx(wt,{className:"w-8 h-8 text-red-600"})}),e.jsx("p",{className:"text-sm text-gray-700",children:n||"Operation failed. Please try again."})]})})}),e.jsx(Tt,{children:e.jsx(E,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function Mp({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=p.useState(""),[l,o]=p.useState(!1),[c,d]=p.useState([]),[m,h]=p.useState(!1),[x,u]=p.useState(null),g=p.useRef(null),b=p.useRef(null),[f,y]=p.useState({open:!1,type:"error",email:"",message:""}),[v,w]=p.useState({open:!1,violations:[]}),[C,k]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});p.useEffect(()=>{t&&(async()=>{var P;try{const R=await Ys("WORKFLOW_SHARING"),O=await Ys("TAT_SETTINGS"),F=[...R,...O],$={};F.forEach(V=>{$[V.configKey]=V.configValue}),k({maxApprovalLevels:parseInt($.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt($.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((P=$.ALLOW_ADD_SPECTATOR)==null?void 0:P.toLowerCase())==="true",maxSpectators:parseInt($.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(R){console.error("Failed to load system policy:",R)}})()},[t]);const S=async()=>{var T,j;const N=n.trim().toLowerCase();if(!N){y({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(N)){y({open:!0,type:"error",email:N,message:"Please enter a valid email address"});return}const R=r.find(U=>(U.email||"").toLowerCase()===N);if(R){const U=((T=R.participantType)==null?void 0:T.toUpperCase())||"PARTICIPANT",I=R.name||N;if(U==="INITIATOR"){y({open:!0,type:"error",email:N,message:`${I} is the request initiator and cannot be added as a spectator.`});return}else if(U==="APPROVER"){y({open:!0,type:"error",email:N,message:`${I} is already an approver on this request and cannot be added as a spectator.`});return}else if(U==="SPECTATOR"){y({open:!0,type:"error",email:N,message:`${I} is already a spectator on this request.`});return}else{y({open:!0,type:"error",email:N,message:`${I} is already a participant on this request.`});return}}const O=[];C.allowSpectators||O.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const $=r.filter(U=>(U.participantType||"").toUpperCase()==="SPECTATOR").length;$>=C.maxSpectators&&O.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:$,maxValue:C.maxSpectators});const V=r.length+1;if(V>C.maxParticipants&&O.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:V,maxValue:C.maxParticipants}),O.length>0){w({open:!0,violations:O});return}if(!x||x.email.toLowerCase()!==N)try{const I=((j=(await ia(N,1)).data)==null?void 0:j.data)||[];if(I.length===0){y({open:!0,type:"not-found",email:N,message:""});return}const M=I[0];await ra({userId:M.userId,email:M.email,displayName:M.displayName,firstName:M.firstName,lastName:M.lastName,department:M.department,phone:M.phone,mobilePhone:M.mobilePhone,designation:M.designation,jobTitle:M.jobTitle,manager:M.manager,employeeId:M.employeeId,employeeNumber:M.employeeNumber,secondEmail:M.secondEmail,location:M.location})}catch(U){console.error("Failed to validate spectator:",U),y({open:!0,type:"error",email:N,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(N),i(""),u(null),s()}catch(U){console.error("Failed to add spectator:",U)}finally{o(!1)}},_=()=>{l||(i(""),u(null),d([]),h(!1),s())};p.useEffect(()=>{c.length>0&&b.current&&b.current.scrollTo({top:b.current.scrollHeight,behavior:"smooth"})},[c.length]),p.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const D=N=>{if(i(N),x&&x.email.toLowerCase()!==N.toLowerCase()&&u(null),g.current&&clearTimeout(g.current),!N||!N.startsWith("@")||N.length<2){d([]),h(!1);return}h(!0),g.current=setTimeout(async()=>{var P;try{const R=N.slice(1),F=((P=(await ia(R,10)).data)==null?void 0:P.data)||[];d(F)}catch(R){console.error("Search failed:",R),d([])}finally{h(!1)}},300)},A=async N=>{try{await ra({userId:N.userId,email:N.email,displayName:N.displayName,firstName:N.firstName,lastName:N.lastName,department:N.department,phone:N.phone,mobilePhone:N.mobilePhone,designation:N.designation,jobTitle:N.jobTitle,manager:N.manager,employeeId:N.employeeId,employeeNumber:N.employeeNumber,secondEmail:N.secondEmail,location:N.location}),i(N.email),u(N),d([]),h(!1)}catch(P){console.error("Failed to ensure user exists:",P),y({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(pt,{open:t,onOpenChange:_,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:_,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:l,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(gt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center",children:e.jsx(ht,{className:"w-5 h-5 text-purple-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:b,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a spectator to this request. They will receive notifications but cannot approve or reject."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ci,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Oe,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:N=>D(N.target.value),className:"pl-10 h-11 border-gray-300",disabled:l,autoFocus:!0}),(m||c.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:m?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):c.length>0?e.jsx("ul",{className:"divide-y",children:c.map(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>A(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zt,{className:"h-8 w-8",children:e.jsx(Jt,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(N.displayName||N.email).split(" ").map(P=>P[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:N.displayName||[N.firstName,N.lastName].filter(Boolean).join(" ")||N.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:N.email}),N.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:N.designation})]})]})},N.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:_,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:S,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(ht,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(pt,{open:f.open,onOpenChange:N=>y(P=>({...P,open:N})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:f.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[f.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:f.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Ni,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),f.type==="error"&&e.jsxs(e.Fragment,{children:[f.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:f.email}),"."]}),f.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:f.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:()=>y(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(Fn,{open:v.open,onClose:()=>w({open:!1,violations:[]}),violations:v.violations,policyDetails:{maxApprovalLevels:C.maxApprovalLevels,maxParticipants:C.maxParticipants,allowSpectators:C.allowSpectators,maxSpectators:C.maxSpectators}})]})}function $p({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=p.useState(""),[d,m]=p.useState(24),[h,x]=p.useState(null),[u,g]=p.useState(!1),[b,f]=p.useState([]),[y,v]=p.useState(!1),[w,C]=p.useState(null),k=p.useRef(null),S=p.useRef(null),[_,D]=p.useState({open:!1,type:"error",email:"",message:""}),A=n.filter(j=>j&&(j.status==="approved"||j.status==="rejected"||j.status==="skipped")),N=Math.max(1,A.length+1),P=Math.max(1,n.length+1),R=P>=N?Array.from({length:P-N+1},(j,U)=>N+U):[N];p.useEffect(()=>{R.length>0&&h===null&&x(R[0]||null)},[R.length,h]);const O=async()=>{var G,ce;const j=o.trim().toLowerCase();if(!j){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(j)){D({open:!0,type:"error",email:j,message:"Please enter a valid email address"});return}if(!d||d<=0){D({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(d>720){D({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!h){D({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(h0?Math.max(...n.map(te=>te.levelNumber),0):0,M=h>I?h:I+1;if(i&&M>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${h} would result in ${M} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:M,maxValue:i}]):D({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${I} level(s).`});return}const W=r.find(te=>(te.email||"").toLowerCase()===j);if(W){const te=((G=W.participantType)==null?void 0:G.toUpperCase())||"PARTICIPANT",L=W.name||j;if(te==="INITIATOR"){D({open:!0,type:"error",email:j,message:`${L} is the request initiator and cannot be added as an approver.`});return}else if(te==="APPROVER"){D({open:!0,type:"error",email:j,message:`${L} is already an approver on this request.`});return}else if(te==="SPECTATOR"){D({open:!0,type:"error",email:j,message:`${L} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{D({open:!0,type:"error",email:j,message:`${L} is already a participant on this request.`});return}}if(!w||w.email.toLowerCase()!==j)try{const L=((ce=(await ia(j,1)).data)==null?void 0:ce.data)||[];if(L.length===0){D({open:!0,type:"not-found",email:j,message:""});return}const z=L[0];await ra({userId:z.userId,email:z.email,displayName:z.displayName,firstName:z.firstName,lastName:z.lastName,department:z.department,phone:z.phone,mobilePhone:z.mobilePhone,designation:z.designation,jobTitle:z.jobTitle,manager:z.manager,employeeId:z.employeeId,employeeNumber:z.employeeNumber,secondEmail:z.secondEmail,location:z.location})}catch(te){console.error("Failed to validate approver:",te),D({open:!0,type:"error",email:j,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(j,d,h),c(""),m(24),x(null),C(null),s()}catch(te){console.error("Failed to add approver:",te)}finally{g(!1)}},F=()=>{u||(c(""),m(24),x(null),C(null),f([]),v(!1),s())},$=j=>{const U=j.toLowerCase();return U==="approved"?e.jsx(De,{className:"w-4 h-4 text-green-600"}):U==="rejected"?e.jsx(wt,{className:"w-4 h-4 text-red-600"}):U==="skipped"?e.jsx(ze,{className:"w-4 h-4 text-orange-600"}):U==="in-review"||U==="pending"?e.jsx(st,{className:"w-4 h-4 text-blue-600"}):e.jsx(st,{className:"w-4 h-4 text-gray-400"})};p.useEffect(()=>{b.length>0&&S.current&&S.current.scrollTo({top:S.current.scrollHeight,behavior:"smooth"})},[b.length]),p.useEffect(()=>()=>{k.current&&clearTimeout(k.current)},[]);const V=j=>{if(c(j),w&&w.email.toLowerCase()!==j.toLowerCase()&&C(null),k.current&&clearTimeout(k.current),!j||!j.startsWith("@")||j.length<2){f([]),v(!1);return}v(!0),k.current=setTimeout(async()=>{var U;try{const I=j.slice(1),W=((U=(await ia(I,10)).data)==null?void 0:U.data)||[];f(W)}catch(I){console.error("Search failed:",I),f([])}finally{v(!1)}},300)},T=async j=>{try{await ra({userId:j.userId,email:j.email,displayName:j.displayName,firstName:j.firstName,lastName:j.lastName,department:j.department,phone:j.phone,mobilePhone:j.mobilePhone,designation:j.designation,jobTitle:j.jobTitle,manager:j.manager,employeeId:j.employeeId,employeeNumber:j.employeeNumber,secondEmail:j.secondEmail,location:j.location}),c(j.email),C(j),f([]),v(!1)}catch(U){console.error("Failed to ensure user exists:",U),D({open:!0,type:"error",email:j.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(pt,{open:t,onOpenChange:F,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:F,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:u,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(gt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(cs,{className:"w-5 h-5 text-blue-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:S,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a new approver at a specific level. Existing approvers at and after the selected level will be shifted down."}),i&&e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-2",children:e.jsxs("p",{className:"text-xs text-blue-800",children:["โ„น๏ธ Max: ",i," level",i!==1?"s":"",n.length>0&&e.jsxs("span",{className:"ml-2",children:["(",Math.max(...n.map(j=>j.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-semibold text-gray-700",children:"Current Approval Levels"}),e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-2 border rounded-lg p-3 bg-gray-50",children:n.map(j=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${j.status==="approved"?"bg-green-100 border border-green-200":j.status==="rejected"?"bg-red-100 border border-red-200":j.status==="skipped"?"bg-orange-100 border border-orange-200":"bg-white border border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-blue-600 text-white text-xs font-semibold flex items-center justify-center",children:j.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:j.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[j.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[$(j.status),e.jsx(ne,{variant:"outline",className:`text-xs ${j.status==="approved"?"bg-green-50 text-green-700 border-green-300":j.status==="rejected"?"bg-red-50 text-red-700 border-red-300":j.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:j.status})]})]},j.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:["โ„น๏ธ New approver can only be added at level ",N," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(We,{value:(h==null?void 0:h.toString())||"",onValueChange:j=>x(Number(j)),disabled:u,children:[e.jsx(Ye,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select level"})}),e.jsx(Ke,{children:R.map(j=>e.jsx(Y,{value:j.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",j]}),j<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",j,")"]})]})},j))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Choose where to insert the new approver. Existing levels will be automatically shifted."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{type:"number",min:"1",max:"720",value:d,onChange:j=>m(Number(j.target.value)),className:"h-11 border-gray-300 flex-1",disabled:u,placeholder:"24"}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-600 bg-gray-100 px-3 h-11 rounded-md border border-gray-300",children:[e.jsx(st,{className:"w-4 h-4"}),"hours"]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum time for this approver to respond (1-720 hours)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ci,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Oe,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:j=>V(j.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(y||b.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:y?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):b.length>0?e.jsx("ul",{className:"divide-y",children:b.map(j=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>T(j),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zt,{className:"h-8 w-8",children:e.jsx(Jt,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(j.displayName||j.email).split(" ").map(U=>U[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:j.displayName||[j.firstName,j.lastName].filter(Boolean).join(" ")||j.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:j.email}),j.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:j.designation})]})]})},j.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:F,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:O,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!o.trim()||!h||!d,children:[e.jsx(cs,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${h||"?"}`]})]})]}),e.jsx(pt,{open:_.open,onOpenChange:j=>D(U=>({...U,open:j})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:_.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[_.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:_.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Ni,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),_.type==="error"&&e.jsxs(e.Fragment,{children:[_.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:_.email}),"."]}),_.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:_.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:()=>D(j=>({...j,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const KS=t=>{switch(t){case"online":return"bg-green-500";case"away":return"bg-yellow-500";case"offline":return"bg-gray-400";default:return"bg-gray-400"}},XS=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},ZS=t=>{const s=t.replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,(a,r,n,i)=>{const l=n+a.length,o=i[l];return!o||/\s|[.,!?;:]|@/.test(o)?'@'+r+"":a}).replace(/\n/g,"
");return ba(s)},JS=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",wu=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Re,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(d0,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Re,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Re,{className:`${s} text-blue-600`}):a.includes("image")||a.includes("png")||a.includes("jpg")||a.includes("jpeg")||a.includes("gif")||a.includes("webp")?e.jsx(Wn,{className:`${s} text-purple-600`}):e.jsx(vi,{className:`${s} text-gray-600`})};function Op({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:c=[],onAddApprover:d,maxApprovalLevels:m,onPolicyViolation:h}){const x=Ea(),u=t||x.requestId||"",[g,b]=p.useState(""),[f,y]=p.useState(""),[v,w]=p.useState(!1),[C,k]=p.useState([]),[S,_]=p.useState(!1),[D,A]=p.useState([]),[N,P]=p.useState(null),[R,O]=p.useState(null),[F,$]=p.useState(!1),[V,T]=p.useState(!1),[j,U]=p.useState(!1),[I,M]=p.useState({success:!0,title:"",message:""}),W=p.useRef(null),G=p.useRef(null),ce=p.useRef(null),te=p.useRef(!1),[L,z]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[H,ye]=p.useState({open:!1,errors:[]}),ae=p.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[me,Q]=p.useState([]),oe=me.filter(X=>X.status==="online"),Ce=C.filter(X=>X.content.toLowerCase().includes(f.toLowerCase())||X.user.name.toLowerCase().includes(f.toLowerCase())),Ee=p.useMemo(()=>o!==void 0?o:!N||me.length===0?!1:me.some(X=>{const we=X.userId||X.user_id,J=(X.role||"").toString().toUpperCase(),Le=(X.participantType||X.participant_type||"").toString().toUpperCase();return we===N&&(J==="SPECTATOR"||Le==="SPECTATOR")}),[o,N,me]);p.useEffect(()=>{},[me]),p.useEffect(()=>{!u||!N||s||(async()=>{try{const X=await Fr(u),we=Array.isArray(X)?X.map(J=>{const Le=J.userId||J.user_id;return{id:J.noteId||J.id||String(Math.random()),user:{name:J.userName||"User",avatar:(J.userName||"U").slice(0,2).toUpperCase(),role:J.userRole||"Participant"},content:J.message||"",timestamp:J.createdAt||new Date().toISOString(),isCurrentUser:Le===N,attachments:Array.isArray(J.attachments)?J.attachments.map(Fe=>({attachmentId:Fe.attachmentId||Fe.attachment_id,name:Fe.fileName||Fe.file_name||Fe.name,fileName:Fe.fileName||Fe.file_name||Fe.name,url:Fe.storageUrl||Fe.storage_url||Fe.url||"#",type:Fe.fileType||Fe.file_type||Fe.type||"file",fileType:Fe.fileType||Fe.file_type||Fe.type||"file",fileSize:Fe.fileSize||Fe.file_size})):void 0}}):[];k(we)}catch(X){console.error("[WorkNoteChat] Failed to load messages:",X)}})()},[u,N,s]);const be=p.useMemo(()=>{const X=[];return C.forEach(we=>{we.attachments&&we.attachments.length>0&&we.attachments.forEach(J=>{X.push({attachmentId:J.attachmentId||J.attachment_id,name:J.fileName||J.file_name||J.name||"Untitled",fileName:J.fileName||J.file_name||J.name||"Untitled",size:J.fileSize||J.file_size,type:J.fileType||J.file_type||J.type||"file",uploadedBy:we.user.name,uploadedAt:we.timestamp,url:J.storageUrl||J.storage_url||J.url||"#"})})}),X},[C]);p.useEffect(()=>{i&&be.length>=0&&i(be)},[be,i]);const q=p.useMemo(()=>me.map(X=>({email:(X.email||"").toLowerCase(),participantType:X.role==="Initiator"?"INITIATOR":X.role==="Approver"?"APPROVER":X.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:X.name})),[me]),ue=X=>{if(!X)return"Participant";switch(X.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()}},Ae=()=>{var X;(X=W.current)==null||X.scrollIntoView({behavior:"smooth"})};p.useEffect(()=>{Ae()},[C]);const Ue=X=>{switch(X.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()}};p.useEffect(()=>{te.current||u&&(async()=>{try{const X=await vs(u),we=Array.isArray(X==null?void 0:X.participants)?X.participants:[];if(we.length===0)return;const J=we.map(Me=>{const Ze=Me.participantType||Me.participant_type||"participant",Be=Me.userId||Me.user_id||"";return{name:Me.userName||Me.user_name||Me.user_email||Me.userEmail||"User",avatar:(Me.userName||Me.user_name||Me.user_email||"U").toString().split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ue(Ze.toString()),status:"offline",email:Me.userEmail||Me.user_email||"",permissions:["read","write","mention"],userId:Be}});te.current=!0,Q(J);let Le=0;const Fe=3,Ve=()=>{ce.current&&ce.current.connected?(ce.current.emit("request:online-users",{requestId:u}),Le++,Le()=>{u&&(te.current=!1)},[u]),p.useEffect(()=>{const X=localStorage.getItem("userData");if(X)try{const we=JSON.parse(X),J=(we==null?void 0:we.id)||(we==null?void 0:we.userId)||(we==null?void 0:we.user_id)||null;P(J)}catch(we){console.error("[WorkNoteChat] Failed to parse userData:",we)}},[]),p.useEffect(()=>{(async()=>{try{const we=await Ys("DOCUMENT_POLICY"),J={};we.forEach(Me=>{J[Me.configKey]=Me.configValue});const Le=parseInt(J.MAX_FILE_SIZE_MB||"10"),Ve=(J.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Me=>Me.trim().toLowerCase());z({maxFileSizeMB:Le,allowedFileTypes:Ve})}catch(we){console.error("Failed to load document policy:",we)}})()},[]),p.useEffect(()=>{if(!N)return;let X=u;return(async()=>{var we;try{const J=await vs(u);(we=J==null?void 0:J.workflow)!=null&&we.requestId&&(X=J.workflow.requestId)}catch{}try{const J=Lr();r?Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)):(Ml(J,X,N),Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)));const Le=at=>{const et=(at==null?void 0:at.note)||at;if(!et)return;const yt=et.noteId||et.id;k(rs=>{if(rs.some(St=>St.id===yt))return rs;const Pt=et.userName||et.user_name||"User",la=et.userRole||et.user_role,pa=ue(la),Fa=et.userId||et.user_id,wa={id:yt||String(Date.now()),user:{name:Pt,avatar:Pt.split(" ").map(St=>St[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:pa},content:et.message||"",timestamp:et.createdAt||new Date().toISOString(),isCurrentUser:Fa===N,attachments:Array.isArray(et.attachments)?et.attachments.map(St=>({attachmentId:St.attachmentId||St.attachment_id,name:St.fileName||St.file_name||St.name,fileName:St.fileName||St.file_name||St.name,url:St.storageUrl||St.storage_url||St.url||"#",type:St.fileType||St.file_type||St.type||"file",fileType:St.fileType||St.file_type||St.type||"file",fileSize:St.fileSize||St.file_size})):void 0};return[...rs,wa]})},Fe=at=>{Q(et=>et.length===0||!et.find(Pt=>Pt.userId===at.userId)?et:et.map(Pt=>Pt.userId===at.userId?{...Pt,status:"online"}:Pt))},Ve=at=>{at.userId!==N&&Q(et=>et.length===0||!et.find(Pt=>Pt.userId===at.userId)?et:et.map(Pt=>Pt.userId===at.userId?{...Pt,status:"offline"}:Pt))},Me=at=>{Q(et=>et.length===0?et:et.map(rs=>{const Pt=rs.userId||"";if(Pt===N)return{...rs,status:"online"};const pa=at.userIds.includes(Pt);return{...rs,status:pa?"online":"offline"}}))},Ze=()=>{Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)),r||Ml(J,X,N),te.current&&(J.emit("request:online-users",{requestId:X}),setTimeout(()=>J.emit("request:online-users",{requestId:X}),300),setTimeout(()=>J.emit("request:online-users",{requestId:X}),800))},Be=at=>{console.error("[WorkNoteChat] โŒ Socket error:",at)},qe=at=>{console.warn("[WorkNoteChat] โš ๏ธ Socket disconnected:",at),Q(et=>et.map(yt=>yt.userId===N?yt:{...yt,status:"offline"}))},fs=at=>{at.includes("presence")||at.includes("worknote")||at.includes("request")};J.on("connect",Ze),J.on("disconnect",qe),J.on("error",Be),J.on("worknote:new",Le),J.on("presence:join",Fe),J.on("presence:leave",Ve),J.on("presence:online",Me),J.onAny(fs),ce.current=J,J.connected&&te.current&&(J.emit("request:online-users",{requestId:X}),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},300),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},800),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},1500));const Ht=()=>{J.off("connect",Ze),J.off("disconnect",qe),J.off("error",Be),J.off("worknote:new",Le),J.off("presence:join",Fe),J.off("presence:leave",Ve),J.off("presence:online",Me),J.offAny(fs),r||Ax(J,X),ce.current=null};window.__wn_cleanup=Ht}catch{}})(),()=>{var we;try{(we=window.__wn_cleanup)==null||we.call(window)}catch{}}},[u,N,r]);const Z=async()=>{if(g.trim()||D.length>0){const X=Xs(g),we=X.map(Fe=>{const Ve=me.find(Me=>Me.name.toLowerCase().includes(Fe.toLowerCase()));return Ve==null?void 0:Ve.userId}).filter(Boolean),J=D.map(Fe=>({name:Fe.name,url:URL.createObjectURL(Fe),type:Fe.type.split("/")[1]||"file"})),Le={id:Date.now().toString(),user:{name:"You",avatar:"YO",role:"Current User"},content:g,timestamp:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),mentions:X,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:J.length>0?J:void 0,isCurrentUser:!0};if(a)try{await a(g,D)}catch{}else try{await Bx(u,{message:g,mentions:we},D);const Fe=await Fr(u),Ve=Array.isArray(Fe)?Fe.map(Me=>{const Ze=Me.userId||Me.user_id;return{id:Me.noteId||Me.id||String(Math.random()),user:{name:Me.userName||"User",avatar:(Me.userName||"U").slice(0,2).toUpperCase(),role:Me.userRole||"Participant"},content:Me.message||"",timestamp:Me.createdAt||new Date().toISOString(),isCurrentUser:Ze===N,attachments:Array.isArray(Me.attachments)?Me.attachments.map(Be=>({attachmentId:Be.attachmentId||Be.attachment_id,name:Be.fileName||Be.file_name||Be.name,fileName:Be.fileName||Be.file_name||Be.name,url:Be.storageUrl||Be.storage_url||Be.url||"#",type:Be.fileType||Be.file_type||Be.type||"file",fileType:Be.fileType||Be.file_type||Be.type||"file",fileSize:Be.fileSize||Be.file_size})):void 0}}):[];k(Ve)}catch{k(Fe=>[...Fe,Le])}b(""),A([])}};p.useEffect(()=>{if(s&&Array.isArray(s))try{const we=s.filter(J=>(J.type||"").toLowerCase()!=="sla_warning").map(J=>{var Fe;if(J.type||J.activityType||J.isSystem)return{id:J.id||`activity-${J.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:J.details||J.action||J.content||"",timestamp:J.timestamp||J.createdAt||J.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const Ve=J.userName||J.user_name||((Fe=J.user)==null?void 0:Fe.name)||"User",Me=J.userRole||J.user_role,Ze=ue(Me),Be=J.userId||J.user_id;return{id:J.noteId||J.note_id||J.id||String(Math.random()),user:{name:Ve,avatar:Ve.split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ze},content:J.message||J.content||"",timestamp:J.createdAt||J.created_at||J.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(J.attachments)?J.attachments.map(qe=>({attachmentId:qe.attachmentId||qe.attachment_id,name:qe.fileName||qe.file_name||qe.name,fileName:qe.fileName||qe.file_name||qe.name,url:qe.storageUrl||qe.storage_url||qe.url||"#",type:qe.fileType||qe.file_type||qe.type||"file",fileType:qe.fileType||qe.file_type||qe.type||"file",fileSize:qe.fileSize||qe.file_size})):void 0,isCurrentUser:Be===N}}}).sort((J,Le)=>new Date(J.timestamp).getTime()-new Date(Le.timestamp).getTime());k(we)}catch(X){console.error("[WorkNoteChat] Error mapping messages:",X)}else(async()=>{try{const X=await Fr(u),we=Array.isArray(X)?X.map(J=>{const Le=J.userName||J.user_name||"User",Fe=J.userRole||J.user_role,Ve=ue(Fe),Me=J.userId||J.user_id;return{id:J.noteId||J.note_id||J.id||String(Math.random()),user:{name:Le,avatar:Le.split(" ").map(Ze=>Ze[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ve},content:J.message||"",timestamp:J.createdAt||J.created_at||new Date().toISOString(),attachments:Array.isArray(J.attachments)?J.attachments.map(Ze=>({attachmentId:Ze.attachmentId||Ze.attachment_id,name:Ze.fileName||Ze.file_name||Ze.name,fileName:Ze.fileName||Ze.file_name||Ze.name,url:Ze.storageUrl||Ze.storage_url||Ze.url||"#",type:Ze.fileType||Ze.file_type||Ze.type||"file",fileType:Ze.fileType||Ze.file_type||Ze.type||"file",fileSize:Ze.fileSize||Ze.file_size})):void 0,isCurrentUser:Me===N}}):[];k(we)}catch(X){console.error("[WorkNoteChat] Error loading work notes:",X)}})()},[s,u,me]);const Te=X=>{const we=L.maxFileSizeMB*1024*1024;if(X.size>we)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${L.maxFileSizeMB}MB. Current size: ${(X.size/(1024*1024)).toFixed(2)}MB`};const J=X.name.toLowerCase(),Le=J.substring(J.lastIndexOf(".")+1);return L.allowedFileTypes.includes(Le)?{valid:!0}:{valid:!1,reason:`File type "${Le}" is not allowed. Allowed types: ${L.allowedFileTypes.join(", ")}`}},Xe=X=>{if(!X.target.files||X.target.files.length===0)return;const we=Array.from(X.target.files),J=[],Le=[];we.forEach(Fe=>{const Ve=Te(Fe);Ve.valid?Le.push(Fe):J.push({fileName:Fe.name,reason:Ve.reason||"Unknown validation error"})}),J.length>0&&ye({open:!0,errors:J}),Le.length>0&&(A(Fe=>[...Fe,...Le]),Le.length{A(we=>we.filter((J,Le)=>Le!==X)),G.current&&(G.current.value="")},_e=X=>{b(we=>we+X),w(!1)},rt=()=>{var X;(X=G.current)==null||X.click()},ut=async X=>{var we,J;try{await zx(u,X);const Le=await vs(u),Fe=Array.isArray(Le==null?void 0:Le.participants)?Le.participants:[];if(Fe.length){const Ve=Fe.map(Me=>{const Ze=Me.participantType||Me.participant_type||"participant",Be=Me.userId||Me.user_id||"",qe=Me.userName||Me.user_name||Me.userEmail||Me.user_email||"User",fs=Me.userEmail||Me.user_email||"",Ht=qe.split(" ").map(at=>at[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:qe,avatar:Ht,role:Ue(Ze),status:"offline",email:fs,lastSeen:void 0,permissions:["read"],userId:Be}});Q(Ve),ce.current&&ce.current.connected&&ce.current.emit("request:online-users",{requestId:u})}$(!1),M({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),U(!0)}catch(Le){throw console.error("Failed to add spectator:",Le),M({success:!1,title:"Failed to Add Spectator",message:((J=(we=Le==null?void 0:Le.response)==null?void 0:we.data)==null?void 0:J.error)||"Failed to add spectator. Please try again."}),U(!0),Le}},nt=async(X,we,J)=>{var Le,Fe;if(d)await d(X,we,J),T(!1);else try{await Vx(u,X,we,J);const Ve=await vs(u),Me=Array.isArray(Ve==null?void 0:Ve.participants)?Ve.participants:[];if(Me.length){const Ze=Me.map(Be=>{const qe=Be.participantType||Be.participant_type||"participant",fs=Be.userId||Be.user_id||"",Ht=Be.userName||Be.user_name||Be.userEmail||Be.user_email||"User",at=Be.userEmail||Be.user_email||"",et=Ht.split(" ").map(yt=>yt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Ht,avatar:et,role:Ue(qe),status:"offline",email:at,lastSeen:void 0,permissions:["read"],userId:fs}});Q(Ze),ce.current&&ce.current.connected&&ce.current.emit("request:online-users",{requestId:u})}T(!1),M({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${J} with ${we}h TAT`}),U(!0)}catch(Ve){throw console.error("Failed to add approver:",Ve),M({success:!1,title:"Failed to Add Approver",message:((Fe=(Le=Ve==null?void 0:Ve.response)==null?void 0:Le.data)==null?void 0:Fe.error)||"Failed to add approver. Please try again."}),U(!0),Ve}},Ps=["๐Ÿ˜Š","๐Ÿ˜‚","๐Ÿคฃ","๐Ÿ˜","๐Ÿ˜ƒ","๐Ÿ˜„","๐Ÿ˜…","๐Ÿ˜†","๐Ÿ˜‰","๐Ÿ˜Œ","๐Ÿ˜","๐Ÿฅฐ","๐Ÿ˜˜","๐Ÿ˜—","๐Ÿ˜™","๐Ÿ˜š","๐Ÿ™‚","๐Ÿค—","๐Ÿคฉ","๐Ÿค”","๐Ÿคจ","๐Ÿ˜","๐Ÿ˜‘","๐Ÿ˜ถ","๐Ÿ™„","๐Ÿ˜","๐Ÿ˜’","๐Ÿ™ƒ","๐Ÿ˜ฌ","๐Ÿค","๐Ÿ˜ด","๐Ÿ˜ช","๐Ÿ˜ต","๐Ÿคฏ","๐Ÿคช","๐Ÿ˜œ","๐Ÿ˜","๐Ÿ˜›","๐Ÿคค","๐Ÿ˜‹","๐Ÿ˜Ž","๐Ÿค“","๐Ÿง","๐Ÿ˜•","๐Ÿ˜Ÿ","๐Ÿ™","โ˜น๏ธ","๐Ÿ˜ฎ","๐Ÿ˜ฏ","๐Ÿ˜ฒ","๐Ÿ˜ณ","๐Ÿฅบ","๐Ÿ˜ฆ","๐Ÿ˜ง","๐Ÿ˜จ","๐Ÿ˜ฐ","๐Ÿ˜ฅ","๐Ÿ˜ข","๐Ÿ˜ญ","๐Ÿ˜ฑ","๐Ÿ˜–","๐Ÿ˜ฃ","๐Ÿ˜ž","๐Ÿ˜“","๐Ÿ˜ฉ","๐Ÿ˜ซ","๐Ÿฅฑ","๐Ÿ˜ค","๐Ÿ˜ก","๐Ÿ˜ ","๐Ÿคฌ","๐Ÿ˜ˆ","๐Ÿ‘ฟ","๐Ÿ’€","โ˜ ๏ธ","๐Ÿ’ฉ","๐Ÿคก","๐Ÿ‘น","๐Ÿ‘บ","๐Ÿ‘ป","๐Ÿ‘‹","๐Ÿคš","๐Ÿ–๏ธ","โœ‹","๐Ÿ––","๐Ÿ‘Œ","๐ŸคŒ","๐Ÿค","โœŒ๏ธ","๐Ÿคž","๐ŸคŸ","๐Ÿค˜","๐Ÿค™","๐Ÿ‘ˆ","๐Ÿ‘‰","๐Ÿ‘†","๐Ÿ–•","๐Ÿ‘‡","โ˜๏ธ","๐Ÿ‘","๐Ÿ‘Ž","โœŠ","๐Ÿ‘Š","๐Ÿค›","๐Ÿคœ","๐Ÿ‘","๐Ÿ™Œ","๐Ÿ‘","๐Ÿคฒ","๐Ÿค","๐Ÿ™","๐Ÿ’ช","๐Ÿฆพ","๐Ÿฆฟ","๐Ÿฆต","๐Ÿฆถ","๐Ÿ‘‚","๐Ÿฆป","๐Ÿ‘ƒ","๐Ÿง ","โค๏ธ","๐Ÿงก","๐Ÿ’›","๐Ÿ’š","๐Ÿ’™","๐Ÿ’œ","๐Ÿ–ค","๐Ÿค","๐ŸคŽ","๐Ÿ’”","โฃ๏ธ","๐Ÿ’•","๐Ÿ’ž","๐Ÿ’“","๐Ÿ’—","๐Ÿ’–","๐Ÿ’˜","๐Ÿ’","๐Ÿ’Ÿ","โค๏ธโ€๐Ÿ”ฅ","๐Ÿ’ผ","๐Ÿ“Š","๐Ÿ“ˆ","๐Ÿ“‰","๐Ÿ’ป","โŒจ๏ธ","๐Ÿ–ฅ๏ธ","๐Ÿ–จ๏ธ","๐Ÿ–ฑ๏ธ","๐Ÿ’พ","๐Ÿ’ฟ","๐Ÿ“ฑ","โ˜Ž๏ธ","๐Ÿ“ž","๐Ÿ“Ÿ","๐Ÿ“ ","๐Ÿ“ง","โœ‰๏ธ","๐Ÿ“จ","๐Ÿ“ฉ","๐Ÿ“ฎ","๐Ÿ“ช","๐Ÿ“ซ","๐Ÿ“ฌ","๐Ÿ“ญ","๐Ÿ“„","๐Ÿ“ƒ","๐Ÿ“‘","๐Ÿ“","โœ๏ธ","โœ’๏ธ","๐Ÿ–Š๏ธ","๐Ÿ–‹๏ธ","๐Ÿ“","๐Ÿ“","๐Ÿ“Œ","๐Ÿ“","๐Ÿ—‚๏ธ","๐Ÿ“","๐Ÿ“‚","โœ…","โœ”๏ธ","โ˜‘๏ธ","๐ŸŽฏ","๐ŸŽ–๏ธ","๐Ÿ†","๐Ÿฅ‡","๐Ÿฅˆ","๐Ÿฅ‰","โญ","๐ŸŒŸ","โœจ","๐Ÿ’ซ","๐Ÿ”ฅ","๐Ÿ’ฅ","โšก","๐Ÿ’ฏ","๐ŸŽ‰","๐ŸŽŠ","๐ŸŽˆ","โš ๏ธ","๐Ÿšซ","โŒ","โ›”","๐Ÿšท","๐Ÿšฏ","๐Ÿšฑ","๐Ÿšณ","๐Ÿ”ž","๐Ÿ“ต","โ—","โ“","โ•","โ”","โ€ผ๏ธ","โ‰๏ธ","๐Ÿ’ข","๐Ÿ’ฌ","๐Ÿ’ญ","๐Ÿ—ฏ๏ธ","โฐ","โฑ๏ธ","โฒ๏ธ","โณ","โŒ›","๐Ÿ“…","๐Ÿ“†","๐Ÿ—“๏ธ","๐Ÿ“‡","๐Ÿ•","๐Ÿ•‘","๐Ÿ•’","๐Ÿ•“","๐Ÿ•”","๐Ÿ••","๐Ÿ•–","๐Ÿ•—","๐Ÿ•˜","๐Ÿ•™","๐Ÿ•š","๐Ÿš€","๐ŸŽฏ","๐ŸŽฒ","๐ŸŽฐ","๐Ÿงฉ","๐Ÿ”","๐Ÿ”Ž","๐Ÿ”‘","๐Ÿ—๏ธ","๐Ÿ”’","๐Ÿ”“","๐Ÿ”","๐Ÿ”","๐Ÿ””","๐Ÿ”•","๐Ÿ“ฃ","๐Ÿ“ข","๐Ÿ’ก","๐Ÿ”ฆ","๐Ÿฎ","โž•","โž–","โœ–๏ธ","โž—","โ™พ๏ธ","โ€ผ๏ธ","โ‰๏ธ","โ“","โ”","โ•","๐Ÿ”„","๐Ÿ”ƒ","๐Ÿ”‚","โ–ถ๏ธ","โธ๏ธ","โฏ๏ธ","โน๏ธ","โบ๏ธ","โญ๏ธ","โฎ๏ธ","โฉ","โช","โซ","โฌ","โ—€๏ธ","๐Ÿ”ผ","๐Ÿ”ฝ","โžก๏ธ","โฌ…๏ธ","โฌ†๏ธ","โฌ‡๏ธ","โ†—๏ธ","โ†˜๏ธ","โ†™๏ธ","โ†–๏ธ","โ†•๏ธ","โ†”๏ธ","โ†ช๏ธ","โ†ฉ๏ธ","โคด๏ธ"],Xs=X=>{const we=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,J=[];let Le;for(;(Le=we.exec(X))!==null;)if(Le[1]){const Fe=Le.index+Le[0].length,Ve=X.slice(Fe),Me=X[Fe];(Ve.startsWith("@")||!Me||/\s|[.,!?;:]|@/.test(Me))&&J.push(Le[1].trim())}return J},Na=X=>{X.key==="Enter"&&!X.shiftKey&&(X.preventDefault(),Z())},Xa=(X,we)=>{k(J=>J.map(Le=>{if(Le.id===X){const Fe=Le.reactions||[],Ve=Fe.find(Me=>Me.emoji===we);if(Ve)if(Ve.users.includes("You")){if(Ve.users=Ve.users.filter(Me=>Me!=="You"),Ve.users.length===0)return{...Le,reactions:Fe.filter(Me=>Me.emoji!==we)}}else Ve.users.push("You");else Fe.push({emoji:we,users:["You"]});return{...Le,reactions:Fe}}return Le}))};return e.jsxs("div",{className:"h-full flex flex-col bg-gray-50 overflow-hidden",children:[e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg shrink-0",children:e.jsx(As,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"text-lg sm:text-2xl font-bold text-gray-900",children:"Work Notes"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("p",{className:"text-gray-600 text-sm sm:text-base truncate",children:ae.title}),e.jsx(ne,{variant:"outline",className:"text-xs shrink-0",children:t})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:e.jsxs("div",{className:"flex -space-x-2",children:[oe.slice(0,3).map((X,we)=>e.jsx(Zt,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:"bg-blue-500 text-white text-xs font-semibold",children:X.avatar})},we)),oe.length>3&&e.jsxs("div",{className:"h-8 w-8 rounded-full bg-gray-100 ring-2 ring-white flex items-center justify-center text-xs font-medium text-gray-600",children:["+",oe.length-3]})]})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>_(!S),className:"lg:hidden",children:e.jsx(cs,{className:"h-4 w-4"})})]})]})}),e.jsxs("div",{className:"flex-1 flex overflow-hidden relative",children:[e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx("div",{className:"bg-white border-b border-gray-200 px-2 sm:px-3 lg:px-6 py-2 sm:py-3 flex-shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Oe,{placeholder:"Search messages...",value:f,onChange:X=>y(X.target.value),className:"pl-10 bg-gray-50 border-gray-200 h-9 sm:h-10"})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-2 sm:px-3 lg:px-6 py-2 sm:py-4 min-h-0",children:e.jsxs("div",{className:"space-y-3 sm:space-y-6 max-w-full",children:[Ce.map(X=>{const we=X.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${X.isSystem?"justify-center":we?"justify-end":""}`,children:[!X.isSystem&&!we&&e.jsx(Zt,{className:"h-8 w-8 sm:h-10 sm:w-10 lg:h-12 lg:w-12 flex-shrink-0 ring-1 sm:ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:`text-white font-semibold text-xs sm:text-sm ${X.user.role==="Initiator"?"bg-green-600":X.user.role==="Current User"?"bg-blue-500":X.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:X.user.avatar})}),e.jsx("div",{className:`${we?"max-w-[70%]":"flex-1"} min-w-0 ${X.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:X.isSystem?e.jsxs("div",{className:"inline-flex items-center gap-2 sm:gap-3 px-3 sm:px-4 py-1.5 sm:py-2 bg-gray-100 rounded-full",children:[e.jsx(kt,{className:"w-3 h-3 sm:w-4 sm:h-4 text-gray-500 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm text-gray-700",children:X.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:Qt(X.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${we?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[X.user.name," ",we&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(ne,{variant:"outline",className:"text-xs flex-shrink-0",children:X.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(st,{className:"w-3 h-3"}),Qt(X.timestamp)]}),X.isHighPriority&&e.jsxs(ne,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(o0,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${we?"bg-blue-50 border-blue-200":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:"text-gray-800 leading-relaxed text-sm sm:text-base",dangerouslySetInnerHTML:{__html:ZS(X.content)}}),X.attachments&&X.attachments.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-100",children:e.jsx("div",{className:"space-y-2",children:X.attachments.map((J,Le)=>{const Fe=J.fileSize||J.file_size,Ve=J.fileName||J.file_name||J.name,Me=J.fileType||J.file_type||J.type||"",Ze=J.attachmentId||J.attachment_id;return e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 p-2 sm:p-3 bg-gray-50 rounded-lg border border-gray-200 hover:bg-gray-100 transition-colors",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx(wu,{type:Me})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs sm:text-sm font-medium text-gray-700 truncate",children:Ve}),Fe&&e.jsx("p",{className:"text-xs text-gray-500",children:JS(Fe)})]}),Ze&&(()=>{const Be=(Me||"").toLowerCase();return Be.includes("image")||Be.includes("pdf")||Be.includes("jpg")||Be.includes("jpeg")||Be.includes("png")||Be.includes("gif")})()&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-purple-100 hover:text-purple-600",onClick:Be=>{Be.preventDefault(),Be.stopPropagation();const qe=eN(Ze);O({fileName:Ve,fileType:Me,fileUrl:qe,fileSize:Fe,attachmentId:Ze})},title:"Preview file",children:e.jsx(ht,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-blue-100 hover:text-blue-600",onClick:async Be=>{if(Be.preventDefault(),Be.stopPropagation(),!Ze){K.error("Cannot download: Attachment ID missing");return}try{await Jd(Ze)}catch{K.error("Failed to download file")}},title:"Download file",children:e.jsx(Ct,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Le)})})}),X.reactions&&X.reactions.length>0&&e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-100 flex-wrap",children:[X.reactions.map((J,Le)=>e.jsxs("button",{onClick:()=>Xa(X.id,J.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${J.users.includes("You")?"bg-blue-100 text-blue-800 border border-blue-200":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,children:[e.jsx("span",{children:J.emoji}),e.jsx("span",{className:"text-xs font-medium",children:J.users.length})]},Le)),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>w(!v),children:e.jsx(gs,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!X.isSystem&&we&&e.jsx(Zt,{className:"h-8 w-8 sm:h-10 sm:w-10 lg:h-12 lg:w-12 flex-shrink-0 ring-1 sm:ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:X.user.avatar})})]},X.id)}),e.jsx("div",{ref:W})]})}),e.jsx("div",{className:"bg-white border-t border-gray-200 p-2 sm:p-3 lg:p-6 flex-shrink-0",children:e.jsxs("div",{className:"max-w-full",children:[e.jsx("input",{type:"file",ref:G,onChange:Xe,className:"hidden",multiple:!0,accept:L.allowedFileTypes.map(X=>`.${X}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((X,we)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-blue-50 rounded-lg border border-blue-200",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx(wu,{type:X.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:X.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(X.size/1024).toFixed(1)," KB"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>pe(we),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(ft,{className:"h-3 w-3 text-red-600"})})]},we))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const X=g.lastIndexOf("@"),we=X>=0;if(!we)return null;const J=g.slice(X+1),Le=J.trim(),Fe=J.endsWith(" "),Ve=Le.length>0,Me=Le.includes(" ")&&!Fe,Ze=Fe&&Ve;if(!(we&&J.length<=20&&!Me&&!Ze))return null;const qe=Le.toLowerCase(),fs=me.filter(Ht=>Ht.userId===N?!1:qe?Ht.name.toLowerCase().includes(qe):!0);return e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border-2 border-blue-300 rounded-lg shadow-2xl p-3 z-[100] w-full sm:max-w-md",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 mb-2",children:"๐Ÿ’ฌ Mention someone"}),e.jsx("div",{className:"max-h-60 overflow-y-auto space-y-1",children:fs.length>0?fs.map((Ht,at)=>e.jsxs("button",{type:"button",onClick:et=>{et.preventDefault(),et.stopPropagation();const yt=g.lastIndexOf("@"),rs=g.slice(0,yt);b(rs+"@"+Ht.name+" ")},className:"w-full flex items-center gap-3 p-3 hover:bg-blue-50 rounded-lg text-left transition-colors border border-transparent hover:border-blue-200",children:[e.jsx(Zt,{className:"h-10 w-10",children:e.jsx(Jt,{className:`text-white text-sm font-semibold ${Ht.role==="Initiator"?"bg-green-600":Ht.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:Ht.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:Ht.name}),e.jsx("p",{className:"text-xs text-gray-600",children:Ht.role})]})]},at)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:qe?`No participants found matching "${qe}"`:"No other participants available"})})]})})(),e.jsx(Ds,{placeholder:"Type your message... Use @username to mention someone",value:g,onChange:X=>b(X.target.value),onKeyPress:Na,className:"min-h-[50px] sm:min-h-[60px] resize-none border-gray-200 focus:ring-blue-500 focus:border-blue-500 w-full text-sm",rows:2}),v&&e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border border-gray-200 rounded-lg shadow-xl p-3 z-50 w-full sm:w-96 max-h-80 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 sticky top-0 bg-white pb-2 border-b",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-700",children:"Pick an emoji"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>w(!1),className:"h-6 w-6 p-0",children:e.jsx(ft,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:Ps.map((X,we)=>e.jsx("button",{onClick:()=>_e(X),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:X,children:X},we))})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-shrink-0",children:[e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:rt,title:"Attach file",children:e.jsx(vi,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>w(!v),title:"Add emoji",children:e.jsx(c0,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>b(X=>X+"@"),title:"Mention someone",children:e.jsx(Ci,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto flex-shrink-0",children:[e.jsxs("span",{className:"text-xs text-gray-500 hidden md:inline whitespace-nowrap",children:[g.length,"/2000"]}),e.jsxs(E,{onClick:Z,disabled:!g.trim()&&D.length===0,className:"bg-blue-600 hover:bg-blue-700 h-8 sm:h-9 px-3 sm:px-4 disabled:opacity-50 disabled:cursor-not-allowed flex-shrink-0",size:"sm",children:[e.jsx(ax,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),S&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>_(!1)}),e.jsxs("div",{className:` + `),()=>{f.contains(b)&&f.removeChild(b)}},[s]),e.jsx(u1,{isPresent:s,childRef:i,sizeRef:l,children:p.cloneElement(t,{ref:c})})}const h1=({children:t,initial:s,isPresent:a,onExitComplete:r,custom:n,presenceAffectsLayout:i,mode:l,anchorX:o,root:c})=>{const d=_o(p1),m=p.useId();let h=!0,x=p.useMemo(()=>(h=!1,{id:m,initial:s,isPresent:a,custom:n,onExitComplete:u=>{d.set(u,!0);for(const g of d.values())if(!g)return;r&&r()},register:u=>(d.set(u,!1),()=>d.delete(u))}),[a,d,r]);return i&&h&&(x={...x}),p.useMemo(()=>{d.forEach((u,g)=>d.set(g,!1))},[a]),p.useEffect(()=>{!a&&!d.size&&r&&r()},[a]),l==="popLayout"&&(t=e.jsx(x1,{isPresent:a,anchorX:o,root:c,children:t})),e.jsx(Ii.Provider,{value:x,children:t})};function p1(){return new Map}function Vh(t=!0){const s=p.useContext(Ii);if(s===null)return[!0,null];const{isPresent:a,onExitComplete:r,register:n}=s,i=p.useId();p.useEffect(()=>{if(t)return n(i)},[t]);const l=p.useCallback(()=>t&&r&&r(i),[i,r,t]);return!a&&r?[!1,l]:[!0]}const Un=t=>t.key||"";function ym(t){const s=[];return p.Children.forEach(t,a=>{p.isValidElement(a)&&s.push(a)}),s}const Ei=({children:t,custom:s,initial:a=!0,onExitComplete:r,presenceAffectsLayout:n=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",root:c})=>{const[d,m]=Vh(l),h=p.useMemo(()=>ym(t),[t]),x=l&&!d?[]:h.map(Un),u=p.useRef(!0),g=p.useRef(h),b=_o(()=>new Map),[f,y]=p.useState(h),[v,w]=p.useState(h);Jx(()=>{u.current=!1,g.current=h;for(let S=0;S{const _=Un(S),D=l&&!d?!1:h===v||x.includes(_),A=()=>{if(b.has(_))b.set(_,!0);else return;let N=!0;b.forEach(P=>{P||(N=!1)}),N&&(k==null||k(),w(g.current),l&&(m==null||m()),r&&r())};return e.jsx(h1,{isPresent:D,initial:!u.current||a?void 0:!1,custom:s,presenceAffectsLayout:n,mode:i,root:c,onExitComplete:D?void 0:A,anchorX:o,children:S},_)})})},zh=p.createContext({strict:!1}),vm={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},$r={};for(const t in vm)$r[t]={isEnabled:s=>vm[t].some(a=>!!s[a])};function g1(t){for(const s in t)$r[s]={...$r[s],...t[s]}}const f1=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function ui(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||f1.has(t)}let Hh=t=>!ui(t);function b1(t){typeof t=="function"&&(Hh=s=>s.startsWith("on")?!ui(s):t(s))}try{b1(require("@emotion/is-prop-valid").default)}catch{}function y1(t,s,a){const r={};for(const n in t)n==="values"&&typeof t.values=="object"||(Hh(n)||a===!0&&ui(n)||!s&&!ui(n)||t.draggable&&n.startsWith("onDrag"))&&(r[n]=t[n]);return r}const Fi=p.createContext({});function _i(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function vn(t){return typeof t=="string"||Array.isArray(t)}const nc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ic=["initial",...nc];function Li(t){return _i(t.animate)||ic.some(s=>vn(t[s]))}function Wh(t){return!!(Li(t)||t.variants)}function v1(t,s){if(Li(t)){const{initial:a,animate:r}=t;return{initial:a===!1||vn(a)?a:void 0,animate:vn(r)?r:void 0}}return t.inherit!==!1?s:{}}function j1(t){const{initial:s,animate:a}=v1(t,p.useContext(Fi));return p.useMemo(()=>({initial:s,animate:a}),[jm(s),jm(a)])}function jm(t){return Array.isArray(t)?t.join(" "):t}const jn={};function N1(t){for(const s in t)jn[s]=t[s],Ho(s)&&(jn[s].isCSSVariable=!0)}function Gh(t,{layout:s,layoutId:a}){return Yr.has(t)||t.startsWith("origin")||(s||a!==void 0)&&(!!jn[t]||t==="opacity")}const w1={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},C1=Gr.length;function S1(t,s,a){let r="",n=!0;for(let i=0;i({style:{},transform:{},transformOrigin:{},vars:{}});function Yh(t,s,a){for(const r in s)!js(s[r])&&!Gh(r,a)&&(t[r]=s[r])}function A1({transformTemplate:t},s){return p.useMemo(()=>{const a=oc();return lc(a,s,t),Object.assign({},a.vars,a.style)},[s])}function T1(t,s){const a=t.style||{},r={};return Yh(r,a,t),Object.assign(r,A1(t,s)),r}function k1(t,s){const a={},r=T1(t,s);return t.drag&&t.dragListener!==!1&&(a.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(a.tabIndex=0),a.style=r,a}const R1={offset:"stroke-dashoffset",array:"stroke-dasharray"},D1={offset:"strokeDashoffset",array:"strokeDasharray"};function P1(t,s,a=1,r=0,n=!0){t.pathLength=1;const i=n?R1:D1;t[i.offset]=Je.transform(-r);const l=Je.transform(s),o=Je.transform(a);t[i.array]=`${l} ${o}`}function Kh(t,{attrX:s,attrY:a,attrScale:r,pathLength:n,pathSpacing:i=1,pathOffset:l=0,...o},c,d,m){if(lc(t,o,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:h,style:x}=t;h.transform&&(x.transform=h.transform,delete h.transform),(x.transform||h.transformOrigin)&&(x.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),x.transform&&(x.transformBox=(m==null?void 0:m.transformBox)??"fill-box",delete h.transformBox),s!==void 0&&(h.x=s),a!==void 0&&(h.y=a),r!==void 0&&(h.scale=r),n!==void 0&&P1(h,n,i,l,!1)}const Xh=()=>({...oc(),attrs:{}}),Zh=t=>typeof t=="string"&&t.toLowerCase()==="svg";function I1(t,s,a,r){const n=p.useMemo(()=>{const i=Xh();return Kh(i,s,Zh(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[s]);if(t.style){const i={};Yh(i,t.style,t),n.style={...i,...n.style}}return n}const E1=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function cc(t){return typeof t!="string"||t.includes("-")?!1:!!(E1.indexOf(t)>-1||/[A-Z]/u.test(t))}function F1(t,s,a,{latestValues:r},n,i=!1){const o=(cc(t)?I1:k1)(s,r,n,t),c=y1(s,typeof t=="string",i),d=t!==p.Fragment?{...c,...o,ref:a}:{},{children:m}=s,h=p.useMemo(()=>js(m)?m.get():m,[m]);return p.createElement(t,{...d,children:h})}function Nm(t){const s=[{},{}];return t==null||t.values.forEach((a,r)=>{s[0][r]=a.get(),s[1][r]=a.getVelocity()}),s}function dc(t,s,a,r){if(typeof s=="function"){const[n,i]=Nm(r);s=s(a!==void 0?a:t.custom,n,i)}if(typeof s=="string"&&(s=t.variants&&t.variants[s]),typeof s=="function"){const[n,i]=Nm(r);s=s(a!==void 0?a:t.custom,n,i)}return s}function Jn(t){return js(t)?t.get():t}function _1({scrapeMotionValuesFromProps:t,createRenderState:s},a,r,n){return{latestValues:L1(a,r,n,t),renderState:s()}}function L1(t,s,a,r){const n={},i=r(t,{});for(const x in i)n[x]=Jn(i[x]);let{initial:l,animate:o}=t;const c=Li(t),d=Wh(t);s&&d&&!c&&t.inherit!==!1&&(l===void 0&&(l=s.initial),o===void 0&&(o=s.animate));let m=a?a.initial===!1:!1;m=m||l===!1;const h=m?o:l;if(h&&typeof h!="boolean"&&!_i(h)){const x=Array.isArray(h)?h:[h];for(let u=0;u(s,a)=>{const r=p.useContext(Fi),n=p.useContext(Ii),i=()=>_1(t,s,r,n);return a?i():_o(i)};function mc(t,s,a){var i;const{style:r}=t,n={};for(const l in r)(js(r[l])||s.style&&js(s.style[l])||Gh(l,t)||((i=a==null?void 0:a.getValue(l))==null?void 0:i.liveStyle)!==void 0)&&(n[l]=r[l]);return n}const M1=Jh({scrapeMotionValuesFromProps:mc,createRenderState:oc});function Qh(t,s,a){const r=mc(t,s,a);for(const n in t)if(js(t[n])||js(s[n])){const i=Gr.indexOf(n)!==-1?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n;r[i]=t[n]}return r}const $1=Jh({scrapeMotionValuesFromProps:Qh,createRenderState:Xh}),O1=Symbol.for("motionComponentSymbol");function Tr(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function U1(t,s,a){return p.useCallback(r=>{r&&t.onMount&&t.onMount(r),s&&(r?s.mount(r):s.unmount()),a&&(typeof a=="function"?a(r):Tr(a)&&(a.current=r))},[s])}const uc=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),B1="framerAppearId",qh="data-"+uc(B1),ep=p.createContext({});function V1(t,s,a,r,n){var b,f;const{visualElement:i}=p.useContext(Fi),l=p.useContext(zh),o=p.useContext(Ii),c=p.useContext(rc).reducedMotion,d=p.useRef(null);r=r||l.renderer,!d.current&&r&&(d.current=r(t,{visualState:s,parent:i,props:a,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:c}));const m=d.current,h=p.useContext(ep);m&&!m.projection&&n&&(m.type==="html"||m.type==="svg")&&z1(d.current,a,n,h);const x=p.useRef(!1);p.useInsertionEffect(()=>{m&&x.current&&m.update(a,o)});const u=a[qh],g=p.useRef(!!u&&!((b=window.MotionHandoffIsComplete)!=null&&b.call(window,u))&&((f=window.MotionHasOptimisedAnimation)==null?void 0:f.call(window,u)));return Jx(()=>{m&&(x.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),g.current&&m.animationState&&m.animationState.animateChanges())}),p.useEffect(()=>{m&&(!g.current&&m.animationState&&m.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,u)}),g.current=!1),m.enteringChildren=void 0)}),m}function z1(t,s,a,r){const{layoutId:n,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutCrossfade:m}=s;t.projection=new a(t.latestValues,s["data-framer-portal-id"]?void 0:tp(t.parent)),t.projection.setOptions({layoutId:n,layout:i,alwaysMeasureLayout:!!l||o&&Tr(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:m,layoutScroll:c,layoutRoot:d})}function tp(t){if(t)return t.options.allowProjection!==!1?t.projection:tp(t.parent)}function ul(t,{forwardMotionProps:s=!1}={},a,r){a&&g1(a);const n=cc(t)?$1:M1;function i(o,c){let d;const m={...p.useContext(rc),...o,layoutId:H1(o)},{isStatic:h}=m,x=j1(o),u=n(o,h);if(!h&&Lo){W1();const g=G1(m);d=g.MeasureLayout,x.visualElement=V1(t,u,m,r,g.ProjectionNode)}return e.jsxs(Fi.Provider,{value:x,children:[d&&x.visualElement?e.jsx(d,{visualElement:x.visualElement,...m}):null,F1(t,o,U1(u,x.visualElement,c),u,h,s)]})}i.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=p.forwardRef(i);return l[O1]=t,l}function H1({layoutId:t}){const s=p.useContext(Fo).id;return s&&t!==void 0?s+"-"+t:t}function W1(t,s){p.useContext(zh).strict}function G1(t){const{drag:s,layout:a}=$r;if(!s&&!a)return{};const r={...s,...a};return{MeasureLayout:s!=null&&s.isEnabled(t)||a!=null&&a.isEnabled(t)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function Y1(t,s){if(typeof Proxy>"u")return ul;const a=new Map,r=(i,l)=>ul(i,l,t,s),n=(i,l)=>r(i,l);return new Proxy(n,{get:(i,l)=>l==="create"?r:(a.has(l)||a.set(l,ul(l,void 0,t,s)),a.get(l))})}function sp({top:t,left:s,right:a,bottom:r}){return{x:{min:s,max:a},y:{min:t,max:r}}}function K1({x:t,y:s}){return{top:s.min,right:t.max,bottom:s.max,left:t.min}}function X1(t,s){if(!s)return t;const a=s({x:t.left,y:t.top}),r=s({x:t.right,y:t.bottom});return{top:a.y,left:a.x,bottom:r.y,right:r.x}}function xl(t){return t===void 0||t===1}function Jl({scale:t,scaleX:s,scaleY:a}){return!xl(t)||!xl(s)||!xl(a)}function or(t){return Jl(t)||ap(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function ap(t){return wm(t.x)||wm(t.y)}function wm(t){return t&&t!=="0%"}function xi(t,s,a){const r=t-a,n=s*r;return a+n}function Cm(t,s,a,r,n){return n!==void 0&&(t=xi(t,n,r)),xi(t,a,r)+s}function Ql(t,s=0,a=1,r,n){t.min=Cm(t.min,s,a,r,n),t.max=Cm(t.max,s,a,r,n)}function rp(t,{x:s,y:a}){Ql(t.x,s.translate,s.scale,s.originPoint),Ql(t.y,a.translate,a.scale,a.originPoint)}const Sm=.999999999999,Am=1.0000000000001;function Z1(t,s,a,r=!1){const n=a.length;if(!n)return;s.x=s.y=1;let i,l;for(let o=0;oSm&&(s.x=1),s.ySm&&(s.y=1)}function kr(t,s){t.min=t.min+s,t.max=t.max+s}function Tm(t,s,a,r,n=.5){const i=zt(t.min,t.max,n);Ql(t,s,a,i,r)}function Rr(t,s){Tm(t.x,s.x,s.scaleX,s.scale,s.originX),Tm(t.y,s.y,s.scaleY,s.scale,s.originY)}function np(t,s){return sp(X1(t.getBoundingClientRect(),s))}function J1(t,s,a){const r=np(t,a),{scroll:n}=s;return n&&(kr(r.x,n.offset.x),kr(r.y,n.offset.y)),r}const km=()=>({translate:0,scale:1,origin:0,originPoint:0}),Dr=()=>({x:km(),y:km()}),Rm=()=>({min:0,max:0}),Yt=()=>({x:Rm(),y:Rm()}),ql={current:null},ip={current:!1};function Q1(){if(ip.current=!0,!!Lo)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),s=()=>ql.current=t.matches;t.addEventListener("change",s),s()}else ql.current=!1}const q1=new WeakMap;function eC(t,s,a){for(const r in s){const n=s[r],i=a[r];if(js(n))t.addValue(r,n);else if(js(i))t.addValue(r,Mr(n,{owner:t}));else if(i!==n)if(t.hasValue(r)){const l=t.getValue(r);l.liveStyle===!0?l.jump(n):l.hasAnimated||l.set(n)}else{const l=t.getStaticValue(r);t.addValue(r,Mr(l!==void 0?l:n,{owner:t}))}}for(const r in a)s[r]===void 0&&t.removeValue(r);return s}const Dm=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class tC{scrapeMotionValuesFromProps(s,a,r){return{}}constructor({parent:s,props:a,presenceContext:r,reducedMotionConfig:n,blockInitialAnimation:i,visualState:l},o={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=qo,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const x=$s.now();this.renderScheduledAtthis.bindToMotionValue(n,r)),ip.current||Q1(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ql.current,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var s;this.projection&&this.projection.unmount(),Wa(this.notifyUpdate),Wa(this.render),this.valueSubscriptions.forEach(a=>a()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(s=this.parent)==null||s.removeChild(this);for(const a in this.events)this.events[a].clear();for(const a in this.features){const r=this.features[a];r&&(r.unmount(),r.isMounted=!1)}this.current=null}addChild(s){this.children.add(s),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(s)}removeChild(s){this.children.delete(s),this.enteringChildren&&this.enteringChildren.delete(s)}bindToMotionValue(s,a){this.valueSubscriptions.has(s)&&this.valueSubscriptions.get(s)();const r=Yr.has(s);r&&this.onBindTransform&&this.onBindTransform();const n=a.on("change",l=>{this.latestValues[s]=l,this.props.onUpdate&&Mt.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,s,a)),this.valueSubscriptions.set(s,()=>{n(),i&&i(),a.owner&&a.stop()})}sortNodePosition(s){return!this.current||!this.sortInstanceNodePosition||this.type!==s.type?0:this.sortInstanceNodePosition(this.current,s.current)}updateFeatures(){let s="animation";for(s in $r){const a=$r[s];if(!a)continue;const{isEnabled:r,Feature:n}=a;if(!this.features[s]&&n&&r(this.props)&&(this.features[s]=new n(this)),this.features[s]){const i=this.features[s];i.isMounted?i.update():(i.mount(),i.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):Yt()}getStaticValue(s){return this.latestValues[s]}setStaticValue(s,a){this.latestValues[s]=a}update(s,a){(s.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=s,this.prevPresenceContext=this.presenceContext,this.presenceContext=a;for(let r=0;ra.variantChildren.delete(s)}addValue(s,a){const r=this.values.get(s);a!==r&&(r&&this.removeValue(s),this.bindToMotionValue(s,a),this.values.set(s,a),this.latestValues[s]=a.get())}removeValue(s){this.values.delete(s);const a=this.valueSubscriptions.get(s);a&&(a(),this.valueSubscriptions.delete(s)),delete this.latestValues[s],this.removeValueFromRenderState(s,this.renderState)}hasValue(s){return this.values.has(s)}getValue(s,a){if(this.props.values&&this.props.values[s])return this.props.values[s];let r=this.values.get(s);return r===void 0&&a!==void 0&&(r=Mr(a===null?void 0:a,{owner:this}),this.addValue(s,r)),r}readValue(s,a){let r=this.latestValues[s]!==void 0||!this.current?this.latestValues[s]:this.getBaseTargetFromProps(this.props,s)??this.readValueFromInstance(this.current,s,this.options);return r!=null&&(typeof r=="string"&&(Qx(r)||eh(r))?r=parseFloat(r):!c1(r)&&Ga.test(a)&&(r=_h(s,a)),this.setBaseTarget(s,js(r)?r.get():r)),js(r)?r.get():r}setBaseTarget(s,a){this.baseTarget[s]=a}getBaseTarget(s){var i;const{initial:a}=this.props;let r;if(typeof a=="string"||typeof a=="object"){const l=dc(this.props,a,(i=this.presenceContext)==null?void 0:i.custom);l&&(r=l[s])}if(a&&r!==void 0)return r;const n=this.getBaseTargetFromProps(this.props,s);return n!==void 0&&!js(n)?n:this.initialValues[s]!==void 0&&r===void 0?void 0:this.baseTarget[s]}on(s,a){return this.events[s]||(this.events[s]=new Bo),this.events[s].add(a)}notify(s,...a){this.events[s]&&this.events[s].notify(...a)}scheduleRenderMicrotask(){sc.render(this.render)}}class lp extends tC{constructor(){super(...arguments),this.KeyframeResolver=Jw}sortInstanceNodePosition(s,a){return s.compareDocumentPosition(a)&2?1:-1}getBaseTargetFromProps(s,a){return s.style?s.style[a]:void 0}removeValueFromRenderState(s,{vars:a,style:r}){delete a[s],delete r[s]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:s}=this.props;js(s)&&(this.childSubscription=s.on("change",a=>{this.current&&(this.current.textContent=`${a}`)}))}}function op(t,{style:s,vars:a},r,n){const i=t.style;let l;for(l in s)i[l]=s[l];n==null||n.applyProjectionStyles(i,r);for(l in a)i.setProperty(l,a[l])}function sC(t){return window.getComputedStyle(t)}class aC extends lp{constructor(){super(...arguments),this.type="html",this.renderInstance=op}readValueFromInstance(s,a){var r;if(Yr.has(a))return(r=this.projection)!=null&&r.isProjecting?Hl(a):gw(s,a);{const n=sC(s),i=(Ho(a)?n.getPropertyValue(a):n[a])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(s,{transformPagePoint:a}){return np(s,a)}build(s,a,r){lc(s,a,r.transformTemplate)}scrapeMotionValuesFromProps(s,a,r){return mc(s,a,r)}}const cp=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function rC(t,s,a,r){op(t,s,void 0,r);for(const n in s.attrs)t.setAttribute(cp.has(n)?n:uc(n),s.attrs[n])}class nC extends lp{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Yt}getBaseTargetFromProps(s,a){return s[a]}readValueFromInstance(s,a){if(Yr.has(a)){const r=Fh(a);return r&&r.default||0}return a=cp.has(a)?a:uc(a),s.getAttribute(a)}scrapeMotionValuesFromProps(s,a,r){return Qh(s,a,r)}build(s,a,r){Kh(s,a,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(s,a,r,n){rC(s,a,r,n)}mount(s){this.isSVGTag=Zh(s.tagName),super.mount(s)}}const iC=(t,s)=>cc(t)?new nC(s):new aC(s,{allowProjection:t!==p.Fragment});function _r(t,s,a){const r=t.getProps();return dc(r,s,a!==void 0?a:r.custom,t)}const eo=t=>Array.isArray(t);function lC(t,s,a){t.hasValue(s)?t.getValue(s).set(a):t.addValue(s,Mr(a))}function oC(t){return eo(t)?t[t.length-1]||0:t}function cC(t,s){const a=_r(t,s);let{transitionEnd:r={},transition:n={},...i}=a||{};i={...i,...r};for(const l in i){const o=oC(i[l]);lC(t,l,o)}}function dC(t){return!!(js(t)&&t.add)}function to(t,s){const a=t.getValue("willChange");if(dC(a))return a.add(s);if(!a&&Ia.WillChange){const r=new Ia.WillChange("auto");t.addValue("willChange",r),r.add(s)}}function dp(t){return t.props[qh]}const mC=t=>t!==null;function uC(t,{repeat:s,repeatType:a="loop"},r){const n=t.filter(mC),i=s&&a!=="loop"&&s%2===1?0:n.length-1;return n[i]}const xC={type:"spring",stiffness:500,damping:25,restSpeed:10},hC=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),pC={type:"keyframes",duration:.8},gC={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},fC=(t,{keyframes:s})=>s.length>2?pC:Yr.has(t)?t.startsWith("scale")?hC(s[1]):xC:gC;function bC({when:t,delay:s,delayChildren:a,staggerChildren:r,staggerDirection:n,repeat:i,repeatType:l,repeatDelay:o,from:c,elapsed:d,...m}){return!!Object.keys(m).length}const xc=(t,s,a,r={},n,i)=>l=>{const o=ec(r,t)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-ya(c);const m={keyframes:Array.isArray(a)?a:[null,a],ease:"easeOut",velocity:s.getVelocity(),...o,delay:-d,onUpdate:x=>{s.set(x),o.onUpdate&&o.onUpdate(x)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:t,motionValue:s,element:i?void 0:n};bC(o)||Object.assign(m,fC(t,m)),m.duration&&(m.duration=ya(m.duration)),m.repeatDelay&&(m.repeatDelay=ya(m.repeatDelay)),m.from!==void 0&&(m.keyframes[0]=m.from);let h=!1;if((m.type===!1||m.duration===0&&!m.repeatDelay)&&(Xl(m),m.delay===0&&(h=!0)),(Ia.instantAnimations||Ia.skipAnimations)&&(h=!0,Xl(m),m.delay=0),m.allowFlatten=!o.type&&!o.ease,h&&!i&&s.get()!==void 0){const x=uC(m.keyframes,o);if(x!==void 0){Mt.update(()=>{m.onUpdate(x),m.onComplete()});return}}return o.isSync?new Qo(m):new Ow(m)};function yC({protectedKeys:t,needsAnimating:s},a){const r=t.hasOwnProperty(a)&&s[a]!==!0;return s[a]=!1,r}function mp(t,s,{delay:a=0,transitionOverride:r,type:n}={}){let{transition:i=t.getDefaultTransition(),transitionEnd:l,...o}=s;r&&(i=r);const c=[],d=n&&t.animationState&&t.animationState.getState()[n];for(const m in o){const h=t.getValue(m,t.latestValues[m]??null),x=o[m];if(x===void 0||d&&yC(d,m))continue;const u={delay:a,...ec(i||{},m)},g=h.get();if(g!==void 0&&!h.isAnimating&&!Array.isArray(x)&&x===g&&!u.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const y=dp(t);if(y){const v=window.MotionHandoffAnimation(y,m,Mt);v!==null&&(u.startTime=v,b=!0)}}to(t,m),h.start(xc(m,h,x,t.shouldReduceMotion&&Ph.has(m)?{type:!1}:u,t,b));const f=h.animation;f&&c.push(f)}return l&&Promise.all(c).then(()=>{Mt.update(()=>{l&&cC(t,l)})}),c}function up(t,s,a,r=0,n=1){const i=Array.from(t).sort((d,m)=>d.sortNodePosition(m)).indexOf(s),l=t.size,o=(l-1)*r;return typeof a=="function"?a(i,l):n===1?i*r:o-i*r}function so(t,s,a={}){var c;const r=_r(t,s,a.type==="exit"?(c=t.presenceContext)==null?void 0:c.custom:void 0);let{transition:n=t.getDefaultTransition()||{}}=r||{};a.transitionOverride&&(n=a.transitionOverride);const i=r?()=>Promise.all(mp(t,r,a)):()=>Promise.resolve(),l=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:m=0,staggerChildren:h,staggerDirection:x}=n;return vC(t,s,d,m,h,x,a)}:()=>Promise.resolve(),{when:o}=n;if(o){const[d,m]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>m())}else return Promise.all([i(),l(a.delay)])}function vC(t,s,a=0,r=0,n=0,i=1,l){const o=[];for(const c of t.variantChildren)c.notify("AnimationStart",s),o.push(so(c,s,{...l,delay:a+(typeof r=="function"?0:r)+up(t.variantChildren,c,r,n,i)}).then(()=>c.notify("AnimationComplete",s)));return Promise.all(o)}function jC(t,s,a={}){t.notify("AnimationStart",s);let r;if(Array.isArray(s)){const n=s.map(i=>so(t,i,a));r=Promise.all(n)}else if(typeof s=="string")r=so(t,s,a);else{const n=typeof s=="function"?_r(t,s,a.custom):s;r=Promise.all(mp(t,n,a))}return r.then(()=>{t.notify("AnimationComplete",s)})}function xp(t,s){if(!Array.isArray(s))return!1;const a=s.length;if(a!==t.length)return!1;for(let r=0;rPromise.all(s.map(({animation:a,options:r})=>jC(t,a,r)))}function AC(t){let s=SC(t),a=Pm(),r=!0;const n=c=>(d,m)=>{var x;const h=_r(t,m,c==="exit"?(x=t.presenceContext)==null?void 0:x.custom:void 0);if(h){const{transition:u,transitionEnd:g,...b}=h;d={...d,...b,...g}}return d};function i(c){s=c(t)}function l(c){const{props:d}=t,m=hp(t.parent)||{},h=[],x=new Set;let u={},g=1/0;for(let f=0;fg&&C,A=!1;const N=Array.isArray(w)?w:[w];let P=N.reduce(n(y),{});k===!1&&(P={});const{prevResolvedValues:R={}}=v,O={...R,...P},F=T=>{D=!0,x.has(T)&&(A=!0,x.delete(T)),v.needsAnimating[T]=!0;const j=t.getValue(T);j&&(j.liveStyle=!1)};for(const T in O){const j=P[T],U=R[T];if(u.hasOwnProperty(T))continue;let I=!1;eo(j)&&eo(U)?I=!xp(j,U):I=j!==U,I?j!=null?F(T):x.add(T):j!==void 0&&x.has(T)?F(T):v.protectedKeys[T]=!0}v.prevProp=w,v.prevResolvedValues=P,v.isActive&&(u={...u,...P}),r&&t.blockInitialAnimation&&(D=!1);const $=S&&_;D&&(!$||A)&&h.push(...N.map(T=>{const j={type:y};if(typeof T=="string"&&r&&!$&&t.manuallyAnimateOnMount&&t.parent){const{parent:U}=t,I=_r(U,T);if(U.enteringChildren&&I){const{delayChildren:M}=I.transition||{};j.delay=up(U.enteringChildren,t,M)}}return{animation:T,options:j}}))}if(x.size){const f={};if(typeof d.initial!="boolean"){const y=_r(t,Array.isArray(d.initial)?d.initial[0]:d.initial);y&&y.transition&&(f.transition=y.transition)}x.forEach(y=>{const v=t.getBaseTarget(y),w=t.getValue(y);w&&(w.liveStyle=!0),f[y]=v??null}),h.push({animation:f})}let b=!!h.length;return r&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(b=!1),r=!1,b?s(h):Promise.resolve()}function o(c,d){var h;if(a[c].isActive===d)return Promise.resolve();(h=t.variantChildren)==null||h.forEach(x=>{var u;return(u=x.animationState)==null?void 0:u.setActive(c,d)}),a[c].isActive=d;const m=l(c);for(const x in a)a[x].protectedKeys={};return m}return{animateChanges:l,setActive:o,setAnimateFunction:i,getState:()=>a,reset:()=>{a=Pm()}}}function TC(t,s){return typeof s=="string"?s!==t:Array.isArray(s)?!xp(s,t):!1}function nr(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Pm(){return{animate:nr(!0),whileInView:nr(),whileHover:nr(),whileTap:nr(),whileDrag:nr(),whileFocus:nr(),exit:nr()}}class Ka{constructor(s){this.isMounted=!1,this.node=s}update(){}}class kC extends Ka{constructor(s){super(s),s.animationState||(s.animationState=AC(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();_i(s)&&(this.unmountControls=s.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:s}=this.node.getProps(),{animate:a}=this.node.prevProps||{};s!==a&&this.updateAnimationControlsSubscription()}unmount(){var s;this.node.animationState.reset(),(s=this.unmountControls)==null||s.call(this)}}let RC=0;class DC extends Ka{constructor(){super(...arguments),this.id=RC++}update(){if(!this.node.presenceContext)return;const{isPresent:s,onExitComplete:a}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||s===r)return;const n=this.node.animationState.setActive("exit",!s);a&&!s&&n.then(()=>{a(this.id)})}mount(){const{register:s,onExitComplete:a}=this.node.presenceContext||{};a&&a(this.id),s&&(this.unmount=s(this.id))}unmount(){}}const PC={animation:{Feature:kC},exit:{Feature:DC}};function Nn(t,s,a,r={passive:!0}){return t.addEventListener(s,a,r),()=>t.removeEventListener(s,a)}function En(t){return{point:{x:t.pageX,y:t.pageY}}}const IC=t=>s=>ac(s)&&t(s,En(s));function mn(t,s,a,r){return Nn(t,s,IC(a),r)}const pp=1e-4,EC=1-pp,FC=1+pp,gp=.01,_C=0-gp,LC=0+gp;function Ss(t){return t.max-t.min}function MC(t,s,a){return Math.abs(t-s)<=a}function Im(t,s,a,r=.5){t.origin=r,t.originPoint=zt(s.min,s.max,t.origin),t.scale=Ss(a)/Ss(s),t.translate=zt(a.min,a.max,t.origin)-t.originPoint,(t.scale>=EC&&t.scale<=FC||isNaN(t.scale))&&(t.scale=1),(t.translate>=_C&&t.translate<=LC||isNaN(t.translate))&&(t.translate=0)}function un(t,s,a,r){Im(t.x,s.x,a.x,r?r.originX:void 0),Im(t.y,s.y,a.y,r?r.originY:void 0)}function Em(t,s,a){t.min=a.min+s.min,t.max=t.min+Ss(s)}function $C(t,s,a){Em(t.x,s.x,a.x),Em(t.y,s.y,a.y)}function Fm(t,s,a){t.min=s.min-a.min,t.max=t.min+Ss(s)}function xn(t,s,a){Fm(t.x,s.x,a.x),Fm(t.y,s.y,a.y)}function Qs(t){return[t("x"),t("y")]}const fp=({current:t})=>t?t.ownerDocument.defaultView:null,_m=(t,s)=>Math.abs(t-s);function OC(t,s){const a=_m(t.x,s.x),r=_m(t.y,s.y);return Math.sqrt(a**2+r**2)}class bp{constructor(s,a,{transformPagePoint:r,contextWindow:n=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const x=pl(this.lastMoveEventInfo,this.history),u=this.startEvent!==null,g=OC(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!u&&!g)return;const{point:b}=x,{timestamp:f}=xs;this.history.push({...b,timestamp:f});const{onStart:y,onMove:v}=this.handlers;u||(y&&y(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,x)},this.handlePointerMove=(x,u)=>{this.lastMoveEvent=x,this.lastMoveEventInfo=hl(u,this.transformPagePoint),Mt.update(this.updatePoint,!0)},this.handlePointerUp=(x,u)=>{this.end();const{onEnd:g,onSessionEnd:b,resumeAnimation:f}=this.handlers;if(this.dragSnapToOrigin&&f&&f(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=pl(x.type==="pointercancel"?this.lastMoveEventInfo:hl(u,this.transformPagePoint),this.history);this.startEvent&&g&&g(x,y),b&&b(x,y)},!ac(s))return;this.dragSnapToOrigin=i,this.handlers=a,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=n||window;const o=En(s),c=hl(o,this.transformPagePoint),{point:d}=c,{timestamp:m}=xs;this.history=[{...d,timestamp:m}];const{onSessionStart:h}=a;h&&h(s,pl(c,this.history)),this.removeListeners=Dn(mn(this.contextWindow,"pointermove",this.handlePointerMove),mn(this.contextWindow,"pointerup",this.handlePointerUp),mn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),Wa(this.updatePoint)}}function hl(t,s){return s?{point:s(t.point)}:t}function Lm(t,s){return{x:t.x-s.x,y:t.y-s.y}}function pl({point:t},s){return{point:t,delta:Lm(t,yp(s)),offset:Lm(t,UC(s)),velocity:BC(s,.1)}}function UC(t){return t[0]}function yp(t){return t[t.length-1]}function BC(t,s){if(t.length<2)return{x:0,y:0};let a=t.length-1,r=null;const n=yp(t);for(;a>=0&&(r=t[a],!(n.timestamp-r.timestamp>ya(s)));)a--;if(!r)return{x:0,y:0};const i=ea(n.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const l={x:(n.x-r.x)/i,y:(n.y-r.y)/i};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function VC(t,{min:s,max:a},r){return s!==void 0&&ta&&(t=r?zt(a,t,r.max):Math.min(t,a)),t}function Mm(t,s,a){return{min:s!==void 0?t.min+s:void 0,max:a!==void 0?t.max+a-(t.max-t.min):void 0}}function zC(t,{top:s,left:a,bottom:r,right:n}){return{x:Mm(t.x,a,n),y:Mm(t.y,s,r)}}function $m(t,s){let a=s.min-t.min,r=s.max-t.max;return s.max-s.minr?a=fn(s.min,s.max-r,t.min):r>n&&(a=fn(t.min,t.max-n,s.min)),Pa(0,1,a)}function GC(t,s){const a={};return s.min!==void 0&&(a.min=s.min-t.min),s.max!==void 0&&(a.max=s.max-t.min),a}const ao=.35;function YC(t=ao){return t===!1?t=0:t===!0&&(t=ao),{x:Om(t,"left","right"),y:Om(t,"top","bottom")}}function Om(t,s,a){return{min:Um(t,s),max:Um(t,a)}}function Um(t,s){return typeof t=="number"?t:t[s]||0}const KC=new WeakMap;class XC{constructor(s){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Yt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:a=!1,distanceThreshold:r}={}){const{presenceContext:n}=this.visualElement;if(n&&n.isPresent===!1)return;const i=h=>{const{dragSnapToOrigin:x}=this.getProps();x?this.pauseAnimation():this.stopAnimation(),a&&this.snapToCursor(En(h).point)},l=(h,x)=>{const{drag:u,dragPropagation:g,onDragStart:b}=this.getProps();if(u&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=t1(u),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=x,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Qs(y=>{let v=this.getAxisMotionValue(y).get()||0;if(va.test(v)){const{projection:w}=this.visualElement;if(w&&w.layout){const C=w.layout.layoutBox[y];C&&(v=Ss(C)*(parseFloat(v)/100))}}this.originPoint[y]=v}),b&&Mt.postRender(()=>b(h,x)),to(this.visualElement,"transform");const{animationState:f}=this.visualElement;f&&f.setActive("whileDrag",!0)},o=(h,x)=>{this.latestPointerEvent=h,this.latestPanInfo=x;const{dragPropagation:u,dragDirectionLock:g,onDirectionLock:b,onDrag:f}=this.getProps();if(!u&&!this.openDragLock)return;const{offset:y}=x;if(g&&this.currentDirection===null){this.currentDirection=ZC(y),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",x.point,y),this.updateAxis("y",x.point,y),this.visualElement.render(),f&&f(h,x)},c=(h,x)=>{this.latestPointerEvent=h,this.latestPanInfo=x,this.stop(h,x),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>Qs(h=>{var x;return this.getAnimationState(h)==="paused"&&((x=this.getAxisMotionValue(h).animation)==null?void 0:x.play())}),{dragSnapToOrigin:m}=this.getProps();this.panSession=new bp(s,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:m,distanceThreshold:r,contextWindow:fp(this.visualElement)})}stop(s,a){const r=s||this.latestPointerEvent,n=a||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!n||!r)return;const{velocity:l}=n;this.startAnimation(l);const{onDragEnd:o}=this.getProps();o&&Mt.postRender(()=>o(r,n))}cancel(){this.isDragging=!1;const{projection:s,animationState:a}=this.visualElement;s&&(s.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),a&&a.setActive("whileDrag",!1)}updateAxis(s,a,r){const{drag:n}=this.getProps();if(!r||!Bn(s,n,this.currentDirection))return;const i=this.getAxisMotionValue(s);let l=this.originPoint[s]+r[s];this.constraints&&this.constraints[s]&&(l=VC(l,this.constraints[s],this.elastic[s])),i.set(l)}resolveConstraints(){var i;const{dragConstraints:s,dragElastic:a}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(i=this.visualElement.projection)==null?void 0:i.layout,n=this.constraints;s&&Tr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&r?this.constraints=zC(r.layoutBox,s):this.constraints=!1,this.elastic=YC(a),n!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&Qs(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=GC(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:a}=this.getProps();if(!s||!Tr(s))return!1;const r=s.current,{projection:n}=this.visualElement;if(!n||!n.layout)return!1;const i=J1(r,n.root,this.visualElement.getTransformPagePoint());let l=HC(n.layout.layoutBox,i);if(a){const o=a(K1(l));this.hasMutatedConstraints=!!o,o&&(l=sp(o))}return l}startAnimation(s){const{drag:a,dragMomentum:r,dragElastic:n,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=Qs(m=>{if(!Bn(m,a,this.currentDirection))return;let h=c&&c[m]||{};l&&(h={min:0,max:0});const x=n?200:1e6,u=n?40:1e7,g={type:"inertia",velocity:r?s[m]:0,bounceStiffness:x,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(m,g)});return Promise.all(d).then(o)}startAxisValueAnimation(s,a){const r=this.getAxisMotionValue(s);return to(this.visualElement,s),r.start(xc(s,r,0,a,this.visualElement,!1))}stopAnimation(){Qs(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Qs(s=>{var a;return(a=this.getAxisMotionValue(s).animation)==null?void 0:a.pause()})}getAnimationState(s){var a;return(a=this.getAxisMotionValue(s).animation)==null?void 0:a.state}getAxisMotionValue(s){const a=`_drag${s.toUpperCase()}`,r=this.visualElement.getProps(),n=r[a];return n||this.visualElement.getValue(s,(r.initial?r.initial[s]:void 0)||0)}snapToCursor(s){Qs(a=>{const{drag:r}=this.getProps();if(!Bn(a,r,this.currentDirection))return;const{projection:n}=this.visualElement,i=this.getAxisMotionValue(a);if(n&&n.layout){const{min:l,max:o}=n.layout.layoutBox[a];i.set(s[a]-zt(l,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:a}=this.getProps(),{projection:r}=this.visualElement;if(!Tr(a)||!r||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};Qs(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();n[l]=WC({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),Qs(l=>{if(!Bn(l,s,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(zt(c,d,n[l]))})}addListeners(){if(!this.visualElement.current)return;KC.set(this.visualElement,this);const s=this.visualElement.current,a=mn(s,"pointerdown",c=>{const{drag:d,dragListener:m=!0}=this.getProps();d&&m&&this.start(c)}),r=()=>{const{dragConstraints:c}=this.getProps();Tr(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,i=n.addEventListener("measure",r);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),Mt.read(r);const l=Nn(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(Qs(m=>{const h=this.getAxisMotionValue(m);h&&(this.originPoint[m]+=c[m].translate,h.set(h.get()+c[m].translate))}),this.visualElement.render())});return()=>{l(),a(),i(),o&&o()}}getProps(){const s=this.visualElement.getProps(),{drag:a=!1,dragDirectionLock:r=!1,dragPropagation:n=!1,dragConstraints:i=!1,dragElastic:l=ao,dragMomentum:o=!0}=s;return{...s,drag:a,dragDirectionLock:r,dragPropagation:n,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Bn(t,s,a){return(s===!0||s===t)&&(a===null||a===t)}function ZC(t,s=10){let a=null;return Math.abs(t.y)>s?a="y":Math.abs(t.x)>s&&(a="x"),a}class JC extends Ka{constructor(s){super(s),this.removeGroupControls=aa,this.removeListeners=aa,this.controls=new XC(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||aa}unmount(){this.removeGroupControls(),this.removeListeners()}}const Bm=t=>(s,a)=>{t&&Mt.postRender(()=>t(s,a))};class QC extends Ka{constructor(){super(...arguments),this.removePointerDownListener=aa}onPointerDown(s){this.session=new bp(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:fp(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:a,onPan:r,onPanEnd:n}=this.node.getProps();return{onSessionStart:Bm(s),onStart:Bm(a),onMove:r,onEnd:(i,l)=>{delete this.session,n&&Mt.postRender(()=>n(i,l))}}}mount(){this.removePointerDownListener=mn(this.node.current,"pointerdown",s=>this.onPointerDown(s))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const Qn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Vm(t,s){return s.max===s.min?0:t/(s.max-s.min)*100}const en={correct:(t,s)=>{if(!s.target)return t;if(typeof t=="string")if(Je.test(t))t=parseFloat(t);else return t;const a=Vm(t,s.target.x),r=Vm(t,s.target.y);return`${a}% ${r}%`}},qC={correct:(t,{treeScale:s,projectionDelta:a})=>{const r=t,n=Ga.parse(t);if(n.length>5)return r;const i=Ga.createTransformer(t),l=typeof n[0]!="number"?1:0,o=a.x.scale*s.x,c=a.y.scale*s.y;n[0+l]/=o,n[1+l]/=c;const d=zt(o,c,.5);return typeof n[2+l]=="number"&&(n[2+l]/=d),typeof n[3+l]=="number"&&(n[3+l]/=d),i(n)}};let gl=!1;class e2 extends p.Component{componentDidMount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r,layoutId:n}=this.props,{projection:i}=s;N1(t2),i&&(a.group&&a.group.add(i),r&&r.register&&n&&r.register(i),gl&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Qn.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:a,visualElement:r,drag:n,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,gl=!0,n||s.layoutDependency!==a||a===void 0||s.isPresent!==i?l.willUpdate():this.safeToRemove(),s.isPresent!==i&&(i?l.promote():l.relegate()||Mt.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),sc.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:a,switchLayoutGroup:r}=this.props,{projection:n}=s;gl=!0,n&&(n.scheduleCheckAfterUnmount(),a&&a.group&&a.group.remove(n),r&&r.deregister&&r.deregister(n))}safeToRemove(){const{safeToRemove:s}=this.props;s&&s()}render(){return null}}function vp(t){const[s,a]=Vh(),r=p.useContext(Fo);return e.jsx(e2,{...t,layoutGroup:r,switchLayoutGroup:p.useContext(ep),isPresent:s,safeToRemove:a})}const t2={borderRadius:{...en,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:en,borderTopRightRadius:en,borderBottomLeftRadius:en,borderBottomRightRadius:en,boxShadow:qC};function s2(t,s,a){const r=js(t)?t:Mr(t);return r.start(xc("",r,s,a)),r.animation}const a2=(t,s)=>t.depth-s.depth;class r2{constructor(){this.children=[],this.isDirty=!1}add(s){Mo(this.children,s),this.isDirty=!0}remove(s){$o(this.children,s),this.isDirty=!0}forEach(s){this.isDirty&&this.children.sort(a2),this.isDirty=!1,this.children.forEach(s)}}function n2(t,s){const a=$s.now(),r=({timestamp:n})=>{const i=n-a;i>=s&&(Wa(r),t(i-s))};return Mt.setup(r,!0),()=>Wa(r)}const jp=["TopLeft","TopRight","BottomLeft","BottomRight"],i2=jp.length,zm=t=>typeof t=="string"?parseFloat(t):t,Hm=t=>typeof t=="number"||Je.test(t);function l2(t,s,a,r,n,i){n?(t.opacity=zt(0,a.opacity??1,o2(r)),t.opacityExit=zt(s.opacity??1,0,c2(r))):i&&(t.opacity=zt(s.opacity??1,a.opacity??1,r));for(let l=0;lrs?1:a(fn(t,s,r))}function Gm(t,s){t.min=s.min,t.max=s.max}function Js(t,s){Gm(t.x,s.x),Gm(t.y,s.y)}function Ym(t,s){t.translate=s.translate,t.scale=s.scale,t.originPoint=s.originPoint,t.origin=s.origin}function Km(t,s,a,r,n){return t-=s,t=xi(t,1/a,r),n!==void 0&&(t=xi(t,1/n,r)),t}function d2(t,s=0,a=1,r=.5,n,i=t,l=t){if(va.test(s)&&(s=parseFloat(s),s=zt(l.min,l.max,s/100)-l.min),typeof s!="number")return;let o=zt(i.min,i.max,r);t===i&&(o-=s),t.min=Km(t.min,s,a,o,n),t.max=Km(t.max,s,a,o,n)}function Xm(t,s,[a,r,n],i,l){d2(t,s[a],s[r],s[n],s.scale,i,l)}const m2=["x","scaleX","originX"],u2=["y","scaleY","originY"];function Zm(t,s,a,r){Xm(t.x,s,m2,a?a.x:void 0,r?r.x:void 0),Xm(t.y,s,u2,a?a.y:void 0,r?r.y:void 0)}function Jm(t){return t.translate===0&&t.scale===1}function wp(t){return Jm(t.x)&&Jm(t.y)}function Qm(t,s){return t.min===s.min&&t.max===s.max}function x2(t,s){return Qm(t.x,s.x)&&Qm(t.y,s.y)}function qm(t,s){return Math.round(t.min)===Math.round(s.min)&&Math.round(t.max)===Math.round(s.max)}function Cp(t,s){return qm(t.x,s.x)&&qm(t.y,s.y)}function eu(t){return Ss(t.x)/Ss(t.y)}function tu(t,s){return t.translate===s.translate&&t.scale===s.scale&&t.originPoint===s.originPoint}class h2{constructor(){this.members=[]}add(s){Mo(this.members,s),s.scheduleRender()}remove(s){if($o(this.members,s),s===this.prevLead&&(this.prevLead=void 0),s===this.lead){const a=this.members[this.members.length-1];a&&this.promote(a)}}relegate(s){const a=this.members.findIndex(n=>s===n);if(a===0)return!1;let r;for(let n=a;n>=0;n--){const i=this.members[n];if(i.isPresent!==!1){r=i;break}}return r?(this.promote(r),!0):!1}promote(s,a){const r=this.lead;if(s!==r&&(this.prevLead=r,this.lead=s,s.show(),r)){r.instance&&r.scheduleRender(),s.scheduleRender(),s.resumeFrom=r,a&&(s.resumeFrom.preserveOpacity=!0),r.snapshot&&(s.snapshot=r.snapshot,s.snapshot.latestValues=r.animationValues||r.latestValues),s.root&&s.root.isUpdating&&(s.isLayoutDirty=!0);const{crossfade:n}=s.options;n===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(s=>{const{options:a,resumingFrom:r}=s;a.onExitComplete&&a.onExitComplete(),r&&r.options.onExitComplete&&r.options.onExitComplete()})}scheduleRender(){this.members.forEach(s=>{s.instance&&s.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function p2(t,s,a){let r="";const n=t.x.translate/s.x,i=t.y.translate/s.y,l=(a==null?void 0:a.z)||0;if((n||i||l)&&(r=`translate3d(${n}px, ${i}px, ${l}px) `),(s.x!==1||s.y!==1)&&(r+=`scale(${1/s.x}, ${1/s.y}) `),a){const{transformPerspective:d,rotate:m,rotateX:h,rotateY:x,skewX:u,skewY:g}=a;d&&(r=`perspective(${d}px) ${r}`),m&&(r+=`rotate(${m}deg) `),h&&(r+=`rotateX(${h}deg) `),x&&(r+=`rotateY(${x}deg) `),u&&(r+=`skewX(${u}deg) `),g&&(r+=`skewY(${g}deg) `)}const o=t.x.scale*s.x,c=t.y.scale*s.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const fl=["","X","Y","Z"],g2=1e3;let f2=0;function bl(t,s,a,r){const{latestValues:n}=s;n[t]&&(a[t]=n[t],s.setStaticValue(t,0),r&&(r[t]=0))}function Sp(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:s}=t.options;if(!s)return;const a=dp(s);if(window.MotionHasOptimisedAnimation(a,"transform")){const{layout:n,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(a,"transform",Mt,!(n||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&Sp(r)}function Ap({attachResizeListener:t,defaultParent:s,measureScroll:a,checkIsScrollRoot:r,resetTransform:n}){return class{constructor(l={},o=s==null?void 0:s()){this.id=f2++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(v2),this.nodes.forEach(C2),this.nodes.forEach(S2),this.nodes.forEach(j2)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=l,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let c=0;cthis.root.updateBlockedByResize=!1;Mt.read(()=>{h=window.innerWidth}),t(l,()=>{const u=window.innerWidth;u!==h&&(h=u,this.root.updateBlockedByResize=!0,m&&m(),m=n2(x,250),Qn.hasAnimatedSinceResize&&(Qn.hasAnimatedSinceResize=!1,this.nodes.forEach(ru)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:m,hasLayoutChanged:h,hasRelativeLayoutChanged:x,layout:u})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||D2,{onLayoutAnimationStart:b,onLayoutAnimationComplete:f}=d.getProps(),y=!this.targetLayout||!Cp(this.targetLayout,u),v=!h&&x;if(this.options.layoutRoot||this.resumeFrom||v||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...ec(g,"layout"),onPlay:b,onComplete:f};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(m,v)}else h||ru(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=u})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Wa(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(A2),this.animationId++)}getTransformTemplate(){const{visualElement:l}=this.options;return l&&l.getProps().transformTemplate}willUpdate(l=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Sp(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let m=0;m{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ss(this.snapshot.measuredBox.x)&&!Ss(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c{const k=C/1e3;nu(h.x,l.x,k),nu(h.y,l.y,k),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(xn(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox),k2(this.relativeTarget,this.relativeTargetOrigin,x,k),w&&x2(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=Yt()),Js(w,this.relativeTarget)),b&&(this.animationValues=m,l2(m,d,this.latestValues,k,v,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=k},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(Wa(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Mt.update(()=>{Qn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Mr(0)),this.currentAnimation=s2(this.motionValue,[0,1e3],{...l,velocity:0,isSync:!0,onUpdate:m=>{this.mixTargetDelta(m),l.onUpdate&&l.onUpdate(m)},onStop:()=>{},onComplete:()=>{l.onComplete&&l.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const l=this.getStack();l&&l.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(g2),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:m}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&Tp(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Yt();const h=Ss(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const x=Ss(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+x}Js(o,c),Rr(o,m),un(this.projectionDeltaWithTransform,this.layoutCorrected,o,m)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new h2),this.sharedNodes.get(l).add(o);const d=o.options.initialPromotionConfig;o.promote({transition:d?d.transition:void 0,preserveFollowOpacity:d&&d.shouldPreserveFollowOpacity?d.shouldPreserveFollowOpacity(o):void 0})}isLead(){const l=this.getStack();return l?l.lead===this:!0}getLead(){var o;const{layoutId:l}=this.options;return l?((o=this.getStack())==null?void 0:o.lead)||this:this}getPrevLead(){var o;const{layoutId:l}=this.options;return l?(o=this.getStack())==null?void 0:o.prevLead:void 0}getStack(){const{layoutId:l}=this.options;if(l)return this.root.sharedNodes.get(l)}promote({needsReset:l,transition:o,preserveFollowOpacity:c}={}){const d=this.getStack();d&&d.promote(this,c),l&&(this.projectionDelta=void 0,this.needsReset=!0),o&&this.setOptions({transition:o})}relegate(){const l=this.getStack();return l?l.relegate(this):!1}resetSkewAndRotation(){const{visualElement:l}=this.options;if(!l)return;let o=!1;const{latestValues:c}=l;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(o=!0),!o)return;const d={};c.z&&bl("z",l,d,this.animationValues);for(let m=0;m{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(su),this.root.sharedNodes.clear()}}}function b2(t){t.updateLayout()}function y2(t){var a;const s=((a=t.resumeFrom)==null?void 0:a.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&s&&t.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:n}=t.layout,{animationType:i}=t.options,l=s.source!==t.layout.source;i==="size"?Qs(h=>{const x=l?s.measuredBox[h]:s.layoutBox[h],u=Ss(x);x.min=r[h].min,x.max=x.min+u}):Tp(i,s.layoutBox,r)&&Qs(h=>{const x=l?s.measuredBox[h]:s.layoutBox[h],u=Ss(r[h]);x.max=x.min+u,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[h].max=t.relativeTarget[h].min+u)});const o=Dr();un(o,r,s.layoutBox);const c=Dr();l?un(c,t.applyTransform(n,!0),s.measuredBox):un(c,r,s.layoutBox);const d=!wp(o);let m=!1;if(!t.resumeFrom){const h=t.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:x,layout:u}=h;if(x&&u){const g=Yt();xn(g,s.layoutBox,x.layoutBox);const b=Yt();xn(b,r,u.layoutBox),Cp(g,b)||(m=!0),h.options.layoutRoot&&(t.relativeTarget=b,t.relativeTargetOrigin=g,t.relativeParent=h)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:s,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:m})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function v2(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=!!(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function j2(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function N2(t){t.clearSnapshot()}function su(t){t.clearMeasurements()}function au(t){t.isLayoutDirty=!1}function w2(t){const{visualElement:s}=t.options;s&&s.getProps().onBeforeLayoutMeasure&&s.notify("BeforeLayoutMeasure"),t.resetTransform()}function ru(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function C2(t){t.resolveTargetDelta()}function S2(t){t.calcProjection()}function A2(t){t.resetSkewAndRotation()}function T2(t){t.removeLeadSnapshot()}function nu(t,s,a){t.translate=zt(s.translate,0,a),t.scale=zt(s.scale,1,a),t.origin=s.origin,t.originPoint=s.originPoint}function iu(t,s,a,r){t.min=zt(s.min,a.min,r),t.max=zt(s.max,a.max,r)}function k2(t,s,a,r){iu(t.x,s.x,a.x,r),iu(t.y,s.y,a.y,r)}function R2(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const D2={duration:.45,ease:[.4,0,.1,1]},lu=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),ou=lu("applewebkit/")&&!lu("chrome/")?Math.round:aa;function cu(t){t.min=ou(t.min),t.max=ou(t.max)}function P2(t){cu(t.x),cu(t.y)}function Tp(t,s,a){return t==="position"||t==="preserve-aspect"&&!MC(eu(s),eu(a),.2)}function I2(t){var s;return t!==t.root&&((s=t.scroll)==null?void 0:s.wasRoot)}const E2=Ap({attachResizeListener:(t,s)=>Nn(t,"resize",s),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),yl={current:void 0},kp=Ap({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!yl.current){const t=new E2({});t.mount(window),t.setOptions({layoutScroll:!0}),yl.current=t}return yl.current},resetTransform:(t,s)=>{t.style.transform=s!==void 0?s:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),F2={pan:{Feature:QC},drag:{Feature:JC,ProjectionNode:kp,MeasureLayout:vp}};function du(t,s,a){const{props:r}=t;t.animationState&&r.whileHover&&t.animationState.setActive("whileHover",a==="Start");const n="onHover"+a,i=r[n];i&&Mt.postRender(()=>i(s,En(s)))}class _2 extends Ka{mount(){const{current:s}=this.node;s&&(this.unmount=s1(s,(a,r)=>(du(this.node,r,"Start"),n=>du(this.node,n,"End"))))}unmount(){}}class L2 extends Ka{constructor(){super(...arguments),this.isActive=!1}onFocus(){let s=!1;try{s=this.node.current.matches(":focus-visible")}catch{s=!0}!s||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Dn(Nn(this.node.current,"focus",()=>this.onFocus()),Nn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function mu(t,s,a){const{props:r}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&r.whileTap&&t.animationState.setActive("whileTap",a==="Start");const n="onTap"+(a==="End"?"":a),i=r[n];i&&Mt.postRender(()=>i(s,En(s)))}class M2 extends Ka{mount(){const{current:s}=this.node;s&&(this.unmount=i1(s,(a,r)=>(mu(this.node,r,"Start"),(n,{success:i})=>mu(this.node,n,i?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const ro=new WeakMap,vl=new WeakMap,$2=t=>{const s=ro.get(t.target);s&&s(t)},O2=t=>{t.forEach($2)};function U2({root:t,...s}){const a=t||document;vl.has(a)||vl.set(a,{});const r=vl.get(a),n=JSON.stringify(s);return r[n]||(r[n]=new IntersectionObserver(O2,{root:t,...s})),r[n]}function B2(t,s,a){const r=U2(s);return ro.set(t,a),r.observe(t),()=>{ro.delete(t),r.unobserve(t)}}const V2={some:0,all:1};class z2 extends Ka{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:a,margin:r,amount:n="some",once:i}=s,l={root:a?a.current:void 0,rootMargin:r,threshold:typeof n=="number"?n:V2[n]},o=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,i&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:m,onViewportLeave:h}=this.node.getProps(),x=d?m:h;x&&x(c)};return B2(this.node.current,l,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:s,prevProps:a}=this.node;["amount","margin","root"].some(H2(s,a))&&this.startObserver()}unmount(){}}function H2({viewport:t={}},{viewport:s={}}={}){return a=>t[a]!==s[a]}const W2={inView:{Feature:z2},tap:{Feature:M2},focus:{Feature:L2},hover:{Feature:_2}},G2={layout:{ProjectionNode:kp,MeasureLayout:vp}},Y2={...PC,...W2,...F2,...G2},ts=Y1(Y2,iC),tn=[{id:"claim-management",name:"Claim Management",description:"End-to-end dealer claim processing workflow with automatic IO generation and budget blocking",category:"Dealer Operations",icon:Gt,color:"from-blue-500 to-indigo-600",estimatedTime:"5-7 days",steps:7,features:["Automatic IO confirmation","Budget blocking","Document verification","E-invoice generation","Credit note issuance"],disabled:!1},{id:"vendor-payment",name:"Vendor Payment",description:"Streamlined vendor payment approval with PO validation and financial controls",category:"Finance",icon:ex,color:"from-green-500 to-emerald-600",estimatedTime:"3-5 days",steps:5,features:["PO matching","Invoice verification","Multi-level approvals","Payment scheduling"],disabled:!0,comingSoon:!0}];function K2({open:t,onClose:s,onSelectTemplate:a}){var d,m,h;const[r,n]=p.useState(null),[i,l]=p.useState(!1);p.useEffect(()=>{const x=tt.getUserData();l((x==null?void 0:x.jobTitle)==="Dealer")},[]);const o=x=>{if(i)return;const u=tn.find(g=>g.id===x);u!=null&&u.disabled||n(x)},c=()=>{r&&(a(r),s())};return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"!fixed !inset-0 !top-0 !left-0 !right-0 !bottom-0 !w-screen !h-screen !max-w-none !translate-x-0 !translate-y-0 p-0 gap-0 border-0 !rounded-none bg-gradient-to-br from-gray-50 to-white [&>button]:hidden !m-0",children:[e.jsx(mt,{className:"sr-only",children:"Select a Template"}),e.jsx(Dt,{className:"sr-only",children:"Choose from pre-configured templates with predefined workflows and approval chains for faster processing."}),e.jsx("button",{onClick:s,className:"!flex absolute top-6 left-6 z-50 w-10 h-10 rounded-full bg-white shadow-lg hover:shadow-xl border border-gray-200 items-center justify-center transition-all hover:scale-110","aria-label":"Go back",children:e.jsx(Ns,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsxs("div",{className:"min-h-full flex flex-col items-center justify-center px-6 py-12",children:[e.jsxs(ts.div,{initial:{opacity:0,y:-20},animate:{opacity:1,y:0},className:"text-center mb-12 max-w-3xl",children:[e.jsx("div",{className:"w-20 h-20 bg-gradient-to-br from-blue-500 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-6",children:e.jsx(qu,{className:"w-10 h-10 text-white"})}),e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4",children:"Choose Your Template"}),e.jsx("p",{className:"text-lg text-gray-600",children:"Select from pre-configured templates with predefined workflows and approval chains for faster processing."})]}),e.jsx("div",{className:"w-full max-w-5xl grid grid-cols-1 md:grid-cols-2 gap-6 mb-8",children:tn.map((x,u)=>{const g=x.icon,b=r===x.id,f=i||x.disabled;return e.jsx(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:u*.1},whileHover:f?{}:{scale:1.03},whileTap:f?{}:{scale:.98},children:e.jsxs(ee,{className:`h-full transition-all duration-300 border-2 ${f?"opacity-50 cursor-not-allowed border-gray-200":b?"cursor-pointer border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200":"cursor-pointer border-gray-200 hover:border-blue-300 hover:shadow-lg"}`,onClick:()=>o(x.id),children:[e.jsxs(ge,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl bg-gradient-to-br ${x.color} flex items-center justify-center shadow-md`,children:e.jsx(g,{className:"w-7 h-7 text-white"})}),b&&e.jsx(ts.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center shadow-md",children:e.jsx(yr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsx(fe,{className:"text-xl mb-2",children:x.name}),e.jsx($e,{className:"text-sm leading-relaxed",children:x.description}),i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-amber-50 border border-amber-200 rounded-lg",children:[e.jsx(ze,{className:"w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-amber-800",children:"Not accessible for Dealers"})]}),x.comingSoon&&!i&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 p-2 bg-blue-50 border border-blue-200 rounded-lg",children:[e.jsx(ze,{className:"w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-blue-800 font-semibold",children:"Coming Soon"})]})]})]}),e.jsxs(se,{className:"pt-0 space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(ne,{variant:"secondary",className:"text-xs",children:x.category})}),e.jsx(Ts,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(st,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:x.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ot,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[x.steps," steps"]})]})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx("p",{className:"text-xs text-gray-500 font-semibold",children:"Key Features:"}),e.jsxs("div",{className:"space-y-1.5",children:[x.features.slice(0,3).map((y,v)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-600",children:[e.jsx(De,{className:"w-3 h-3 text-green-600 flex-shrink-0"}),e.jsx("span",{children:y})]},v)),x.features.length>3&&e.jsxs("p",{className:"text-xs text-blue-600 italic pl-5",children:["+",x.features.length-3," more features"]})]})]})]})]})},x.id)})}),e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"flex flex-col sm:flex-row justify-center gap-4 mt-4",children:[e.jsx(E,{variant:"outline",onClick:s,size:"lg",className:"px-8",children:"Cancel"}),e.jsxs(E,{onClick:c,disabled:!r||i||((d=tn.find(x=>x.id===r))==null?void 0:d.disabled),size:"lg",className:`gap-2 px-8 ${r&&!i&&!((m=tn.find(x=>x.id===r))!=null&&m.disabled)?"bg-blue-600 hover:bg-blue-700":"bg-gray-400 cursor-not-allowed"}`,children:["Continue with Template",e.jsx(ss,{className:"w-4 h-4"})]})]}),e.jsx(Ei,{children:r&&e.jsx(ts.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},className:"mt-6 text-center",children:e.jsxs("p",{className:"text-sm text-gray-600",children:["Selected: ",e.jsx("span",{className:"font-semibold text-blue-600",children:(h=tn.find(x=>x.id===r))==null?void 0:h.name})]})})})]})})]})})}function jr({fileName:t,fileType:s,fileUrl:a,fileSize:r,attachmentId:n,onDownload:i,open:l,onClose:o}){const[c,d]=p.useState(100),[m,h]=p.useState(0),[x,u]=p.useState(null),[g,b]=p.useState(!1),[f,y]=p.useState(null),v=s.toLowerCase().includes("image")||s.toLowerCase().includes("png")||s.toLowerCase().includes("jpg")||s.toLowerCase().includes("jpeg")||s.toLowerCase().includes("gif")||s.toLowerCase().includes("webp"),w=s.toLowerCase().includes("pdf"),C=v||w;p.useEffect(()=>{if(!l||!C||!a){u(null);return}return(async()=>{b(!0),y(null);try{let R=a;a.startsWith("/")&&!a.startsWith("//")&&(R=`${window.location.origin}${a}`);const F=await fetch(R,{headers:{Accept:w?"application/pdf":"*/*"},credentials:"include",mode:"cors"});if(!F.ok){const T=await F.text().catch(()=>"");throw new Error(`Failed to load file: ${F.status} ${F.statusText}. ${T}`)}const $=await F.blob();if($.size===0)throw new Error("File is empty or could not be loaded");w&&!$.type.includes("pdf")&&$.type!=="application/octet-stream"&&console.warn(`Expected PDF but got ${$.type}`);const V=window.URL.createObjectURL($);u(V)}catch(N){console.error("Failed to load file for preview:",N),y(N instanceof Error?N.message:"Failed to load file for preview")}finally{b(!1)}})(),()=>{x&&(window.URL.revokeObjectURL(x),u(null))}},[l,a,C,w]);const k=async()=>{if(i&&n)try{await i(n)}catch{alert("Failed to download file")}},S=()=>d(A=>Math.min(A+25,200)),_=()=>d(A=>Math.max(A-25,50)),D=()=>h(A=>(A+90)%360);return e.jsx(pt,{open:l,onOpenChange:o,children:e.jsx(dt,{className:"file-preview-dialog p-3 sm:p-6",children:e.jsxs("div",{className:"file-preview-content",children:[e.jsx(gt,{className:"pb-4 flex-shrink-0 pr-8",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(ht,{className:"w-5 h-5 text-blue-600 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(mt,{className:"text-base sm:text-lg font-bold text-gray-900 truncate pr-2",children:t}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-500",children:[s," ",r&&`โ€ข ${(r/1024).toFixed(1)} KB`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mr-2",children:[v&&e.jsxs("div",{className:"flex items-center gap-1 mr-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:_,disabled:c<=50,title:"Zoom out",className:"h-8 w-8 p-0",children:e.jsx(r0,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs sm:text-sm text-gray-600 min-w-[3rem] text-center",children:[c,"%"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:S,disabled:c>=200,title:"Zoom in",className:"h-8 w-8 p-0",children:e.jsx(n0,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:D,title:"Rotate",className:"h-8 w-8 p-0",children:e.jsx(tx,{className:"h-4 w-4"})})]}),i&&n&&e.jsxs(E,{variant:"outline",size:"sm",onClick:k,className:"gap-2 h-9",children:[e.jsx(Ct,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Download"})]})]})]})}),e.jsx("div",{className:"file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4",children:g?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[e.jsx(lt,{className:"w-12 h-12 text-blue-600 animate-spin mb-4"}),e.jsx("p",{className:"text-sm text-gray-600",children:"Loading preview..."})]}):f?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(ft,{className:"w-10 h-10 text-red-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Failed"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:f}),i&&n&&e.jsxs(E,{onClick:k,className:"gap-2",children:[e.jsx(Ct,{className:"h-4 w-4"}),"Download ",t]})]}):C&&x?e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("img",{src:x,alt:t,style:{transform:`scale(${c/100}) rotate(${m}deg)`,transition:"transform 0.2s ease-in-out",maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},className:"rounded-lg shadow-lg"})}),w&&e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx("iframe",{src:x,className:"w-full h-full rounded-lg border-0",title:t,style:{minHeight:"70vh",height:"100%"},onError:()=>{y("Failed to load PDF preview")}})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4",children:e.jsx(ht,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Preview Not Available"}),e.jsx("p",{className:"text-sm text-gray-600 mb-6",children:"This file type cannot be previewed. Please download to view."}),i&&n&&e.jsxs(E,{onClick:k,className:"gap-2",children:[e.jsx(Ct,{className:"h-4 w-4"}),"Download ",t]})]})})]})})})}function Fn({open:t,onClose:s,violations:a,policyDetails:r}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2",children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Policy Violation"]}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following policy violations were detected:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:a.map((n,i)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3",children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:n.type}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:n.message}),n.currentValue!==void 0&&n.maxValue!==void 0&&e.jsxs("p",{className:"text-xs text-red-600 mt-1 font-semibold",children:["Current: ",n.currentValue," / Maximum: ",n.maxValue]})]},i))}),r&&e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"System Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[r.maxApprovalLevels!==void 0&&e.jsxs("li",{children:["Maximum approval levels: ",r.maxApprovalLevels]}),r.maxParticipants!==void 0&&e.jsxs("li",{children:["Maximum participants per request: ",r.maxParticipants]}),r.allowSpectators!==void 0&&e.jsxs("li",{children:["Allow adding spectators: ",r.allowSpectators?"Yes":"No"]}),r.maxSpectators!==void 0&&e.jsxs("li",{children:["Maximum spectators per request: ",r.maxSpectators]})]})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto",children:"OK"})})]})})}const Ys=async t=>{const s=t?{category:t}:{};return(await je.get("/users/configurations",{params:s})).data.data},X2=async t=>{const s={};return(await je.get("/admin/configurations",{params:s})).data.data},Z2=async(t,s)=>{await je.put(`/admin/configurations/${t}`,{configValue:s})},J2=async t=>{await je.post(`/admin/configurations/${t}/reset`)},Q2=async t=>{const s=t?{year:t}:{};return(await je.get("/admin/holidays",{params:s})).data.data},q2=async t=>(await je.post("/admin/holidays",t)).data.data,eS=async(t,s)=>(await je.put(`/admin/holidays/${t}`,s)).data.data,tS=async t=>{await je.delete(`/admin/holidays/${t}`)},sS=async()=>(await je.get("/config/activity-types")).data.data,aS=async t=>{const s={activeOnly:t.toString()};return(await je.get("/admin/activity-types",{params:s})).data.data},rS=async t=>(await je.post("/admin/activity-types",t)).data.data,nS=async(t,s)=>(await je.put(`/admin/activity-types/${t}`,s)).data.data,iS=async t=>{await je.delete(`/admin/activity-types/${t}`)},lS={template:"",title:"",description:"",category:"",priority:"",urgency:"",businessImpact:"",amount:"",currency:"USD",vendor:"",timeline:"",slaTemplate:"",slaHours:0,customSlaHours:0,slaEndDate:void 0,expectedCompletionDate:void 0,breachEscalation:!0,reminderSchedule:"50",workflowType:"sequential",requiresAllApprovals:!0,escalationEnabled:!0,reminderEnabled:!0,minimumLevel:1,maxLevel:1,approvers:[],approverCount:1,spectators:[],ccList:[],invitedUsers:[],allowComments:!0,allowDocumentUpload:!0,documents:[],tags:[],relatedRequests:[],costCenter:"",project:""};function oS(t,s,a){const[r,n]=p.useState(lS),[i,l]=p.useState(null),[o,c]=p.useState(t),[d,m]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20}),[h,x]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[u,g]=p.useState([]);return p.useEffect(()=>{(async()=>{var y;try{const v=await Ys("DOCUMENT_POLICY"),w={};v.forEach(P=>{w[P.configKey]=P.configValue});const C=parseInt(w.MAX_FILE_SIZE_MB||"10"),S=(w.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(P=>P.trim().toLowerCase());x({maxFileSizeMB:C,allowedFileTypes:S});const _=await Ys("SYSTEM_SETTINGS"),D=await Ys("WORKFLOW_SHARING"),A=[..._,...D],N={};A.forEach(P=>{N[P.configKey]=P.configValue}),m({maxApprovalLevels:parseInt(N.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt(N.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((y=N.ALLOW_ADD_SPECTATOR)==null?void 0:y.toLowerCase())==="true",maxSpectators:parseInt(N.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(v){console.error("Failed to load policies:",v)}})()},[]),p.useEffect(()=>{if(!t||!s)return;let f=!0;return(async()=>{try{c(!0);const y=await vs(s);if(!f||!y)return;const v=y.workflow||{},w=Array.isArray(y.approvals)?y.approvals:[],C=Array.isArray(y.participants)?y.participants:[],k=Array.isArray(y.documents)?y.documents.filter(R=>!R.isDeleted):[];g(k);const S=(v.priority||"").toString().toLowerCase(),_={standard:"standard",express:"express"},D=v.templateType==="TEMPLATE"?"existing-template":"custom",A=a.find(R=>R.id===D)||a[0]||null;l(A);const N=w.sort((R,O)=>(R.levelNumber||0)-(O.levelNumber||0)).map(R=>{const O=Number(R.tatHours||24),F=Math.floor(O/24),$=O%24;return{id:R.approverId||`temp-${R.levelNumber}`,name:R.approverName||R.approverEmail||"",email:R.approverEmail||"",role:R.levelName||`Level ${R.levelNumber}`,department:"",avatar:(R.approverName||R.approverEmail||"XX").substring(0,2).toUpperCase(),level:R.levelNumber||1,canClose:!1,tat:F>0?F:$,tatType:F>0?"days":"hours",userId:R.approverId}}),P=C.filter(R=>(R.participantType||R.participant_type||"").toString().toUpperCase().trim()==="SPECTATOR"?!!(R.userEmail||R.user_email||R.email):!1).map((R,O)=>{const F=R.userId||R.user_id||R.id,$=R.userName||R.user_name||R.name||"",V=R.userEmail||R.user_email||R.email||"",j=($||V||"XX").split(" ").map(U=>U[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{id:F||`spectator-${s}-${O}-${Date.now()}`,userId:F,name:$||V||"Spectator",email:V,role:"Spectator",department:R.department||"",avatar:j,level:1,canClose:!1}});n(R=>({...R,template:D,title:v.title||"",description:v.description||"",priority:_[S]||"standard",approvers:N,approverCount:N.length||1,spectators:P,maxLevel:Math.max(...N.map(O=>O.level||1),1)}))}catch(y){console.error("Failed to load draft:",y)}finally{f&&c(!1)}})(),()=>{f=!1}},[t,s,a]),{formData:r,setFormData:n,updateFormData:(f,y)=>{n(v=>({...v,[f]:y}))},selectedTemplate:i,setSelectedTemplate:l,loadingDraft:o,systemPolicy:d,documentPolicy:h,existingDocuments:u,setExistingDocuments:g}}const uu=["Template Selection","Basic Information","Approval Workflow","Participants & Access","Documents & Attachments","Review & Submit"];function cS(t,s,a){const[r,n]=p.useState(t?2:1),i=uu.length,l=h=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(h),o=()=>{switch(r){case 1:return s!==null;case 2:return a.title.trim()!==""&&a.description.trim()!==""&&a.priority!=="";case 3:return(a.approverCount||1)>0&&a.approvers.length===(a.approverCount||1)&&a.approvers.every(h=>{if(!h||!h.email||!l(h.email))return!1;if(!h.userId)return!0;const x=h.tatType||"hours";return x==="hours"?h.tat&&h.tat>0&&h.tat<=720:x==="days"?h.tat&&h.tat>0&&h.tat<=30:!1});case 4:return!0;case 5:return!0;case 6:return!0;default:return!1}};return{currentStep:r,setCurrentStep:n,totalSteps:i,stepNames:uu,isStepValid:o,nextStep:()=>{o()&&(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),r{r>1&&(n(r-1),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}))},goToStep:h=>{h>=1&&h<=i&&n(h)},validateEmail:l}}function dS(){const[t,s]=p.useState({open:!1,type:"error",email:"",message:""}),[a,r]=p.useState({open:!1,violations:[]}),[n,i]=p.useState({open:!1,errors:[]});return{validationModal:t,policyViolationModal:a,documentErrorModal:n,openValidationModal:(x,u,g="")=>{s({open:!0,type:x,email:u,message:g})},closeValidationModal:()=>{s(x=>({...x,open:!1}))},openPolicyViolationModal:x=>{r({open:!0,violations:x})},closePolicyViolationModal:()=>{r({open:!1,violations:[]})},openDocumentErrorModal:x=>{i({open:!0,errors:x})},closeDocumentErrorModal:()=>{i({open:!1,errors:[]})}}}function mS(t,s){const a=typeof t=="number"?t:parseInt(String(t))||0;return s==="days"?a*24:a||24}function uS(t,s,a){var n;const r=mS(t.tat||24,t.tatType||"hours");return{levelNumber:s,levelName:`Level ${s}`,approverId:t.userId||"",approverEmail:t.email||"",approverName:t.name||((n=t.email)==null?void 0:n.split("@")[0])||`Approver ${s}`,tatHours:r,isFinalApprover:a}}function xS(t,s){return t.slice(0,s).map((a,r)=>{const n=r+1;return uS(a,n,n===s)})}function xu(t,s,a,r=!1){return{templateId:(s==null?void 0:s.id)||null,templateType:(s==null?void 0:s.id)==="custom"?"CUSTOM":"TEMPLATE",title:t.title,description:t.description,priorityUi:t.priority==="express"?"express":"standard",approverCount:t.approverCount||1,approvers:(t.approvers||[]).map(n=>({userId:(n==null?void 0:n.userId)||"",email:(n==null?void 0:n.email)||"",name:n==null?void 0:n.name,tat:(n==null?void 0:n.tat)||24,tatType:(n==null?void 0:n.tatType)||"hours"})),spectators:(t.spectators||[]).map(n=>({userId:(n==null?void 0:n.userId)||"",name:(n==null?void 0:n.name)||"",email:(n==null?void 0:n.email)||""})),ccList:[],participants:[],isDraft:r}}function hu(t,s,a,r=!1){const n=xS(t.approvers||[],t.approverCount||1);return{title:t.title,description:t.description,priority:t.priority==="express"?"EXPRESS":"STANDARD",approvalLevels:n,participants:[],deleteDocumentIds:a.length>0?a:void 0,isDraft:r}}function hS(t,s){const a=t.slice(0,s);if(a.some(l=>!(l!=null&&l.email)||!l.email.trim()))return{valid:!1,message:"Please provide email addresses for all approvers."};const n=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return a.some(l=>!n.test((l==null?void 0:l.email)||""))?{valid:!1,message:"Please provide valid email addresses for all approvers."}:{valid:!0}}async function pu(t,s){return{id:(await Io(t,s||[],"SUPPORTING")).id}}async function gu(t,s,a,r){const n=a&&a.length>0,i=r.length>0;n||i?await sN(t,s,a||[],r):await tN(t,s)}function pS({formData:t,selectedTemplate:s,documents:a,documentsToDelete:r,user:n,isEditing:i,editRequestId:l,onSubmit:o}){const[c,d]=p.useState(!1),[m,h]=p.useState(!1);return{submitting:c,savingDraft:m,handleSubmit:async()=>{var b,f;if(c||m)return;const g=hS(t.approvers||[],t.approverCount||1);if(!g.valid){alert(g.message);return}d(!0);try{if(i&&l){const y=hu(t,n,r,!1);await gu(l,y,a,r),K.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been submitted and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const y=xu(t,s,n,!1),v=await pu(y,a);K.success("Request Submitted Successfully!",{description:`Your request "${t.title}" has been created and sent for approval.`,duration:5e3}),o==null||o({...t,backendId:v.id,template:s})}}catch(y){console.error("Failed to submit workflow:",y),K.error("Failed to Submit Request",{description:((f=(b=y==null?void 0:y.response)==null?void 0:b.data)==null?void 0:f.message)||(y==null?void 0:y.message)||"An error occurred while submitting the request.",duration:5e3}),d(!1)}},handleSaveDraft:async()=>{var g,b;if(!(!s||!t.title.trim()||!t.description.trim()||!t.priority)&&!(c||m)){h(!0);try{if(i&&l){const f=hu(t,n,r,!0);await gu(l,f,a,r),K.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:l,template:s})}else{const f=xu(t,s,n,!0),y=await pu(f,a);K.success("Draft Saved Successfully!",{description:`Your request "${t.title}" has been saved as draft.`,duration:5e3}),o==null||o({...t,backendId:y.id,template:s})}}catch(f){console.error("Failed to save draft:",f),K.error("Failed to Save Draft",{description:((b=(g=f==null?void 0:f.response)==null?void 0:g.data)==null?void 0:b.message)||(f==null?void 0:f.message)||"An error occurred while saving the draft.",duration:5e3}),h(!1)}}}}}async function ia(t,s=10,a="default"){return await je.get("/users/search",{params:{q:t,limit:s,source:a}})}async function ra(t){var a;const s=await je.post("/users/ensure",t);return((a=s.data)==null?void 0:a.data)||s.data}async function gS(t,s){return await je.post("/admin/users/assign-role",{email:t,role:s})}async function fS(t,s){return await je.put(`/admin/users/${t}/role`,{role:s})}async function bS(t,s=1,a=10){return await je.get("/admin/users/by-role",{params:{role:t||"ELEVATED",page:s,limit:a}})}async function yS(){return await je.get("/admin/users/role-statistics")}async function vS(t){var a;const s=await je.get(`/users/${t}`);return((a=s.data)==null?void 0:a.data)||s.data}async function jS(){var s,a;return((a=(s=(await je.get("/users")).data)==null?void 0:s.data)==null?void 0:a.users)||[]}const dr={searchUsers:ia,getUserById:vS,ensureUserExists:ra,assignRole:gS,updateUserRole:fS,getUsersByRole:bS,getRoleStatistics:yS,getAllUsers:jS};async function NS(t,s){var a;if(t.email.toLowerCase()===s.toLowerCase())return{success:!1,error:{type:"self-assign",email:t.email,message:""}};try{const n=((a=(await ia(t.email,1)).data)==null?void 0:a.data)||[];if(n.length===0)return{success:!1,error:{type:"not-found",email:t.email,message:""}};const i=n[0];return i?(await ra({userId:i.userId,email:i.email,displayName:i.displayName,firstName:i.firstName,lastName:i.lastName,department:i.department,phone:i.phone,mobilePhone:i.mobilePhone,designation:i.designation,jobTitle:i.jobTitle,manager:i.manager,employeeId:i.employeeId,employeeNumber:i.employeeNumber,secondEmail:i.secondEmail,location:i.location}),{success:!0}):{success:!1,error:{type:"error",email:t.email,message:"Could not retrieve user details. Please try again."}}}catch(r){return console.error(`Failed to validate approver ${t.email}:`,r),{success:!1,error:{type:"error",email:t.email,message:"Failed to validate user. Please try again or select a different user."}}}}async function wS(t,s){var n;if(t.filter(i=>i&&i.email&&!i.userId).length===0)return{success:!0,validatedApprovers:t};const r=[...t];for(let i=0;i{s(D),a("template",D.id),a("category",D.category),a("priority",D.priority);const A=new Date;A.setDate(A.getDate()+D.suggestedSLA),a("slaEndDate",A),D.id!=="custom"&&D.id!=="existing-template"&&u(`/create-admin-request/${D.id}`)},handleTemplateSelection:D=>{D==="claim-management"?u("/claim-management"):D==="vendor-payment"?u("/vendor-payment"):x&&x({templateType:D})},nextStep:async()=>{var D;if(i()){if(n===1&&(t==null?void 0:t.id)==="existing-template"){b(!0);return}if(window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"}),n===3){if(m&&h){const P=r.approverCount||1;if(P>m.maxApprovalLevels){h([{type:"Maximum Approval Levels Exceeded",message:`The request has ${P} approval levels, which exceeds the maximum allowed (${m.maxApprovalLevels}). Please reduce the number of approvers.`,currentValue:P,maxValue:m.maxApprovalLevels}]);return}}const A=((D=c==null?void 0:c.email)==null?void 0:D.toLowerCase())||"",N=await wS(r.approvers,A);if(!N.success&&N.error){d(N.error.type,N.error.email,N.error.message);return}N.validatedApprovers&&a("approvers",N.validatedApprovers)}l()}},prevStep:()=>{o(),window.innerWidth<640&&window.scrollTo({top:0,behavior:"smooth"})},handlePreviewDocument:(D,A)=>{if(A){const N=D.documentId||D.document_id||"";y({fileName:D.originalFileName||D.fileName||"Document",fileType:D.fileType||D.file_type||"application/octet-stream",fileUrl:Hr(N),fileSize:Number(D.fileSize||D.file_size||0),documentId:N})}else{const N=URL.createObjectURL(D);y({fileName:D.name,fileType:D.type||"application/octet-stream",fileUrl:N,fileSize:D.size,file:D})}},closePreview:()=>{f!=null&&f.fileUrl&&(f!=null&&f.file)&&URL.revokeObjectURL(f.fileUrl),y(null)}}}const fu=[{id:"custom",name:"Non-Templatized",description:"Create a custom request for unique business needs with full flexibility to define your own workflow and requirements",category:"General",icon:Ni,estimatedTime:"Variable",commonApprovers:[],suggestedSLA:3,priority:"medium",fields:{}},{id:"existing-template",name:"Existing Template",description:"Use a pre-configured template with predefined approval workflows, timelines, and requirements for faster processing",category:"Templates",icon:Re,estimatedTime:"1-2 days",commonApprovers:["Department Head","Manager"],suggestedSLA:2,priority:"medium",fields:{timeline:!0}}];let br=null;const bu=()=>br,SS=async t=>{const a=(await je.post("/templates",t)).data.data,r={id:a.templateId||a.id,name:a.templateName||a.name,description:a.templateDescription||a.description,category:a.templateCategory||a.category,priority:a.priority||"medium",estimatedTime:a.estimatedTime||"Variable",approvers:a.approvalLevelsConfig||a.approvers||[],suggestedSLA:a.defaultTatHours||a.suggestedSLA||24,isActive:a.isActive,fields:a.userFieldMappings||a.fields};return br&&br.push(r),r},Mi=async()=>{var r;const a=(((r=(await je.get("/templates")).data)==null?void 0:r.data)||[]).map(n=>({id:n.templateId||n.id,name:n.templateName||n.name,description:n.templateDescription||n.description,category:n.templateCategory||n.category,priority:n.priority||"medium",estimatedTime:n.estimatedTime||"Variable",approvers:n.approvalLevelsConfig||n.approvers||[],suggestedSLA:n.defaultTatHours||n.suggestedSLA||24,isActive:n.isActive,fields:n.userFieldMappings||n.fields}));return br=a,a},AS=async(t,s)=>{const r=(await je.put(`/templates/${t}`,s)).data.data,n={id:r.templateId||r.id,name:r.templateName||r.name,description:r.templateDescription||r.description,category:r.templateCategory||r.category,priority:r.priority||"medium",estimatedTime:r.estimatedTime||"Variable",approvers:r.approvalLevelsConfig||r.approvers||[],suggestedSLA:r.defaultTatHours||r.suggestedSLA||24,isActive:r.isActive,fields:r.userFieldMappings||r.fields};return br&&(br=br.map(i=>i.id===t?n:i)),n};function Rp({currentStep:t,totalSteps:s,stepNames:a}){const r=Math.round(t/s*100),n=a.length<=3?"max-w-xl":"max-w-6xl";return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-2 sm:py-3 flex-shrink-0","data-testid":"wizard-stepper",children:e.jsxs("div",{className:`${n} mx-auto`,children:[e.jsxs("div",{className:"block sm:hidden","data-testid":"wizard-stepper-mobile",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-green-600 text-white flex items-center justify-center text-xs font-semibold","data-testid":"wizard-stepper-mobile-current-step",children:t}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-gray-900","data-testid":"wizard-stepper-mobile-step-name",children:a[t-1]}),e.jsxs("p",{className:"text-xs text-gray-600","data-testid":"wizard-stepper-mobile-step-info",children:["Step ",t," of ",s]})]})]}),e.jsx("div",{className:"text-right",children:e.jsxs("p",{className:"text-xs font-medium text-green-600","data-testid":"wizard-stepper-mobile-progress",children:[r,"%"]})})]}),e.jsx("div",{className:"w-full bg-gray-200 h-1.5 rounded-full overflow-hidden","data-testid":"wizard-stepper-mobile-progress-bar",children:e.jsx("div",{className:"bg-green-600 h-full transition-all duration-300",style:{width:`${r}%`},"data-testid":"wizard-stepper-mobile-progress-fill"})})]}),e.jsxs("div",{className:"hidden sm:block","data-testid":"wizard-stepper-desktop",children:[e.jsx("div",{className:"flex items-center justify-center gap-4 mb-2","data-testid":"wizard-stepper-desktop-steps",children:a.map((i,l)=>e.jsxs("div",{className:"flex items-center flex-1 last:flex-none","data-testid":`wizard-stepper-desktop-step-${l+1}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-xs font-semibold flex-shrink-0 ${l+1e.jsx("span",{className:`${l+1===t?"font-semibold text-green-600":""}`,"data-testid":`wizard-stepper-desktop-label-${l+1}`,children:i},l))})]})]})})}function TS({currentStep:t,totalSteps:s,isStepValid:a,onPrev:r,onNext:n,onSubmit:i,onSaveDraft:l,submitting:o,savingDraft:c,loadingDraft:d,isEditing:m}){return e.jsx("div",{className:"fixed sm:relative bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0 shadow-lg sm:shadow-none z-50","data-testid":"wizard-footer",children:e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-2 sm:gap-4 max-w-6xl mx-auto",children:[e.jsxs(E,{variant:"outline",onClick:r,disabled:t===1,size:"sm",className:"sm:size-lg order-2 sm:order-1","data-testid":"wizard-footer-prev-button",children:[e.jsx(Ns,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),e.jsx("span",{className:"text-xs sm:text-sm",children:"Previous"})]}),e.jsxs("div",{className:"flex gap-2 sm:gap-3 order-1 sm:order-2","data-testid":"wizard-footer-actions",children:[e.jsx(E,{variant:"outline",onClick:l,size:"sm",className:"sm:size-lg flex-1 sm:flex-none text-xs sm:text-sm",disabled:d||o||c,"data-testid":"wizard-footer-save-draft-button",children:c?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),e.jsx("span",{children:m?"Updating...":"Saving..."})]}):e.jsx("span",{children:m?"Update Draft":"Save Draft"})}),t===s?e.jsx(E,{onClick:i,disabled:!a||d||o||c,size:"sm",className:"sm:size-lg bg-green-600 hover:bg-green-700 flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-submit-button",children:o?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(sx,{className:"h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2"}),"Submit"]})}):e.jsxs(E,{onClick:n,disabled:!a,size:"sm",className:"sm:size-lg flex-1 sm:flex-none sm:px-8 text-xs sm:text-sm","data-testid":"wizard-footer-next-button",children:[e.jsx("span",{className:"hidden sm:inline",children:"Next Step"}),e.jsx("span",{className:"sm:hidden",children:"Next"}),e.jsx(ss,{className:"h-3 w-3 sm:h-4 sm:w-4 ml-1 sm:ml-2"})]})]})]})})}const yu=t=>{switch(t){case"high":return e.jsx(ha,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Ot,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(ta,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Ot,{className:"w-4 h-4 text-gray-600"})}};function kS({templates:t,selectedTemplate:s,onSelectTemplate:a,adminTemplates:r=[]}){var d;const[n,i]=p.useState("main"),l=Ks(),o=m=>{m.id==="admin-templates-category"?i("admin"):n==="admin"?l(`/create-admin-request/${m.id}`):a(m)},c=n==="main"?[...t]:r;return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"min-h-full flex flex-col items-center justify-center py-8","data-testid":"template-selection-step",children:[e.jsxs("div",{className:"text-center mb-12 max-w-3xl","data-testid":"template-selection-header",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-gray-900 mb-4","data-testid":"template-selection-title",children:n==="main"?"Choose Your Request Type":"Organization Templates"}),e.jsx("p",{className:"text-lg text-gray-600","data-testid":"template-selection-description",children:n==="main"?"Start with a pre-built template for faster approvals, or create a custom request tailored to your needs.":"Select a pre-configured workflow template defined by your organization."})]}),n==="admin"&&e.jsx("div",{className:"w-full max-w-6xl mb-6 flex justify-start",children:e.jsxs(E,{variant:"ghost",className:"gap-2",onClick:()=>i("main"),children:[e.jsx(Ns,{className:"w-4 h-4"}),"Back to All Types"]})}),e.jsx("div",{className:"w-full max-w-6xl grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8","data-testid":"template-selection-grid",children:c.length===0&&n==="admin"?e.jsxs("div",{className:"col-span-full text-center py-12 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed border-gray-200",children:[e.jsx(i0,{className:"w-12 h-12 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No admin templates available yet."})]}):c.map(m=>{var g;const x=m.id==="admin-templates-category",u=(s==null?void 0:s.id)===m.id;return e.jsx(ts.div,{whileHover:{scale:1.03},whileTap:{scale:.98},transition:{type:"spring",stiffness:300,damping:20},"data-testid":`template-card-${m.id}`,children:e.jsxs(ee,{className:`h-full transition-all duration-300 border-2 ${u?"border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200 cursor-pointer":x?"border-blue-200 bg-blue-50/30 hover:border-blue-400 hover:shadow-lg cursor-pointer":"border-gray-200 hover:border-blue-300 hover:shadow-lg cursor-pointer"}`,onClick:()=>o(m),"data-testid":`template-card-${m.id}-clickable`,children:[e.jsxs(ge,{className:"space-y-4 pb-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`w-14 h-14 rounded-xl flex items-center justify-center ${u||x?"bg-blue-100":"bg-gray-100"}`,"data-testid":`template-card-${m.id}-icon`,children:e.jsx(m.icon,{className:`w-7 h-7 ${u||x?"text-blue-600":"text-gray-600"}`})}),u&&e.jsx(ts.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:500,damping:15},"data-testid":`template-card-${m.id}-selected-indicator`,children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center",children:e.jsx(yr,{className:"w-5 h-5 text-white"})})})]}),e.jsxs("div",{className:"text-left",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsx(fe,{className:"text-xl","data-testid":`template-card-${m.id}-name`,children:m.name}),!1]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{variant:"secondary",className:"text-xs","data-testid":`template-card-${m.id}-category`,children:m.category}),yu(m.priority)]})]})]}),e.jsxs(se,{className:"pt-0 space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed line-clamp-2","data-testid":`template-card-${m.id}-description`,children:m.description}),!x&&e.jsxs(e.Fragment,{children:[e.jsx(Ts,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs text-gray-500",children:[e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-estimated-time`,children:[e.jsx(st,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:m.estimatedTime})]}),e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`template-card-${m.id}-approvers-count`,children:[e.jsx(cs,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[((g=m.commonApprovers)==null?void 0:g.length)||0," approvers"]})]})]})]}),x&&e.jsx("div",{className:"pt-2",children:e.jsx("p",{className:"text-xs text-blue-600 font-medium flex items-center gap-1",children:"Click to browse templates โ†’"})})]})]})},m.id)})}),e.jsx(Ei,{children:s&&e.jsx(ts.div,{initial:{opacity:0,y:20,height:0},animate:{opacity:1,y:0,height:"auto"},exit:{opacity:0,y:-20,height:0},transition:{duration:.3},className:"w-full max-w-6xl","data-testid":"template-details-card",children:e.jsxs(ee,{className:"bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-blue-900","data-testid":"template-details-title",children:[e.jsx(Ur,{className:"w-5 h-5"}),s.name," - Template Details"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-sla",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Suggested SLA"}),e.jsxs("p",{className:"text-blue-700 mt-1",children:[s.suggestedSLA," hours"]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-priority",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Priority Level"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[yu(s.priority),e.jsx("span",{className:"text-blue-700 capitalize",children:s.priority})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-duration",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Estimated Duration"}),e.jsx("p",{className:"text-blue-700 mt-1",children:s.estimatedTime})]})]}),e.jsxs("div",{className:"bg-white/60 p-3 rounded-lg","data-testid":"template-details-approvers",children:[e.jsx(re,{className:"text-blue-900 font-semibold",children:"Approvers"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:((d=s.commonApprovers)==null?void 0:d.length)>0?s.commonApprovers.map((m,h)=>e.jsx(ne,{variant:"outline",className:"border-blue-300 text-blue-700 bg-white","data-testid":`template-details-approver-${h}`,children:m},`${s.id}-approver-${h}-${m}`)):e.jsx("span",{className:"text-sm text-gray-500 italic",children:"No specific approvers defined"})})]})]})]})})})]})}function Oe({className:t,type:s,...a}){return e.jsx("input",{type:s,"data-slot":"input",className:ke("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground flex h-9 w-full min-w-0 rounded-md border border-gray-400 bg-white px-3 py-1 text-base text-gray-900 transition-all outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-re-light-green focus-visible:ring-0 focus-visible:outline-none","hover:border-gray-500","aria-invalid:ring-destructive/20 aria-invalid:border-destructive",t),...a})}function RS({className:t,...s}){return e.jsx(uf,{"data-slot":"radio-group",className:ke("grid gap-3",t),...s})}function vu({className:t,...s}){return e.jsx(xf,{"data-slot":"radio-group-item",className:ke("border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(hf,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(l0,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function DS({formData:t,selectedTemplate:s,updateFormData:a}){return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"basic-information-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"basic-information-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-green-500 to-blue-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(Re,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"basic-information-title",children:"Basic Information"}),e.jsxs("p",{className:"text-gray-600","data-testid":"basic-information-description",children:["Provide the essential details for your ",(s==null?void 0:s.name)||"request","."]})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"basic-information-form",children:[e.jsxs("div",{"data-testid":"basic-information-title-field",children:[e.jsx(re,{htmlFor:"title",className:"text-base font-semibold",children:"Request Title *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-3",children:"Be specific and descriptive. This will be visible to all participants."}),e.jsx(Oe,{id:"title",placeholder:"e.g., Approval on new office location",value:t.title,onChange:r=>a("title",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-title-input"})]}),e.jsxs("div",{"data-testid":"basic-information-description-field",children:[e.jsx(re,{htmlFor:"description",className:"text-base font-semibold",children:"Detailed Description *"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Explain what you need approval for, why it's needed, and any relevant background information.",e.jsx("span",{className:"block mt-1 text-xs text-blue-600",children:"๐Ÿ’ก Tip: You can paste formatted content (lists, tables) and the formatting will be preserved."})]}),e.jsx(Rn,{value:t.description||"",onChange:r=>a("description",r),placeholder:"Provide comprehensive details about your request including scope, objectives, expected outcomes, and any supporting context that will help approvers make an informed decision.",className:"min-h-[120px] text-base border-2 border-gray-300 focus-within:border-blue-500 bg-white shadow-sm",minHeight:"120px","data-testid":"basic-information-description-textarea"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6","data-testid":"basic-information-priority-section",children:e.jsxs("div",{"data-testid":"basic-information-priority-field",children:[e.jsx(re,{className:"text-base font-semibold",children:"Priority Level *"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"select priority for your request"}),e.jsxs(RS,{value:t.priority||"",onValueChange:r=>a("priority",r),"data-testid":"basic-information-priority-radio-group",children:[e.jsxs("div",{className:`flex items-center space-x-3 p-3 rounded-lg border-2 cursor-pointer transition-all ${t.priority==="express"?"border-red-500 bg-red-100":"border-red-200 bg-red-50 hover:bg-red-100"}`,onClick:()=>a("priority","express"),"data-testid":"basic-information-priority-express-option",children:[e.jsx(vu,{value:"express",id:"express"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(xo,{className:"w-4 h-4 text-red-600"}),e.jsx(re,{htmlFor:"express",className:"font-medium text-red-900 cursor-pointer",children:"Express"}),e.jsx(ne,{variant:"destructive",className:"text-xs",children:"URGENT"})]}),e.jsx("p",{className:"text-xs text-red-700",children:"Includes calendar days in TAT - faster processing timeline"})]})]}),e.jsxs("div",{className:`flex items-center space-x-3 p-3 rounded-lg border cursor-pointer transition-all ${t.priority==="standard"?"border-blue-500 bg-blue-50":"border-gray-200 hover:bg-gray-50"}`,onClick:()=>a("priority","standard"),"data-testid":"basic-information-priority-standard-option",children:[e.jsx(vu,{value:"standard",id:"standard"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(st,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{htmlFor:"standard",className:"font-medium text-blue-900 cursor-pointer",children:"Standard"}),e.jsx(ne,{variant:"secondary",className:"text-xs",children:"DEFAULT"})]}),e.jsx("p",{className:"text-xs text-gray-600",children:"Includes working days in TAT - regular processing timeline"})]})]})]})]})}),((s==null?void 0:s.fields.amount)||(s==null?void 0:s.fields.vendor)||(s==null?void 0:s.fields.timeline)||(s==null?void 0:s.fields.impact))&&e.jsxs("div",{className:"border-t pt-6","data-testid":"basic-information-additional-details",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-4",children:"Additional Details"}),e.jsxs("div",{className:"space-y-6",children:[(s==null?void 0:s.fields.amount)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4","data-testid":"basic-information-amount-field",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{htmlFor:"amount",className:"text-base font-semibold",children:"Budget Amount"}),e.jsx(Oe,{id:"amount",placeholder:"Enter amount",value:t.amount,onChange:r=>a("amount",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-amount-input"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-base font-semibold",children:"Currency"}),e.jsxs(We,{value:t.currency,onValueChange:r=>a("currency",r),"data-testid":"basic-information-currency-select",children:[e.jsx(Ye,{className:"h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"USD",children:"USD ($)"}),e.jsx(Y,{value:"EUR",children:"EUR (โ‚ฌ)"}),e.jsx(Y,{value:"GBP",children:"GBP (ยฃ)"}),e.jsx(Y,{value:"INR",children:"INR (โ‚น)"})]})]})]})]}),(s==null?void 0:s.fields.vendor)&&e.jsxs("div",{"data-testid":"basic-information-vendor-field",children:[e.jsx(re,{htmlFor:"vendor",className:"text-base font-semibold",children:"Vendor/Supplier"}),e.jsx(Oe,{id:"vendor",placeholder:"Enter vendor or supplier name",value:t.vendor,onChange:r=>a("vendor",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-vendor-input"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{"data-testid":"basic-information-cost-center-field",children:[e.jsx(re,{htmlFor:"costCenter",className:"text-base font-semibold",children:"Cost Center"}),e.jsx(Oe,{id:"costCenter",placeholder:"e.g., Marketing, IT, Operations",value:t.costCenter,onChange:r=>a("costCenter",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-cost-center-input"})]}),e.jsxs("div",{"data-testid":"basic-information-project-field",children:[e.jsx(re,{htmlFor:"project",className:"text-base font-semibold",children:"Related Project"}),e.jsx(Oe,{id:"project",placeholder:"Associated project name or code",value:t.project,onChange:r=>a("project",r.target.value),className:"text-base h-12 border-2 border-gray-300 focus:border-blue-500 bg-white shadow-sm","data-testid":"basic-information-project-input"})]})]})]})]})]})]})}function Dp(){const[t,s]=p.useState([]),[a,r]=p.useState(!1),n=p.useRef(null);return{searchResults:t,searchLoading:a,searchUsersDebounced:async(c,d=10)=>{if(n.current&&clearTimeout(n.current),!c||!c.startsWith("@")||c.length<2){s([]),r(!1);return}r(!0),n.current=setTimeout(async()=>{var m;try{const h=c.slice(1),u=((m=(await ia(h,d)).data)==null?void 0:m.data)||[];s(u)}catch(h){console.error("User search failed:",h),s([])}finally{r(!1)}},300)},clearSearch:()=>{n.current&&clearTimeout(n.current),s([]),r(!1)},ensureUser:async c=>{try{return await ra({userId:c.userId,email:c.email,displayName:c.displayName,firstName:c.firstName,lastName:c.lastName,department:c.department,phone:c.phone,mobilePhone:c.mobilePhone,designation:c.designation,jobTitle:c.jobTitle,manager:c.manager,employeeId:c.employeeId,employeeNumber:c.employeeNumber,secondEmail:c.secondEmail,location:c.location})}catch(d){throw console.error("Failed to ensure user exists:",d),d}}}}function Pp(){const[t,s]=p.useState({}),[a,r]=p.useState({}),n=p.useRef({});return{userSearchResults:t,userSearchLoading:a,searchUsersForIndex:async(o,c,d=10)=>{if(n.current[o]&&clearTimeout(n.current[o]),!c||!c.startsWith("@")||c.length<2){s(m=>({...m,[o]:[]})),r(m=>({...m,[o]:!1}));return}r(m=>({...m,[o]:!0})),n.current[o]=setTimeout(async()=>{var m;try{const h=c.slice(1),u=((m=(await ia(h,d)).data)==null?void 0:m.data)||[];s(g=>({...g,[o]:u}))}catch(h){console.error(`User search failed for index ${o}:`,h),s(x=>({...x,[o]:[]}))}finally{r(h=>({...h,[o]:!1}))}},300)},clearSearchForIndex:o=>{n.current[o]&&clearTimeout(n.current[o]),s(c=>({...c,[o]:[]})),r(c=>({...c,[o]:!1}))}}}function PS({formData:t,updateFormData:s,onValidationError:a,systemPolicy:r,onPolicyViolation:n}){var h;const{userSearchResults:i,userSearchLoading:l,searchUsersForIndex:o,clearSearchForIndex:c}=Pp();p.useEffect(()=>{const x=t.approverCount||1,u=t.approvers||[];if(u.lengthx&&s("approvers",u.slice(0,x))},[t.approverCount,s]);const d=(x,u)=>{var y,v,w,C,k;const g=[...t.approvers],f=((y=g[x])==null?void 0:y.email)!==u;if(g[x]={...g[x],email:u,level:x+1,userId:f||(v=g[x])==null?void 0:v.userId,name:f||(w=g[x])==null?void 0:w.name,department:f||(C=g[x])==null?void 0:C.department,avatar:f||(k=g[x])==null?void 0:k.avatar},s("approvers",g),!u||!u.startsWith("@")||u.length<2){c(x);return}o(x,u,10)},m=async(x,u)=>{var g,b;try{if((g=t.approvers)==null?void 0:g.some((C,k)=>{var S,_;return k!==x&&(C.userId===u.userId||((S=C.email)==null?void 0:S.toLowerCase())===((_=u.email)==null?void 0:_.toLowerCase()))})){a({type:"error",email:u.email,message:"This user is already added as an approver in another level."});return}if((b=t.spectators)==null?void 0:b.some(C=>{var k,S;return C.userId===u.userId||((k=C.email)==null?void 0:k.toLowerCase())===((S=u.email)==null?void 0:S.toLowerCase())})){a({type:"error",email:u.email,message:"This user is already added as a spectator. A user cannot be both an approver and a spectator."});return}const v=await ra({userId:u.userId,email:u.email,displayName:u.displayName,firstName:u.firstName,lastName:u.lastName,department:u.department,phone:u.phone,mobilePhone:u.mobilePhone,designation:u.designation,jobTitle:u.jobTitle,manager:u.manager,employeeId:u.employeeId,employeeNumber:u.employeeNumber,secondEmail:u.secondEmail,location:u.location}),w=[...t.approvers];w[x]={...w[x],email:u.email,name:u.displayName||[u.firstName,u.lastName].filter(Boolean).join(" "),userId:v.userId,level:x+1},s("approvers",w),c(x)}catch(f){console.error("Failed to ensure user exists:",f),a({type:"error",email:u.email,message:"Failed to validate user. Please try again."})}};return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"approval-workflow-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"approval-workflow-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-orange-500 to-red-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(cs,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"approval-workflow-title",children:"Approval Workflow"}),e.jsx("p",{className:"text-gray-600","data-testid":"approval-workflow-description",children:"Define the approval hierarchy and assign approvers by email ID."})]}),e.jsxs("div",{className:"max-w-4xl mx-auto space-y-8","data-testid":"approval-workflow-content",children:[e.jsxs(ee,{"data-testid":"approval-workflow-config-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"approval-workflow-config-title",children:[e.jsx(Va,{className:"w-5 h-5"}),"Approval Configuration"]}),e.jsx($e,{children:"Configure how many approvers you need and define the approval sequence."})]}),e.jsx(se,{className:"space-y-6",children:e.jsxs("div",{"data-testid":"approval-workflow-count-field",children:[e.jsx(re,{className:"text-base font-semibold mb-4 block",children:"Number of Approvers *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const x=t.approverCount||1,u=Math.max(1,x-1);s("approverCount",u),t.approvers.length>u&&s("approvers",t.approvers.slice(0,u))},disabled:(t.approverCount||1)<=1,"data-testid":"approval-workflow-decrease-count",children:e.jsx(ho,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-2xl font-semibold w-12 text-center","data-testid":"approval-workflow-count-display",children:t.approverCount||1}),e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{const u=(t.approverCount||1)+1;if(u>r.maxApprovalLevels){n([{type:"Maximum Approval Levels Exceeded",message:`Cannot add more than ${r.maxApprovalLevels} approval levels. Please remove an approver level or contact your administrator.`,currentValue:u,maxValue:r.maxApprovalLevels}]);return}s("approverCount",u)},disabled:(t.approverCount||1)>=r.maxApprovalLevels,"data-testid":"approval-workflow-increase-count",children:e.jsx(gs,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Maximum ",r.maxApprovalLevels," approver",r.maxApprovalLevels!==1?"s":""," allowed. Each approver will review sequentially."]})]})})]}),e.jsxs(ee,{"data-testid":"approval-workflow-hierarchy-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"approval-workflow-hierarchy-title",children:[e.jsx(hs,{className:"w-5 h-5"}),"Approval Hierarchy *"]}),e.jsxs($e,{children:["Define the approval sequence. Each approver will review the request in order from Level 1 to Level ",t.approverCount||1,"."]})]}),e.jsxs(se,{className:"space-y-6",children:[e.jsx("div",{className:"p-4 rounded-lg border-2 border-blue-200 bg-blue-50","data-testid":"approval-workflow-initiator-card",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center",children:e.jsx(Vt,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-blue-900",children:"Request Initiator"}),e.jsx(ne,{variant:"secondary",className:"text-xs",children:"YOU"})]}),e.jsx("p",{className:"text-sm text-blue-700",children:"Creates and submits the request"})]})]})}),Array.from({length:t.approverCount||1},(x,u)=>{var y,v;const g=u+1,b=g===(t.approverCount||1),f=t.approvers[u]||{email:"",tat:""};return e.jsxs("div",{className:"space-y-3","data-testid":`approval-workflow-approver-level-${g}`,children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-px h-6 bg-gray-300"})}),e.jsx("div",{className:`p-4 rounded-lg border-2 transition-all ${f.email?"border-green-200 bg-green-50":"border-gray-200 bg-gray-50"}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${f.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:g})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",g]}),b&&e.jsx(ne,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-email-field`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(re,{htmlFor:`approver-${g}`,className:"text-sm font-medium",children:"Email Address *"}),f.email&&f.userId&&e.jsxs(ne,{variant:"outline",className:"text-xs bg-green-50 text-green-700 border-green-300",children:[e.jsx(De,{className:"w-3 h-3 mr-1"}),"Verified"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Oe,{id:`approver-${g}`,type:"email",placeholder:"approver@royalenfield.com",value:f.email||"",onChange:w=>d(u,w.target.value),className:"h-10 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full","data-testid":`approval-workflow-approver-${g}-email-input`}),(l[u]||(((y=i[u])==null?void 0:y.length)||0)>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:l[u]?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:(v=i[u])==null?void 0:v.map(w=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>m(u,w),"data-testid":`approval-workflow-approver-${g}-search-result-${w.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:w.displayName||w.email}),e.jsx("div",{className:"text-xs text-gray-600",children:w.email})]},w.userId))})})]})]}),e.jsxs("div",{"data-testid":`approval-workflow-approver-${g}-tat-field`,children:[e.jsx(re,{htmlFor:`tat-${g}`,className:"text-sm font-medium",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Oe,{id:`tat-${g}`,type:"number",placeholder:f.tatType==="days"?"7":"24",min:"1",max:f.tatType==="days"?"30":"720",value:f.tat||"",onChange:w=>{const C=[...t.approvers];C[u]={...C[u],tat:parseInt(w.target.value)||"",level:g,tatType:f.tatType||"hours"},s("approvers",C)},className:"h-10 border-2 border-gray-300 focus:border-blue-500 flex-1","data-testid":`approval-workflow-approver-${g}-tat-input`}),e.jsxs(We,{value:f.tatType||"hours",onValueChange:w=>{const C=[...t.approvers];C[u]={...C[u],tatType:w,level:g,tat:""},s("approvers",C)},"data-testid":`approval-workflow-approver-${g}-tat-type-select`,children:[e.jsx(Ye,{className:"w-20 h-10 border-2 border-gray-300",children:e.jsx(Ge,{})}),e.jsxs(Ke,{children:[e.jsx(Y,{value:"hours",children:"Hours"}),e.jsx(Y,{value:"days",children:"Days"})]})]})]})]})]})]})]})})]},g)})]})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsx("div",{className:"p-4 bg-blue-50 rounded-lg border border-blue-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ur,{className:"w-5 h-5 text-blue-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-blue-900 mb-1",children:"Approval Flow Summary"}),e.jsxs("p",{className:"text-sm text-blue-700",children:["Your request will follow this sequence: ",e.jsx("strong",{children:"You (Initiator)"})," โ†’ ",Array.from({length:t.approverCount||1},(x,u)=>`Level ${u+1} Approver`).join(" โ†’ "),". The final approver can close the request."]})]})]})}),e.jsx("div",{className:"p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-lg border border-emerald-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(st,{className:"w-5 h-5 text-emerald-600 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-emerald-900",children:"TAT Summary"}),e.jsx("div",{className:"text-right",children:(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const y=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+y:b+y/24},0))||0,u=Math.ceil(x);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[u," ",u===1?"Day":"Days"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Duration"})]})})()})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:(h=t.approvers)==null?void 0:h.map((x,u)=>{const g=Number(x.tat||0),f=(x.tatType||"hours")==="days"?g*24:g;return g?e.jsx("div",{className:"bg-white/60 p-2 rounded border border-emerald-100",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium text-emerald-900",children:["Level ",u+1]}),e.jsxs("span",{className:"text-sm text-emerald-700",children:[f," ",f===1?"hour":"hours"]})]})},u):null})}),(()=>{var g;const x=((g=t.approvers)==null?void 0:g.reduce((b,f)=>{const y=Number(f.tat||0);return(f.tatType||"hours")==="days"?b+y*24:b+y},0))||0,u=Math.ceil(x/8);return x===0?null:e.jsxs("div",{className:"bg-white/80 p-3 rounded border border-emerald-200",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-lg font-bold text-emerald-800",children:[x,"h"]}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Total Hours"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-emerald-800",children:u}),e.jsx("div",{className:"text-xs text-emerald-600",children:"Working Days*"})]})]}),e.jsx("p",{className:"text-xs text-emerald-600 mt-2 text-center",children:"*Based on 8-hour working days"})]})})()]})]})]})})]})]})]})}function IS({formData:t,updateFormData:s,onValidationError:a,initiatorEmail:r}){const[n,i]=p.useState(""),{searchResults:l,searchLoading:o,searchUsersDebounced:c,clearSearch:d,ensureUser:m}=Dp(),h=g=>{if(i(g),!g||!g.startsWith("@")||g.length<2){d();return}c(g,10)},x=async g=>{var b,f;if(g){if(g.email.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:g.email,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(w=>{var C,k;return w.userId===g.userId||((C=w.email)==null?void 0:C.toLowerCase())===((k=g.email)==null?void 0:k.toLowerCase())}),v=(b=t.approvers)==null?void 0:b.some(w=>{var C,k;return w.userId===g.userId||((C=w.email)==null?void 0:C.toLowerCase())===((k=g.email)==null?void 0:k.toLowerCase())});if(y){a({type:"error",email:g.email,message:"This user is already added as a spectator."});return}if(v){a({type:"error",email:g.email,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}try{const w=await m(g),C={id:w.userId,userId:w.userId,name:w.displayName||g.email.split("@")[0],email:w.email,avatar:(w.displayName||w.email).substring(0,2).toUpperCase(),role:"Spectator",department:w.department||"",level:1,canClose:!1},k=[...t.spectators,C];s("spectators",k),i(""),d()}catch{a({type:"error",email:g.email,message:"Failed to validate user. Please try again."})}}else if(n&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)){if(n.toLowerCase()===r.toLowerCase()){a({type:"self-assign",email:n,message:"You cannot add yourself as a spectator."});return}const y=t.spectators.some(w=>{var C;return((C=w.email)==null?void 0:C.toLowerCase())===n.toLowerCase()}),v=(f=t.approvers)==null?void 0:f.some(w=>{var C;return((C=w.email)==null?void 0:C.toLowerCase())===n.toLowerCase()});if(y){a({type:"error",email:n,message:"This user is already added as a spectator."});return}if(v){a({type:"error",email:n,message:"This user is already added as an approver. A user cannot be both an approver and a spectator."});return}}},u=g=>{const b=t.spectators.filter(f=>f.id!==g);s("spectators",b)};return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"participants-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"participants-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-teal-500 to-green-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(ht,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"participants-title",children:"Participants & Access"}),e.jsx("p",{className:"text-gray-600","data-testid":"participants-description",children:"Configure additional participants and visibility settings for your request."})]}),e.jsx("div",{className:"max-w-3xl mx-auto space-y-8","data-testid":"participants-content",children:e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:e.jsxs(ee,{"data-testid":"participants-spectators-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center justify-between text-base","data-testid":"participants-spectators-title",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ht,{className:"w-4 h-4"}),"Spectators"]}),e.jsx(ne,{variant:"outline",className:"text-xs","data-testid":"participants-spectators-count",children:t.spectators.length})]}),e.jsx($e,{children:"Users who can view and comment but cannot approve"})]}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2","data-testid":"participants-spectators-add-section",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-full",children:[e.jsx(Oe,{placeholder:"Use @ sign to add a user",value:n,onChange:g=>h(g.target.value),onKeyPress:async g=>{g.key==="Enter"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)&&(g.preventDefault(),await x())},className:"text-sm w-full","data-testid":"participants-spectators-email-input"}),(o||l.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg",children:o?e.jsx("div",{className:"p-2 text-xs text-gray-500",children:"Searching..."}):e.jsx("ul",{className:"max-h-56 overflow-auto divide-y",children:l.map(g=>e.jsxs("li",{className:"p-2 text-sm cursor-pointer hover:bg-gray-50",onClick:()=>x(g),"data-testid":`participants-spectators-search-result-${g.userId}`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:g.displayName||g.email}),e.jsx("div",{className:"text-xs text-gray-600",children:g.email})]},g.userId))})})]}),e.jsx(E,{size:"sm",onClick:()=>x(),disabled:!n||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n),"data-testid":"participants-spectators-add-button",children:"Add"})]}),e.jsxs("p",{className:"text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded p-2 flex items-center gap-1",children:[e.jsx(Ur,{className:"w-3 h-3 flex-shrink-0"}),e.jsxs("span",{children:["Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users, or type email directly (will be validated against organization directory)"]})]})]}),e.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto","data-testid":"participants-spectators-list",children:t.spectators.map(g=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-teal-50 rounded-lg","data-testid":`participants-spectator-${g.id}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zt,{className:"h-6 w-6",children:e.jsx(Jt,{className:"bg-teal-600 text-white text-xs",children:g.avatar})}),e.jsx("span",{className:"text-sm font-medium",children:g.name})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(g.id),"data-testid":`participants-spectator-${g.id}-remove`,children:e.jsx(ft,{className:"h-3 w-3"})})]},g.id))})]})]})})})]})}function ES({documentPolicy:t,isEditing:s,documents:a,existingDocuments:r,documentsToDelete:n,onDocumentsChange:i,onExistingDocumentsChange:l,onDocumentsToDeleteChange:o,onPreviewDocument:c,onDocumentErrors:d,fileInputRef:m}){const h=b=>{const f=Array.from(b.target.files||[]);if(f.length===0)return;const y=t.maxFileSizeMB*1024*1024,v=[],w=[];f.forEach(C=>{if(C.size>y){v.push({fileName:C.name,reason:`File size exceeds the maximum allowed size of ${t.maxFileSizeMB}MB. Current size: ${(C.size/1048576).toFixed(2)}MB`});return}const k=C.name.toLowerCase(),S=k.substring(k.lastIndexOf(".")+1);if(!t.allowedFileTypes.includes(S)){v.push({fileName:C.name,reason:`File type "${S}" is not allowed. Allowed types: ${t.allowedFileTypes.join(", ")}`});return}w.push(C)}),w.length>0&&i([...a,...w]),v.length>0&&d&&d(v),b.target&&(b.target.value="")},x=b=>{const f=a.filter((y,v)=>v!==b);i(f)},u=b=>{o([...n,b])},g=(b,f=!1)=>{if(f){const y=(b.fileType||b.file_type||"").toLowerCase(),v=(b.originalFileName||b.fileName||"").toLowerCase();return y.includes("image")||y.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}else{const y=(b.type||"").toLowerCase(),v=(b.name||"").toLowerCase();return y.includes("image")||y.includes("pdf")||v.endsWith(".jpg")||v.endsWith(".jpeg")||v.endsWith(".png")||v.endsWith(".gif")||v.endsWith(".pdf")}};return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"documents-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"documents-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(zs,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"documents-title",children:"Documents & Attachments"}),e.jsx("p",{className:"text-gray-600","data-testid":"documents-description",children:"Upload supporting documents, files, and any additional materials for your request."})]}),e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6","data-testid":"documents-content",children:[e.jsxs(ee,{"data-testid":"documents-upload-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"documents-upload-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"File Upload"]}),e.jsxs($e,{children:["Attach supporting documents. Max ",t.maxFileSizeMB,"MB per file. Allowed types: ",t.allowedFileTypes.join(", ")]})]}),e.jsx(se,{children:e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-gray-400 transition-colors","data-testid":"documents-upload-area",children:[e.jsx(zs,{className:"h-12 w-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Upload Files"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"click to browse"}),e.jsx("input",{type:"file",multiple:!0,accept:t.allowedFileTypes.map(b=>`.${b}`).join(","),onChange:h,className:"hidden",id:"file-upload",ref:m,"data-testid":"documents-file-input"}),e.jsxs(E,{variant:"outline",size:"lg",type:"button",onClick:()=>{var b;return(b=m.current)==null?void 0:b.click()},"data-testid":"documents-browse-button",children:[e.jsx(gs,{className:"w-4 h-4 mr-2"}),"Browse Files"]}),e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Supported formats: ",t.allowedFileTypes.map(b=>b.toUpperCase()).join(", ")," (Max ",t.maxFileSizeMB,"MB per file)"]})]})})]}),s&&r.length>0&&e.jsxs(ee,{"data-testid":"documents-existing-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center justify-between","data-testid":"documents-existing-title",children:[e.jsx("span",{children:"Existing Documents"}),e.jsxs(ne,{variant:"secondary","data-testid":"documents-existing-count",children:[r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length," file",r.filter(b=>!n.includes(b.documentId||b.document_id||"")).length!==1?"s":""]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-existing-list",children:r.map(b=>{const f=b.documentId||b.document_id||"";return n.includes(f)?null:e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-gray-50","data-testid":`documents-existing-${f}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.originalFileName||b.fileName||"Document"}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsx("span",{children:b.fileSize?(Number(b.fileSize)/(1024*1024)).toFixed(2)+" MB":"Unknown size"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!0)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>c(b,!0),"data-testid":`documents-existing-${f}-preview`,children:e.jsx(ht,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>u(f),"data-testid":`documents-existing-${f}-delete`,children:e.jsx(ft,{className:"h-4 w-4 text-red-600"})})]})]},f)})})})]}),a.length>0&&e.jsxs(ee,{"data-testid":"documents-new-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center justify-between","data-testid":"documents-new-title",children:[e.jsx("span",{children:"New Files to Upload"}),e.jsxs(ne,{variant:"secondary","data-testid":"documents-new-count",children:[a.length," file",a.length!==1?"s":""]})]})}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"documents-new-list",children:a.map((b,f)=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border","data-testid":`documents-new-${f}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(Re,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900",children:b.name}),e.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:e.jsxs("span",{children:[(b.size/(1024*1024)).toFixed(2)," MB"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g(b,!1)&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>c(b,!1),"data-testid":`documents-new-${f}-preview`,children:e.jsx(ht,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>x(f),"data-testid":`documents-new-${f}-remove`,children:e.jsx(ft,{className:"h-4 w-4"})})]})]},f))})})]})]})]})}const FS=t=>{switch(t){case"high":return e.jsx(ha,{className:"w-4 h-4 text-red-600"});case"medium":return e.jsx(Ot,{className:"w-4 h-4 text-orange-600"});case"low":return e.jsx(ta,{className:"w-4 h-4 text-green-600"});default:return e.jsx(Ot,{className:"w-4 h-4 text-gray-600"})}};function _S({formData:t,selectedTemplate:s}){return e.jsxs(ts.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"space-y-6","data-testid":"review-submit-step",children:[e.jsxs("div",{className:"text-center mb-8","data-testid":"review-submit-header",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-green-500 to-teal-600 rounded-2xl flex items-center justify-center mx-auto mb-4",children:e.jsx(De,{className:"w-8 h-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2","data-testid":"review-submit-title",children:"Review & Submit"}),e.jsx("p",{className:"text-gray-600","data-testid":"review-submit-description",children:"Please review all details before submitting your request for approval."})]}),e.jsxs("div",{className:"max-w-5xl mx-auto space-y-8","data-testid":"review-submit-content",children:[e.jsxs(ee,{className:"border-2 border-green-200 bg-green-50/50","data-testid":"review-submit-overview-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-green-900","data-testid":"review-submit-overview-title",children:[e.jsx(sx,{className:"w-5 h-5"}),"Request Overview"]})}),e.jsxs(se,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6","data-testid":"review-submit-overview-grid",children:[e.jsxs("div",{"data-testid":"review-submit-overview-type",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Request Type"}),e.jsx("p",{className:"text-green-800 mt-1",children:s==null?void 0:s.name}),e.jsx(ne,{variant:"outline",className:"mt-2 text-xs border-green-300 text-green-700",children:s==null?void 0:s.category})]}),e.jsxs("div",{"data-testid":"review-submit-overview-priority",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Priority"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[FS(t.priority),e.jsx("span",{className:"text-green-800 capitalize",children:t.priority})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-workflow",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Workflow Type"}),e.jsx("p",{className:"text-green-800 mt-1 capitalize",children:t.workflowType}),e.jsxs("p",{className:"text-sm text-green-700",children:[t.approverCount||1," Level",(t.approverCount||1)>1?"s":""]})]})]}),e.jsxs("div",{"data-testid":"review-submit-overview-title",children:[e.jsx(re,{className:"text-green-900 font-semibold",children:"Request Title"}),e.jsx("p",{className:"text-green-800 font-medium mt-1 text-lg",children:t.title})]})]})]}),e.jsxs(ee,{"data-testid":"review-submit-basic-info-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-basic-info-title",children:[e.jsx(Re,{className:"w-5 h-5"}),"Basic Information"]})}),e.jsxs(se,{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"review-submit-basic-info-description",children:[e.jsx(re,{className:"font-semibold",children:"Description"}),e.jsx("div",{className:"mt-1 p-3 bg-gray-50 rounded-lg border",children:e.jsx(sa,{content:t.description||""})})]}),t.amount&&e.jsxs("div",{className:"p-3 bg-blue-50 rounded-lg border border-blue-200","data-testid":"review-submit-basic-info-financial",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Da,{className:"w-4 h-4 text-blue-600"}),e.jsx(re,{className:"font-semibold text-blue-900",children:"Financial Details"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Amount"}),e.jsxs("p",{className:"font-semibold text-blue-900",children:[t.amount," ",t.currency]})]}),t.costCenter&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-blue-700",children:"Cost Center"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.costCenter})]})]})]})]})]}),e.jsxs(ee,{className:"border-2 border-orange-200 bg-orange-50/50","data-testid":"review-submit-approval-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-orange-900","data-testid":"review-submit-approval-title",children:[e.jsx(cs,{className:"w-5 h-5"}),"Approval Workflow"]}),e.jsx($e,{className:"text-orange-700",children:"Sequential approval hierarchy with TAT (Turn Around Time) for each level"})]}),e.jsx(se,{className:"space-y-6",children:e.jsx("div",{className:"space-y-4","data-testid":"review-submit-approval-levels",children:Array.from({length:t.approverCount||1},(a,r)=>{const n=r+1,i=n===(t.approverCount||1),l=t.approvers[r];return e.jsx("div",{className:"p-4 bg-white rounded-lg border border-orange-200","data-testid":`review-submit-approval-level-${n}`,children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${l!=null&&l.email?"bg-green-600":"bg-gray-400"}`,children:e.jsx("span",{className:"text-white font-semibold",children:n})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs("span",{className:"font-semibold text-gray-900",children:["Approver Level ",n]}),i&&e.jsx(ne,{variant:"destructive",className:"text-xs",children:"FINAL APPROVER"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Email Address"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:(l==null?void 0:l.email)||"Not assigned"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-gray-600",children:"TAT (Turn Around Time)"}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l!=null&&l.tat?`${l.tat} ${l.tatType==="days"?"day":"hour"}${l.tat!==1?"s":""}`:"Not set"})]})]})]})]})},n)})})})]}),e.jsxs(ee,{"data-testid":"review-submit-participants-card",children:[e.jsx(ge,{children:e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-participants-title",children:[e.jsx(ht,{className:"w-5 h-5"}),"Participants & Access Control"]})}),e.jsx(se,{className:"space-y-4",children:t.spectators.length>0&&e.jsxs("div",{"data-testid":"review-submit-participants-spectators",children:[e.jsxs(re,{className:"font-semibold text-sm",children:["Spectators (",t.spectators.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:t.spectators.map(a=>e.jsxs(ne,{variant:"outline",className:"text-xs","data-testid":`review-submit-spectator-${a.id}`,children:[a.name," (",a.email,")"]},a.id))})]})})]}),t.documents.length>0&&e.jsxs(ee,{"data-testid":"review-submit-documents-card",children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2","data-testid":"review-submit-documents-title",children:[e.jsx(zs,{className:"w-5 h-5"}),"Documents & Attachments"]}),e.jsxs($e,{children:[t.documents.length," document",t.documents.length!==1?"s":""," attached to this request"]})]}),e.jsx(se,{children:e.jsx("div",{className:"space-y-3","data-testid":"review-submit-documents-list",children:t.documents.map((a,r)=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-gray-50 rounded-lg border","data-testid":`review-submit-document-${r}`,children:[e.jsx(Re,{className:"w-5 h-5 text-gray-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.name}),e.jsx("div",{className:"flex items-center gap-3 text-xs text-gray-500 mt-1",children:e.jsxs("span",{children:[(a.size/(1024*1024)).toFixed(2)," MB"]})})]})]},r))})})]}),e.jsx(ee,{className:"border-2 border-blue-200 bg-blue-50/50","data-testid":"review-submit-confirmation-card",children:e.jsx(se,{className:"pt-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(De,{className:"w-6 h-6 text-blue-600 mt-1 flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-blue-900 mb-2","data-testid":"review-submit-confirmation-title",children:"Ready to Submit Request"}),e.jsx("p",{className:"text-sm text-blue-700 mb-4","data-testid":"review-submit-confirmation-message",children:"Once submitted, your request will enter the approval workflow and notifications will be sent to all relevant participants."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 text-sm","data-testid":"review-submit-confirmation-summary",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-700",children:"Request Type:"}),e.jsx("p",{className:"font-medium text-blue-900",children:s==null?void 0:s.name})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-700",children:"Approval Levels:"}),e.jsx("p",{className:"font-medium text-blue-900",children:t.approverCount||1})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-700",children:"Documents:"}),e.jsxs("p",{className:"font-medium text-blue-900",children:[t.documents.length," attached"]})]})]})]})]})})})]})]})}function LS({isEditing:t,currentStep:s,totalSteps:a,stepNames:r,onBack:n}){return e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-3 sm:py-4 flex-shrink-0","data-testid":"create-request-header",children:e.jsxs("div",{className:"flex items-center justify-between max-w-6xl mx-auto gap-2 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-1 min-w-0",children:[e.jsx(E,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 h-8 w-8 sm:h-10 sm:w-10","data-testid":"create-request-back-button",children:e.jsx(Ns,{className:"h-4 w-4 sm:h-5 sm:w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-base sm:text-xl md:text-2xl font-bold text-gray-900 truncate","data-testid":"create-request-title",children:t?"Edit Draft":"New Request"}),e.jsxs("p",{className:"text-xs sm:text-sm text-gray-600 hidden sm:block","data-testid":"create-request-step-info",children:["Step ",s," of ",a,": ",r[s-1]]})]})]}),e.jsx("div",{className:"hidden md:flex items-center gap-4","data-testid":"create-request-progress-info",children:e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium text-gray-900",children:[Math.round(s/a*100),"% Complete"]}),e.jsxs("p",{className:"text-xs text-gray-600",children:[a-s," steps remaining"]})]})})]})})}function MS({children:t}){return e.jsx("div",{className:"flex-1 overflow-y-auto pb-24 sm:pb-4","data-testid":"create-request-content",children:e.jsx("div",{className:"max-w-6xl mx-auto p-3 sm:p-6 pb-6 sm:pb-6",children:e.jsx(Ei,{mode:"wait",children:t})})})}function $S({modal:t,onClose:s}){return e.jsx(pt,{open:t.open,onOpenChange:a=>!a&&s(),"data-testid":"create-request-validation-modal",children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"validation-modal-title",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-amber-600"}),"Cannot Add Yourself"]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})]}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[t.type==="self-assign"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["You cannot add yourself (",e.jsx("strong",{children:t.email}),") as an approver."]}),e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-amber-800",children:[e.jsx("strong",{children:"Why?"})," The initiator creates the request and cannot approve their own request. Please select a different user."]})})]}),t.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:t.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Ni,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use"," ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," ","sign to search and select users from the directory for guaranteed results."]})})]}),t.type==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:[t.email&&e.jsxs(e.Fragment,{children:["Failed to validate ",e.jsx("strong",{children:t.email}),"."]}),!t.email&&e.jsx(e.Fragment,{children:"An error occurred during validation."})]}),t.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:t.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:s,className:"w-full sm:w-auto","data-testid":"validation-modal-ok-button",children:t.type==="not-found"?"Fix Email":"OK"})})]})})}function OS({modal:t,documentPolicy:s,onClose:a}){return e.jsx(pt,{open:t.open,onOpenChange:r=>!r&&a(),"data-testid":"create-request-document-error-modal",children:e.jsxs(dt,{className:"sm:max-w-lg",children:[e.jsxs(gt,{children:[e.jsxs(mt,{className:"flex items-center gap-2","data-testid":"document-error-modal-title",children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Document Upload Policy Violation"]}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-gray-700",children:"The following file(s) could not be uploaded due to policy violations:"}),e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:t.errors.map((r,n)=>e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3","data-testid":`document-error-${n}`,children:[e.jsx("p",{className:"font-medium text-red-900 text-sm",children:r.fileName}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:r.reason})]},n))}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-sm text-blue-800 font-semibold mb-1",children:"Document Policy:"}),e.jsxs("ul",{className:"text-xs text-blue-700 space-y-1 list-disc list-inside",children:[e.jsxs("li",{children:["Maximum file size: ",s.maxFileSizeMB,"MB"]}),e.jsxs("li",{children:["Allowed file types:"," ",s.allowedFileTypes.join(", ")]})]})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:a,className:"w-full sm:w-auto","data-testid":"document-error-modal-ok-button",children:"OK"})})]})})}function ju({onBack:t,onSubmit:s,requestId:a,isEditMode:r=!1}){const n=Ea(),i=Ks(),l=n.requestId||a||"",o=r&&!!l,{user:c}=Kt(),[d,m]=p.useState([]);p.useEffect(()=>{(async()=>{try{const rt=(await Mi()).map(ut=>({id:ut.id,name:ut.name,description:ut.description,category:ut.category,icon:Re,estimatedTime:ut.estimatedTime,commonApprovers:ut.approvers.map(nt=>nt.name),workflowApprovers:ut.approvers,suggestedSLA:ut.suggestedSLA,priority:ut.priority,fields:ut.fields||{}}));m(rt)}catch(_e){console.error("Failed to fetch admin templates:",_e)}})()},[]);const h=p.useMemo(()=>[...fu,...d],[d]),{formData:x,updateFormData:u,selectedTemplate:g,setSelectedTemplate:b,loadingDraft:f,systemPolicy:y,documentPolicy:v,existingDocuments:w,setExistingDocuments:C}=oS(o,l,h),{currentStep:k,totalSteps:S,stepNames:_,isStepValid:D,nextStep:A,prevStep:N}=cS(o,g,x),[P,R]=p.useState([]),[O,F]=p.useState([]),$=p.useRef(null),{validationModal:V,policyViolationModal:T,documentErrorModal:j,openValidationModal:U,closeValidationModal:I,openPolicyViolationModal:M,closePolicyViolationModal:W,openDocumentErrorModal:G,closeDocumentErrorModal:ce}=dS(),{submitting:te,savingDraft:L,handleSubmit:z,handleSaveDraft:H}=pS({formData:x,selectedTemplate:g,documents:P,documentsToDelete:O,user:c,isEditing:o,editRequestId:l,onSubmit:s}),{showTemplateModal:ye,setShowTemplateModal:ae,previewDocument:me,selectTemplate:Q,handleTemplateSelection:oe,nextStep:Ce,prevStep:Ee,handlePreviewDocument:be,closePreview:q}=CS({selectedTemplate:g,setSelectedTemplate:b,updateFormData:u,formData:x,currentStep:k,isStepValid:D,wizardNextStep:A,wizardPrevStep:N,user:c,openValidationModal:U,systemPolicy:y,onPolicyViolation:M,onSubmit:s}),ue=p.useCallback(()=>{if(k===1){i("/dashboard",{replace:!0});return}k===3||k===4?t?t():window.history.length>1?window.history.back():i("/dashboard",{replace:!0}):Ee()},[k,t,i,Ee]),Ae=p.useRef(!0),Ue=p.useRef(!1);p.useEffect(()=>{Ae.current&&x.documents&&x.documents.length>0&&!Ue.current&&(R(x.documents),Ue.current=!0),Ae.current=!1},[x.documents]);const Z=p.useRef(!1),Te=p.useRef(P);p.useEffect(()=>{if(Z.current){Z.current=!1,Te.current=P;return}Te.current!==P&&(u("documents",P),Te.current=P)},[P]);const Xe=()=>{switch(k){case 1:return e.jsx(kS,{templates:fu,selectedTemplate:g,onSelectTemplate:Q,adminTemplates:d});case 2:return e.jsx(DS,{formData:x,selectedTemplate:g,updateFormData:u});case 3:return e.jsx(PS,{formData:x,updateFormData:u,systemPolicy:y,onValidationError:pe=>U(pe.type,pe.email,pe.message),onPolicyViolation:M});case 4:return e.jsx(IS,{formData:x,updateFormData:u,onValidationError:pe=>U(pe.type,pe.email,pe.message),initiatorEmail:(c==null?void 0:c.email)||""});case 5:return e.jsx(ES,{documentPolicy:v,isEditing:o,documents:P,existingDocuments:w,documentsToDelete:O,onDocumentsChange:R,onExistingDocumentsChange:C,onDocumentsToDeleteChange:F,onPreviewDocument:be,onDocumentErrors:pe=>G(pe),fileInputRef:$});case 6:return e.jsx(_S,{formData:x,selectedTemplate:g});default:return null}};return f?e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center","data-testid":"create-request-loading",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-600",children:"Loading draft..."})]})}):e.jsxs("div",{className:"h-full flex flex-col bg-gradient-to-br from-gray-50 to-white","data-testid":"create-request",children:[e.jsx(LS,{isEditing:o,currentStep:k,totalSteps:S,stepNames:_,onBack:ue}),e.jsx(Rp,{currentStep:k,totalSteps:S,stepNames:_}),e.jsx(MS,{children:Xe()}),e.jsx(TS,{currentStep:k,totalSteps:S,isStepValid:D(),onPrev:Ee,onNext:Ce,onSubmit:z,onSaveDraft:H,submitting:te,savingDraft:L,loadingDraft:f,isEditing:o}),e.jsx(K2,{open:ye,onClose:()=>ae(!1),onSelectTemplate:oe}),me&&e.jsx(jr,{fileName:me.fileName,fileType:me.fileType,fileUrl:me.fileUrl,fileSize:me.fileSize,open:!!me,onClose:q,onDownload:async()=>{if(me.file){const pe=document.createElement("a");pe.href=me.fileUrl,pe.download=me.fileName,document.body.appendChild(pe),pe.click(),document.body.removeChild(pe)}else me.documentId&&await ps(me.documentId)},attachmentId:me.documentId}),e.jsx($S,{modal:V,onClose:I}),e.jsx(OS,{modal:j,documentPolicy:v,onClose:ce}),e.jsx(Fn,{open:T.open,onClose:W,violations:T.violations,policyDetails:{maxApprovalLevels:y.maxApprovalLevels,maxParticipants:y.maxParticipants,allowSpectators:y.allowSpectators,maxSpectators:y.maxSpectators}})]})}function $i({className:t,...s}){return e.jsx(pf,{"data-slot":"tabs",className:ke("flex flex-col gap-2",t),...s})}function Oi({className:t,...s}){return e.jsx(gf,{"data-slot":"tabs-list",className:ke("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",t),...s})}function qt({className:t,...s}){return e.jsx(ff,{"data-slot":"tabs-trigger",className:ke("data-[state=active]:bg-card dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-xl border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}function es({className:t,...s}){return e.jsx(bf,{"data-slot":"tabs-content",className:ke("flex-1 outline-none",t),...s})}function hc(t,s=[],a){const[r,n]=p.useState(null),[i,l]=p.useState(!1),[o,c]=p.useState(!0),[d,m]=p.useState(null),[h,x]=p.useState(null),[u,g]=p.useState(!1),b=(k,S)=>(k||S||"NA").toString().split(" ").map(D=>D[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),f=k=>{const S=(k||"").toUpperCase();return S==="IN_PROGRESS"?"in-review":S==="PENDING"?"pending":S==="APPROVED"?"approved":S==="REJECTED"?"rejected":S==="CLOSED"?"closed":S==="SKIPPED"?"skipped":(k||"").toLowerCase()},y=p.useCallback(async()=>{var k,S,_,D,A,N,P,R,O,F,$,V,T;l(!0);try{const j=await ks.getWorkflowDetails(t);if(!j){console.warn("[useRequestDetails] No details returned from API");return}const U=j.workflow||{},I=Array.isArray(j.approvals)?j.approvals:[],M=Array.isArray(j.participants)?j.participants:[],W=Array.isArray(j.documents)?j.documents:[],G=j.summary||{},ce=Array.isArray(j.tatAlerts)?j.tatAlerts:[];ce.length>0;const te=(G==null?void 0:G.currentLevel)||U.currentLevel||1,L=I.map(Z=>{const Te=Z.levelNumber||0,Xe=(Z.status||"").toString().toUpperCase(),pe=Z.levelId||Z.level_id;let _e=f(Z.status);Te>te&&Xe!=="APPROVED"&&Xe!=="REJECTED"?_e="waiting":Te===te&&Xe==="PENDING"&&(_e="pending");const rt=ce.filter(ut=>ut.levelId===pe);return{step:Te,levelId:pe,role:Z.levelName||Z.approverName||"Approver",status:_e,approver:Z.approverName||Z.approverEmail,approverId:Z.approverId||Z.approver_id,approverEmail:Z.approverEmail,tatHours:Number(Z.tatHours||0),elapsedHours:Number(Z.elapsedHours||0),remainingHours:Number(Z.remainingHours||0),tatPercentageUsed:Number(Z.tatPercentageUsed||0),actualHours:Z.levelEndTime&&Z.levelStartTime?Math.max(0,(new Date(Z.levelEndTime).getTime()-new Date(Z.levelStartTime).getTime())/(1e3*60*60)):void 0,comment:Z.comments||void 0,timestamp:Z.actionDate||void 0,levelStartTime:Z.levelStartTime||Z.tatStartTime,tatAlerts:rt,skipReason:Z.skipReason||void 0,isSkipped:Xe==="SKIPPED"||Z.isSkipped||!1}}),z=M.filter(Z=>(Z.participantType||Z.participant_type||"").toUpperCase()==="SPECTATOR").map(Z=>({name:Z.userName||Z.user_name||Z.userEmail||Z.user_email,role:"Spectator",email:Z.userEmail||Z.user_email,avatar:b(Z.userName||Z.user_name,Z.userEmail||Z.user_email)})),H=Z=>{var Xe,pe;if(!Z)return;const Te=M.find(_e=>_e.userId===Z||_e.user_id===Z);return Te!=null&&Te.userName||Te!=null&&Te.user_name?Te.userName||Te.user_name:U.initiatorId===Z?((Xe=U.initiator)==null?void 0:Xe.displayName)||((pe=U.initiator)==null?void 0:pe.email):Z},ye=W.map(Z=>{const Te=Number(Z.fileSize||Z.file_size||0),Xe=(Te/(1024*1024)).toFixed(2)+" MB";return{documentId:Z.documentId||Z.document_id,name:Z.originalFileName||Z.fileName||Z.file_name,fileType:Z.fileType||Z.file_type||"",size:Xe,sizeBytes:Te,uploadedBy:H(Z.uploadedBy||Z.uploaded_by),uploadedAt:Z.uploadedAt||Z.uploaded_at}}),ae=Array.isArray(j.activities)?j.activities.filter(Z=>(Z.type||"").toLowerCase()!=="sla_warning"):[];let me=null;if(U.isPaused||!1)try{me=await Zd(U.requestId)}catch{}let oe=null,Ce=null,Ee=null,be=null;if(U.workflowType==="CLAIM_MANAGEMENT"||U.templateType==="claim-management")try{const Z=await je.get(`/dealer-claims/${U.requestId}`),Te=((k=Z.data)==null?void 0:k.data)||Z.data;if(Te){oe=Te.claimDetails||Te.claim_details,Ce=Te.proposalDetails||Te.proposal_details,Ee=Te.completionDetails||Te.completion_details,be=Te.internalOrder||Te.internal_order||null;const Xe=Te.budgetTracking||Te.budget_tracking||null,pe=Te.invoice||null,_e=Te.creditNote||Te.credit_note||null,rt=Te.completionExpenses||Te.completion_expenses||null;oe&&(oe.budgetTracking=Xe,oe.invoice=pe,oe.creditNote=_e,oe.completionExpenses=rt)}else console.warn("[useRequestDetails] No claimData found in response")}catch(Z){console.error("[useRequestDetails] Error fetching claim details:",{error:(Z==null?void 0:Z.message)||Z,status:(S=Z==null?void 0:Z.response)==null?void 0:S.status,statusText:(_=Z==null?void 0:Z.response)==null?void 0:_.statusText,responseData:(D=Z==null?void 0:Z.response)==null?void 0:D.data,requestId:U.requestId})}const q={...U,id:U.requestNumber||U.requestId,requestId:U.requestId,requestNumber:U.requestNumber,title:U.title,description:U.description,status:f(U.status),priority:(U.priority||"").toString().toLowerCase(),workflowType:U.workflowType||(U.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),approvalFlow:L,approvals:I,participants:M,documents:ye,spectators:z,summary:G,sla:(G==null?void 0:G.sla)||U.sla||null,initiator:{name:((A=U.initiator)==null?void 0:A.displayName)||((N=U.initiator)==null?void 0:N.email),role:((P=U.initiator)==null?void 0:P.designation)||void 0,department:((R=U.initiator)==null?void 0:R.department)||void 0,email:((O=U.initiator)==null?void 0:O.email)||void 0,phone:((F=U.initiator)==null?void 0:F.phone)||void 0,avatar:b(($=U.initiator)==null?void 0:$.displayName,(V=U.initiator)==null?void 0:V.email)},createdAt:U.createdAt,updatedAt:U.updatedAt,totalSteps:U.totalLevels||1,currentStepRaw:(G==null?void 0:G.currentLevel)||U.currentLevel||1,currentStep:Math.min(Math.max(1,(G==null?void 0:G.currentLevel)||U.currentLevel||1),U.totalLevels||1),auditTrail:ae,conclusionRemark:U.conclusionRemark||null,closureDate:U.closureDate||null,pauseInfo:me||null,claimDetails:oe||null,proposalDetails:Ce||null,completionDetails:Ee||null,internalOrder:be||null,budgetTracking:(oe==null?void 0:oe.budgetTracking)||null,invoice:(oe==null?void 0:oe.invoice)||null,creditNote:(oe==null?void 0:oe.creditNote)||null,completionExpenses:(oe==null?void 0:oe.completionExpenses)||null};n(q);const ue=(T=a==null?void 0:a.email)==null?void 0:T.toLowerCase(),Ae=I.find(Z=>{const Te=(Z.status||"").toString().toUpperCase(),Xe=(Z.approverEmail||"").toLowerCase(),pe=Z.levelNumber||0;return(Te==="PENDING"||Te==="IN_PROGRESS"||Te==="PAUSED")&&Xe===ue&&pe===te});x(Ae||null);const Ue=a==null?void 0:a.userId;if(Ue){const Z=M.some(Te=>(Te.participantType||Te.participant_type||"").toUpperCase()==="SPECTATOR"&&(Te.userId||Te.user_id)===Ue);g(Z)}else g(!1)}catch(j){console.error("[useRequestDetails] Error refreshing details:",j),alert("Failed to refresh request details. Please try again.")}finally{l(!1)}},[t,a]);p.useEffect(()=>{if(!t){c(!1);return}let k=!0;return c(!0),m(null),(async()=>{var S,_,D,A,N,P,R,O,F,$,V,T,j,U;try{const I=await ks.getWorkflowDetails(t);if(!k||!I){k&&c(!1);return}const M=I.workflow||{},W=Array.isArray(I.approvals)?I.approvals:[],G=Array.isArray(I.participants)?I.participants:[],ce=Array.isArray(I.documents)?I.documents:[],te=I.summary||{},L=Array.isArray(I.tatAlerts)?I.tatAlerts:[],z=(M.priority||"").toString().toLowerCase(),H=(te==null?void 0:te.currentLevel)||M.currentLevel||1,ye=W.map(pe=>{const _e=pe.levelNumber||0,rt=(pe.status||"").toString().toUpperCase(),ut=pe.levelId||pe.level_id;let nt=f(pe.status);rt==="PAUSED"?nt="paused":_e>H&&rt!=="APPROVED"&&rt!=="REJECTED"?nt="waiting":_e===H&&(rt==="PENDING"||rt==="IN_PROGRESS")&&(nt=rt==="IN_PROGRESS"?"in-review":"pending");const Ps=L.filter(Xs=>Xs.levelId===ut);return{step:_e,levelId:ut,role:pe.levelName||pe.approverName||"Approver",status:nt,approver:pe.approverName||pe.approverEmail,approverId:pe.approverId||pe.approver_id,approverEmail:pe.approverEmail,tatHours:Number(pe.tatHours||0),elapsedHours:Number(pe.elapsedHours||0),remainingHours:Number(pe.remainingHours||0),tatPercentageUsed:Number(pe.tatPercentageUsed||0),actualHours:pe.elapsedHours!==void 0&&pe.elapsedHours!==null?Number(pe.elapsedHours):void 0,comment:pe.comments||void 0,timestamp:pe.actionDate||void 0,levelStartTime:pe.levelStartTime||pe.tatStartTime,tatAlerts:Ps}}),ae=G.filter(pe=>(pe.participantType||"").toUpperCase()==="SPECTATOR").map(pe=>({name:pe.userName||pe.userEmail,role:"Spectator",avatar:b(pe.userName,pe.userEmail)})),me=pe=>{var rt,ut;if(!pe)return;const _e=G.find(nt=>nt.userId===pe);return _e!=null&&_e.userName?_e.userName:M.initiatorId===pe?((rt=M.initiator)==null?void 0:rt.displayName)||((ut=M.initiator)==null?void 0:ut.email):pe},Q=ce.map(pe=>{const _e=Number(pe.fileSize||0),rt=(_e/(1024*1024)).toFixed(2)+" MB";return{documentId:pe.documentId||pe.document_id,name:pe.originalFileName||pe.fileName,fileType:pe.fileType||pe.file_type||"",size:rt,sizeBytes:_e,uploadedBy:me(pe.uploadedBy),uploadedAt:pe.uploadedAt}}),oe=Array.isArray(I.activities)?I.activities.filter(pe=>(pe.type||"").toLowerCase()!=="sla_warning"):[];let Ce=null;if(M.isPaused||!1)try{Ce=await Zd(M.requestId)}catch{}let be=null,q=null,ue=null,Ae=null;if(M.workflowType==="CLAIM_MANAGEMENT"||M.templateType==="claim-management")try{const pe=await je.get(`/dealer-claims/${M.requestId}`),_e=((S=pe.data)==null?void 0:S.data)||pe.data;if(_e){be=_e.claimDetails||_e.claim_details,q=_e.proposalDetails||_e.proposal_details,ue=_e.completionDetails||_e.completion_details,Ae=_e.internalOrder||_e.internal_order||null;const rt=_e.budgetTracking||_e.budget_tracking||null,ut=_e.invoice||null,nt=_e.creditNote||_e.credit_note||null,Ps=_e.completionExpenses||_e.completion_expenses||null;be&&(be.budgetTracking=rt,be.invoice=ut,be.creditNote=nt,be.completionExpenses=Ps)}}catch(pe){console.error("[useRequestDetails] Initial load - Error fetching claim details:",{error:(pe==null?void 0:pe.message)||pe,status:(_=pe==null?void 0:pe.response)==null?void 0:_.status,requestId:M.requestId})}const Ue={id:M.requestNumber||M.requestId,requestId:M.requestId,title:M.title,description:M.description,priority:z,status:f(M.status),workflowType:M.workflowType||(M.templateType==="claim-management"?"CLAIM_MANAGEMENT":"NON_TEMPLATIZED"),summary:te,initiator:{name:((D=M.initiator)==null?void 0:D.displayName)||((A=M.initiator)==null?void 0:A.email),role:((N=M.initiator)==null?void 0:N.designation)||void 0,department:((P=M.initiator)==null?void 0:P.department)||void 0,email:((R=M.initiator)==null?void 0:R.email)||void 0,phone:((O=M.initiator)==null?void 0:O.phone)||void 0,avatar:b((F=M.initiator)==null?void 0:F.displayName,($=M.initiator)==null?void 0:$.email)},createdAt:M.createdAt,updatedAt:M.updatedAt,totalSteps:M.totalLevels||1,currentStepRaw:(te==null?void 0:te.currentLevel)||M.currentLevel||1,currentStep:Math.min(Math.max(1,(te==null?void 0:te.currentLevel)||M.currentLevel||1),M.totalLevels||1),approvalFlow:ye,approvals:W,documents:Q,spectators:ae,auditTrail:oe,conclusionRemark:M.conclusionRemark||null,closureDate:M.closureDate||null,pauseInfo:Ce||null,claimDetails:be||null,proposalDetails:q||null,completionDetails:ue||null,internalOrder:Ae||null,budgetTracking:(be==null?void 0:be.budgetTracking)||null,invoice:(be==null?void 0:be.invoice)||null,creditNote:(be==null?void 0:be.creditNote)||null,completionExpenses:(be==null?void 0:be.completionExpenses)||null};n(Ue);const Z=(V=a==null?void 0:a.email)==null?void 0:V.toLowerCase(),Te=W.find(pe=>{const _e=(pe.status||"").toString().toUpperCase(),rt=(pe.approverEmail||"").toLowerCase(),ut=pe.levelNumber||0;return(_e==="PENDING"||_e==="IN_PROGRESS"||_e==="PAUSED")&&rt===Z&&ut===H});x(Te||null);const Xe=a==null?void 0:a.userId;if(Xe){const pe=G.some(_e=>(_e.participantType||"").toUpperCase()==="SPECTATOR"&&_e.userId===Xe);g(pe)}else g(!1)}catch(I){if(console.error("[useRequestDetails] Error loading request details:",I),k){if(((T=I==null?void 0:I.response)==null?void 0:T.status)===403){const M=((U=(j=I==null?void 0:I.response)==null?void 0:j.data)==null?void 0:U.message)||"You do not have permission to view this request. Access is restricted to the initiator, approvers, and spectators of this request.";m({denied:!0,message:M})}n(null)}}finally{k&&c(!1)}})(),()=>{k=!1}},[t,a]);const v=p.useMemo(()=>{if(r)return r;const k=s.find(S=>S.id===t||S.requestNumber===t||S.request_number===t);return k||null},[t,s,r]),w=p.useMemo(()=>{var _,D,A;if(!v||!a)return!1;const k=(_=a==null?void 0:a.email)==null?void 0:_.toLowerCase(),S=(A=(D=v.initiator)==null?void 0:D.email)==null?void 0:A.toLowerCase();return k===S},[v,a]),C=p.useMemo(()=>{var S;if(!v)return[];const k=[];return(S=v.initiator)!=null&&S.email&&k.push({email:v.initiator.email.toLowerCase(),participantType:"INITIATOR",name:v.initiator.name}),v.approvalFlow&&Array.isArray(v.approvalFlow)&&v.approvalFlow.forEach(_=>{_.approverEmail&&k.push({email:_.approverEmail.toLowerCase(),participantType:"APPROVER",name:_.approver})}),v.spectators&&Array.isArray(v.spectators)&&v.spectators.forEach(_=>{_.email&&k.push({email:_.email.toLowerCase(),participantType:"SPECTATOR",name:_.name})}),v.participants&&Array.isArray(v.participants)&&v.participants.forEach(_=>{const D=(_.userEmail||_.email||"").toLowerCase(),A=(_.participantType||_.participant_type||"").toUpperCase(),N=_.userName||_.user_name||_.name;D&&A&&!k.find(P=>P.email===D)&&k.push({email:D,participantType:A,name:N})}),k},[v]);return p.useEffect(()=>{if(!t||!r)return;const k=Lr();if(!k)return;const S=_=>{((_==null?void 0:_.requestId)===r.requestId||(_==null?void 0:_.requestNumber)===t)&&y()};return k.on("request:updated",S),()=>{k.off("request:updated",S)}},[t,r,y]),{request:v,apiRequest:r,loading:o,refreshing:i,refreshDetails:y,currentApprovalLevel:h,isSpectator:u,isInitiator:w,existingParticipants:C,accessDenied:d}}function Ip(t,s,a,r){const[n,i]=p.useState([]),[l,o]=p.useState(0),[c,d]=p.useState([]);return p.useEffect(()=>{if(!t){console.warn("[useRequestSocket] No requestIdentifier, cannot join socket room");return}let m=!0,h=t;return(async()=>{var b;try{const f=await ks.getWorkflowDetails(t);(b=f==null?void 0:f.workflow)!=null&&b.requestId&&m&&(h=f.workflow.requestId)}catch(f){console.error("[useRequestSocket] Failed to resolve UUID:",f)}if(!m)return;const x=Lr();if(!x){console.error("[useRequestSocket] Socket not available");return}const u=r==null?void 0:r.userId,g=()=>{Ml(x,h,u)};return x.connected?g():x.on("connect",g),()=>{m&&(x.off("connect",g),Ax(x,h))}})(),()=>{m=!1}},[t,r]),p.useEffect(()=>{!t||!s||(async()=>{try{const m=await Fr(t),h=s.auditTrail||[],x=[...m,...h];x.sort((u,g)=>{const b=new Date(u.createdAt||u.created_at||u.timestamp||0).getTime(),f=new Date(g.createdAt||g.created_at||g.timestamp||0).getTime();return b-f}),i(x)}catch(m){console.error("[useRequestSocket] Failed to fetch and merge messages:",m)}})()},[t,s]),p.useEffect(()=>{if(!t)return;const m=Lr();if(!m)return;const h=u=>{a!=="worknotes"&&o(g=>g+1),(async()=>{try{const g=await Fr(t),b=(s==null?void 0:s.auditTrail)||[],f=[...g,...b].sort((y,v)=>{const w=new Date(y.createdAt||y.created_at||y.timestamp||0).getTime(),C=new Date(v.createdAt||v.created_at||v.timestamp||0).getTime();return w-C});i(f)}catch(g){console.error("[useRequestSocket] Failed to refresh messages:",g)}})()},x=u=>{const g=u.type==="breach"?"โฐ":u.type==="threshold2"?"โš ๏ธ":"โณ";(async()=>{try{const b=await ks.getWorkflowDetails(t);b&&(Array.isArray(b.tatAlerts)&&b.tatAlerts,"Notification"in window&&Notification.permission==="granted"&&new Notification(`${g} TAT Alert`,{body:u.message,icon:"/favicon.ico",tag:`tat-${u.requestId}-${u.type}`,requireInteraction:!1}))}catch(b){console.error("[useRequestSocket] Failed to refresh after TAT alert:",b)}})()};return m.on("noteHandler",h),m.on("worknote:new",h),m.on("tat:alert",x),()=>{m.off("noteHandler",h),m.off("worknote:new",h),m.off("tat:alert",x)}},[t,a,s]),p.useEffect(()=>{a==="worknotes"&&o(0)},[a]),{mergedMessages:n,unreadWorkNotes:l,workNoteAttachments:c,setWorkNoteAttachments:d}}async function nn(t,s,a="SUPPORTING"){var l;const r=new FormData;r.append("file",t),r.append("requestId",s),r.append("category",a);const n=await je.post("/documents",r,{headers:{"Content-Type":"multipart/form-data"}}),i=((l=n.data)==null?void 0:l.data)||n.data;return{documentId:(i==null?void 0:i.documentId)||(i==null?void 0:i.document_id)||"",storageUrl:(i==null?void 0:i.storageUrl)||(i==null?void 0:i.storage_url),fileName:(i==null?void 0:i.fileName)||(i==null?void 0:i.file_name)||t.name,originalFileName:(i==null?void 0:i.originalFileName)||(i==null?void 0:i.original_file_name)||t.name}}function Ep(t,s){const[a,r]=p.useState(!1),[n,i]=p.useState(null),[l,o]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[c,d]=p.useState({show:!1,errors:[]});p.useEffect(()=>{(async()=>{try{const g=await Ys("DOCUMENT_POLICY"),b={};g.forEach(w=>{b[w.configKey]=w.configValue});const f=parseInt(b.MAX_FILE_SIZE_MB||"10"),v=(b.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(w=>w.trim().toLowerCase());o({maxFileSizeMB:f,allowedFileTypes:v})}catch(g){console.error("Failed to load document policy:",g)}})()},[]);const m=u=>{const g=l.maxFileSizeMB*1024*1024;if(u.size>g)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${l.maxFileSizeMB}MB. Current size: ${(u.size/(1024*1024)).toFixed(2)}MB`};const b=u.name.toLowerCase(),f=b.substring(b.lastIndexOf(".")+1);return l.allowedFileTypes.includes(f)?{valid:!0}:{valid:!1,reason:`File type "${f}" is not allowed. Allowed types: ${l.allowedFileTypes.join(", ")}`}},h=async u=>{var v,w;const g=u.target.files;if(!g||g.length===0)return;const b=Array.from(g),f=[],y=[];if(b.forEach(C=>{const k=m(C);k.valid?y.push(C):f.push({fileName:C.name,reason:k.reason||"Unknown validation error"})}),f.length>0&&d({show:!0,errors:f}),y.length===0){u.target&&(u.target.value="");return}r(!0);try{const C=y[0],k=t==null?void 0:t.requestId;if(!k){K.error("Request ID not found");return}C&&await nn(C,k,"SUPPORTING"),await s(),y.length{const u=document.createElement("input");u.type="file",u.accept=l.allowedFileTypes.map(g=>`.${g}`).join(","),u.onchange=h,u.click()},previewDocument:n,setPreviewDocument:i,documentPolicy:l,documentError:c,setDocumentError:d}}const US="modulepreload",BS=function(t){return"/"+t},Nu={},jl=function(s,a,r){let n=Promise.resolve();if(a&&a.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));n=Promise.allSettled(a.map(c=>{if(c=BS(c),c in Nu)return;Nu[c]=!0;const d=c.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${m}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":US,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((x,u)=>{h.addEventListener("load",x),h.addEventListener("error",()=>u(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return n.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};function Fp(t,s,a,r,n,i,l){const[o,c]=p.useState(""),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(!1),[b,f]=p.useState(0),[y,v]=p.useState(!1),[w,C]=p.useState(!1),[k,S]=p.useState(0),_=async()=>{var R;const N=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),P=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);if(N||P){c(N||P),g(!!P);return}try{const{getConclusion:O}=await jl(async()=>{const{getConclusion:$}=await import("./conclusionApi-C_Bd1V1u.js");return{getConclusion:$}},__vite__mapDeps([0,1,2,3,4,5,6,7])),F=await O(t.requestId||s);F&&(F.aiGeneratedRemark||F.finalRemark)&&(c(F.finalRemark||F.aiGeneratedRemark||""),g(!!F.aiGeneratedRemark))}catch(O){((R=O==null?void 0:O.response)==null?void 0:R.status)!==404&&console.error("[useConclusionRemark] Error fetching conclusion:",O)}},D=async()=>{if(!w)try{m(!0),v(!1);const{generateConclusion:N}=await jl(async()=>{const{generateConclusion:F}=await import("./conclusionApi-C_Bd1V1u.js");return{generateConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7])),P=await N(t.requestId||s),R=b+1;if(f(R),!(P!=null&&P.aiGeneratedRemark)||P.aiGeneratedRemark.toLowerCase().includes("unable to generate")||P.aiGeneratedRemark.toLowerCase().includes("sorry")){const F=k+1;S(F),F>=2?(C(!0),i==null||i({success:!1,title:"AI Generation Limit Reached",message:"We're unable to process a conclusion remark at this time after 2 attempts. Please proceed with a manual approach using the editor below."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process a conclusion remark at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0),c((P==null?void 0:P.aiGeneratedRemark)||""),g(!1);return}c(P.aiGeneratedRemark),g(!0),S(0),R>=2&&(C(!0),i==null||i({success:!0,title:"Maximum Attempts Reached",message:"You've reached the maximum of 2 regeneration attempts. Feel free to manually edit the current suggestion to fit your specific needs."}),l==null||l(!0))}catch(N){console.error("[useConclusionRemark] AI generation failed:",N);const P=k+1;S(P),g(!1),P>=2?(C(!0),i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. Since the maximum of 2 attempts is reached, please proceed with a manual approach."})):i==null||i({success:!1,title:"System Note",message:"We're unable to process your request at the moment. You have one more attempt remaining, or you can proceed manually."}),l==null||l(!0)}finally{m(!1)}},A=async()=>{var P,R;const N=o.replace(/<[^>]*>/g,"").trim();if(!N){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark cannot be empty"}),l==null||l(!0);return}if(N.length>2e3){i==null||i({success:!1,title:"Validation Error",message:"Conclusion remark exceeds 2000 characters limit"}),l==null||l(!0);return}try{x(!0);const{finalizeConclusion:O}=await jl(async()=>{const{finalizeConclusion:F}=await import("./conclusionApi-C_Bd1V1u.js");return{finalizeConclusion:F}},__vite__mapDeps([0,1,2,3,4,5,6,7]));await O(t.requestId||s,o),i==null||i({success:!0,title:"Request Closed with Successful Completion",message:"The request has been finalized and moved to Closed Requests."}),l==null||l(!0),await r(),setTimeout(()=>{n?(n(),setTimeout(()=>{window.location.hash="#/closed-requests"},100)):window.location.hash="#/closed-requests"},2e3)}catch(O){i==null||i({success:!1,title:"Error",message:((R=(P=O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to finalize conclusion"}),l==null||l(!0)}finally{x(!1)}};return p.useEffect(()=>{var F;const N=(F=t==null?void 0:t.status)==null?void 0:F.toLowerCase();if(!((N==="approved"||N==="rejected"||N==="closed")&&a&&!o))return;const R=(t==null?void 0:t.conclusionRemark)||(t==null?void 0:t.conclusion_remark),O=(t==null?void 0:t.aiGeneratedConclusion)||(t==null?void 0:t.ai_generated_conclusion);R||O?(c(R||O),g(!!O)):_()},[t==null?void 0:t.status,t==null?void 0:t.conclusionRemark,t==null?void 0:t.aiGeneratedConclusion,a,o]),{conclusionRemark:o,setConclusionRemark:c,conclusionLoading:d,conclusionSubmitting:h,aiGenerated:u,handleGenerateConclusion:D,handleFinalizeConclusion:A,generationAttempts:b,generationFailed:y,maxAttemptsReached:w}}function _p(t,s,a){const[r,n]=p.useState(!1),[i,l]=p.useState(!1),[o,c]=p.useState(!1),[d,m]=p.useState(!1),[h,x]=p.useState(!1),[u,g]=p.useState(!1),[b,f]=p.useState(null),[y,v]=p.useState(null);return{showApproveModal:r,setShowApproveModal:n,showRejectModal:i,setShowRejectModal:l,showAddApproverModal:o,setShowAddApproverModal:c,showAddSpectatorModal:d,setShowAddSpectatorModal:m,showSkipApproverModal:h,setShowSkipApproverModal:x,showActionStatusModal:u,setShowActionStatusModal:g,skipApproverData:b,setSkipApproverData:f,actionStatus:y,setActionStatus:v,handleApproveConfirm:async D=>{var N,P;const A=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!A){alert("Approval level not found");return}await an(t,A,D||""),await new Promise(R=>setTimeout(R,500)),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Approved successfully")},handleRejectConfirm:async D=>{var N,P;if(!(D!=null&&D.trim())){alert("Comments & remarks are required");return}const A=(s==null?void 0:s.levelId)||(s==null?void 0:s.level_id);if(!A){alert("Approval level not found");return}await Sr(t,A,D.trim(),D.trim()),await a(),(N=window==null?void 0:window.closeModal)==null||N.call(window),(P=window==null?void 0:window.toast)==null||P.call(window,"Rejected successfully")},handleAddApprover:async(D,A,N)=>{var P,R;try{await Vx(t,D,A,N),await a(),c(!1),v==null||v({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${N} with ${A}h TAT`}),g==null||g(!0)}catch(O){throw v==null||v({success:!1,title:"Failed to Add Approver",message:((R=(P=O==null?void 0:O.response)==null?void 0:P.data)==null?void 0:R.error)||"Failed to add approver. Please try again."}),g==null||g(!0),O}},handleSkipApprover:async D=>{var A,N;if(b)try{await Zj(t,b.levelId,D),await a(),x(!1),f(null),v==null||v({success:!0,title:"Approver Skipped",message:"Approver skipped successfully. The workflow has moved to the next level."}),g==null||g(!0)}catch(P){throw v==null||v({success:!1,title:"Failed to Skip Approver",message:((N=(A=P==null?void 0:P.response)==null?void 0:A.data)==null?void 0:N.error)||"Failed to skip approver. Please try again."}),g==null||g(!0),P}},handleAddSpectator:async D=>{var A,N;try{await zx(t,D),await a(),m(!1),v==null||v({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),g==null||g(!0)}catch(P){throw v==null||v({success:!1,title:"Failed to Add Spectator",message:((N=(A=P==null?void 0:P.response)==null?void 0:A.data)==null?void 0:N.error)||"Failed to add spectator. Please try again."}),g==null||g(!0),P}}}}const VS=t=>{const s=(t||"").toLowerCase();return s.includes("image")||s.includes("pdf")||s.includes("jpg")||s.includes("jpeg")||s.includes("png")||s.includes("gif")};function Or({document:t,onPreview:s,onDownload:a,showPreview:r=!0,testId:n="document-card"}){return e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors","data-testid":`${n}-${t.documentId}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-blue-100 rounded-lg",children:e.jsx(Re,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-gray-900","data-testid":`${n}-name`,children:t.name}),e.jsxs("p",{className:"text-xs text-gray-500","data-testid":`${n}-metadata`,children:[t.size&&e.jsxs("span",{children:[t.size," โ€ข "]}),t.uploadedBy&&e.jsxs("span",{children:["Uploaded by ",t.uploadedBy," on "]}),Qt(t.uploadedAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&VS(t.fileType)&&s&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>s({fileName:t.name,fileType:t.fileType,documentId:t.documentId,fileSize:t.sizeBytes}),title:"Preview file","data-testid":`${n}-preview-btn`,children:e.jsx(ht,{className:"w-4 h-4"})}),a&&e.jsx(E,{variant:"ghost",size:"sm",onClick:async()=>{if(!t.documentId){alert("Document ID not available");return}try{await a(t.documentId)}catch{alert("Failed to download document")}},title:"Download file","data-testid":`${n}-download-btn`,children:e.jsx(Ct,{className:"w-4 h-4"})})]})]})}function zS({request:t,workNoteAttachments:s,uploadingDocument:a,documentPolicy:r,triggerFileInput:n,setPreviewDocument:i,downloadDocument:l}){return e.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[e.jsxs(ee,{children:[e.jsx(ge,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(Re,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-600"}),"Request Documents"]}),e.jsx($e,{className:"text-xs sm:text-sm mt-1",children:"Documents attached while creating the request"})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsxs(E,{size:"sm",onClick:n,disabled:a||t.status==="closed",className:"gap-1 sm:gap-2 h-8 sm:h-9 text-xs sm:text-sm shrink-0","data-testid":"upload-document-btn",children:[e.jsx(zs,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a?"Uploading...":t.status==="closed"?"Closed":"Upload",e.jsx("span",{className:"hidden sm:inline",children:t.status==="closed"?"":"Document"})]}),e.jsxs("p",{className:"text-xs text-gray-500 whitespace-nowrap",children:["Max ",r.maxFileSizeMB,"MB"]})]})]})}),e.jsx(se,{children:t.documents&&t.documents.length>0?e.jsx("div",{className:"space-y-3",children:t.documents.map((o,c)=>e.jsx(Or,{document:o,onPreview:d=>i(d),onDownload:l,testId:"request-document"},c))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-documents",children:"No documents uploaded yet"})})]}),e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(As,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-600"}),"Work Note Attachments"]}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Files shared in work notes discussions"})]}),e.jsx(se,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3",children:s.map((o,c)=>e.jsx(Or,{document:{documentId:o.attachmentId||"",name:o.name,fileType:o.type||"",size:o.size?`${(o.size/1024).toFixed(1)} KB`:"Unknown size",sizeBytes:o.size,uploadedBy:o.uploadedBy,uploadedAt:o.uploadedAt},onPreview:d=>i(d),onDownload:async d=>{const{downloadWorkNoteAttachment:m}=require("@/services/workflowApi");await m(d)},testId:"worknote-attachment"},o.attachmentId||c))}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-8","data-testid":"no-attachments",children:"No files shared in work notes yet"})})]})]})}const HS=t=>{switch(t){case"express":case"urgent":return{color:"bg-red-100 text-red-800 border-red-200",label:"urgent priority"};case"standard":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"standard priority"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:"normal priority"}}},WS=t=>{switch(t){case"pending":return{color:"bg-yellow-100 text-yellow-800 border-yellow-200",label:"pending"};case"paused":return{color:"bg-gray-400 text-gray-100 border-gray-500",label:"paused"};case"in-review":return{color:"bg-blue-100 text-blue-800 border-blue-200",label:"in-review"};case"approved":return{color:"bg-green-100 text-green-800 border-green-200",label:"approved"};case"rejected":return{color:"bg-red-100 text-red-800 border-red-200",label:"rejected"};case"closed":return{color:"bg-gray-100 text-gray-800 border-gray-300",label:"closed"};case"skipped":return{color:"bg-orange-100 text-orange-800 border-orange-200",label:"skipped"};default:return{color:"bg-gray-100 text-gray-800 border-gray-200",label:t}}},GS=t=>{switch(t){case"approval":case"approved":return e.jsx(De,{className:"w-5 h-5 text-green-600"});case"rejection":case"rejected":return e.jsx(wt,{className:"w-5 h-5 text-red-600"});case"comment":return e.jsx(As,{className:"w-5 h-5 text-blue-600"});case"status_change":case"updated":return e.jsx($t,{className:"w-5 h-5 text-orange-600"});case"assignment":return e.jsx(wi,{className:"w-5 h-5 text-purple-600"});case"created":return e.jsx(Re,{className:"w-5 h-5 text-blue-600"});case"reminder":return e.jsx(st,{className:"w-5 h-5 text-yellow-600"});case"document_added":return e.jsx(vi,{className:"w-5 h-5 text-indigo-600"});case"sla_warning":return e.jsx(as,{className:"w-5 h-5 text-amber-600"});default:return e.jsx(kt,{className:"w-5 h-5 text-gray-600"})}};function YS({request:t}){return e.jsxs(ee,{children:[e.jsxs(ge,{children:[e.jsxs(fe,{className:"flex items-center gap-2 text-sm sm:text-base",children:[e.jsx(kt,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-600"}),"Activity Timeline"]}),e.jsx($e,{className:"text-xs sm:text-sm",children:"Complete audit trail of all request activities"})]}),e.jsx(se,{children:e.jsx("div",{className:"space-y-4 sm:space-y-6",children:t.auditTrail&&t.auditTrail.length>0?t.auditTrail.map((s,a)=>e.jsxs("div",{className:"flex items-start gap-4","data-testid":`activity-item-${a}`,children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center",children:GS(s.type)})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4 shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"font-semibold text-gray-900",children:s.action}),e.jsx("span",{className:"text-xs text-gray-500 whitespace-nowrap ml-4",children:Qt(s.timestamp)})]}),e.jsx("div",{className:"text-sm text-gray-600 leading-relaxed",children:e.jsx("p",{className:"whitespace-pre-line break-words",children:s.details})})]})})]},a)):e.jsxs("div",{className:"text-center py-12","data-testid":"no-activity",children:[e.jsx(kt,{className:"w-12 h-12 text-gray-400 mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-gray-500",children:"No activity recorded yet"}),e.jsx("p",{className:"text-xs text-gray-400 mt-2",children:"Actions and updates will appear here"})]})})})]})}function Lp({open:t,onClose:s,success:a,title:r,message:n}){return e.jsx(pt,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsx(gt,{children:e.jsxs(mt,{className:"flex items-center gap-2",children:[a?e.jsx(De,{className:"w-5 h-5 text-green-600"}):e.jsx(ze,{className:"w-5 h-5 text-red-600"}),r||(a?"Success":"Error")]})}),e.jsx("div",{className:"py-6",children:e.jsx("div",{className:"flex flex-col items-center text-center",children:a?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mb-4",children:e.jsx(De,{className:"w-8 h-8 text-green-600"})}),e.jsx("p",{className:"text-sm text-gray-700",children:n||"Operation completed successfully!"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-red-100 flex items-center justify-center mb-4",children:e.jsx(wt,{className:"w-8 h-8 text-red-600"})}),e.jsx("p",{className:"text-sm text-gray-700",children:n||"Operation failed. Please try again."})]})})}),e.jsx(Tt,{children:e.jsx(E,{onClick:s,className:`w-full ${a?"bg-green-600 hover:bg-green-700":"bg-gray-600 hover:bg-gray-700"}`,children:"OK"})})]})})}function Mp({open:t,onClose:s,onConfirm:a,existingParticipants:r=[]}){const[n,i]=p.useState(""),[l,o]=p.useState(!1),[c,d]=p.useState([]),[m,h]=p.useState(!1),[x,u]=p.useState(null),g=p.useRef(null),b=p.useRef(null),[f,y]=p.useState({open:!1,type:"error",email:"",message:""}),[v,w]=p.useState({open:!1,violations:[]}),[C,k]=p.useState({maxApprovalLevels:10,maxParticipants:50,allowSpectators:!0,maxSpectators:20});p.useEffect(()=>{t&&(async()=>{var P;try{const R=await Ys("WORKFLOW_SHARING"),O=await Ys("TAT_SETTINGS"),F=[...R,...O],$={};F.forEach(V=>{$[V.configKey]=V.configValue}),k({maxApprovalLevels:parseInt($.MAX_APPROVAL_LEVELS||"10"),maxParticipants:parseInt($.MAX_PARTICIPANTS_PER_REQUEST||"50"),allowSpectators:((P=$.ALLOW_ADD_SPECTATOR)==null?void 0:P.toLowerCase())==="true",maxSpectators:parseInt($.MAX_SPECTATORS_PER_REQUEST||"20")})}catch(R){console.error("Failed to load system policy:",R)}})()},[t]);const S=async()=>{var T,j;const N=n.trim().toLowerCase();if(!N){y({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(N)){y({open:!0,type:"error",email:N,message:"Please enter a valid email address"});return}const R=r.find(U=>(U.email||"").toLowerCase()===N);if(R){const U=((T=R.participantType)==null?void 0:T.toUpperCase())||"PARTICIPANT",I=R.name||N;if(U==="INITIATOR"){y({open:!0,type:"error",email:N,message:`${I} is the request initiator and cannot be added as a spectator.`});return}else if(U==="APPROVER"){y({open:!0,type:"error",email:N,message:`${I} is already an approver on this request and cannot be added as a spectator.`});return}else if(U==="SPECTATOR"){y({open:!0,type:"error",email:N,message:`${I} is already a spectator on this request.`});return}else{y({open:!0,type:"error",email:N,message:`${I} is already a participant on this request.`});return}}const O=[];C.allowSpectators||O.push({type:"Spectators Not Allowed",message:"Adding spectators is not allowed by system policy."});const $=r.filter(U=>(U.participantType||"").toUpperCase()==="SPECTATOR").length;$>=C.maxSpectators&&O.push({type:"Maximum Spectators Exceeded",message:"This request has reached the maximum number of spectators allowed.",currentValue:$,maxValue:C.maxSpectators});const V=r.length+1;if(V>C.maxParticipants&&O.push({type:"Maximum Participants Exceeded",message:"Adding this spectator would exceed the maximum participants limit.",currentValue:V,maxValue:C.maxParticipants}),O.length>0){w({open:!0,violations:O});return}if(!x||x.email.toLowerCase()!==N)try{const I=((j=(await ia(N,1)).data)==null?void 0:j.data)||[];if(I.length===0){y({open:!0,type:"not-found",email:N,message:""});return}const M=I[0];await ra({userId:M.userId,email:M.email,displayName:M.displayName,firstName:M.firstName,lastName:M.lastName,department:M.department,phone:M.phone,mobilePhone:M.mobilePhone,designation:M.designation,jobTitle:M.jobTitle,manager:M.manager,employeeId:M.employeeId,employeeNumber:M.employeeNumber,secondEmail:M.secondEmail,location:M.location})}catch(U){console.error("Failed to validate spectator:",U),y({open:!0,type:"error",email:N,message:"Failed to validate user. Please try again."});return}try{o(!0),await a(N),i(""),u(null),s()}catch(U){console.error("Failed to add spectator:",U)}finally{o(!1)}},_=()=>{l||(i(""),u(null),d([]),h(!1),s())};p.useEffect(()=>{c.length>0&&b.current&&b.current.scrollTo({top:b.current.scrollHeight,behavior:"smooth"})},[c.length]),p.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const D=N=>{if(i(N),x&&x.email.toLowerCase()!==N.toLowerCase()&&u(null),g.current&&clearTimeout(g.current),!N||!N.startsWith("@")||N.length<2){d([]),h(!1);return}h(!0),g.current=setTimeout(async()=>{var P;try{const R=N.slice(1),F=((P=(await ia(R,10)).data)==null?void 0:P.data)||[];d(F)}catch(R){console.error("Search failed:",R),d([])}finally{h(!1)}},300)},A=async N=>{try{await ra({userId:N.userId,email:N.email,displayName:N.displayName,firstName:N.firstName,lastName:N.lastName,department:N.department,phone:N.phone,mobilePhone:N.mobilePhone,designation:N.designation,jobTitle:N.jobTitle,manager:N.manager,employeeId:N.employeeId,employeeNumber:N.employeeNumber,secondEmail:N.secondEmail,location:N.location}),i(N.email),u(N),d([]),h(!1)}catch(P){console.error("Failed to ensure user exists:",P),y({open:!0,type:"error",email:N.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(pt,{open:t,onOpenChange:_,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:_,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:l,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(gt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center",children:e.jsx(ht,{className:"w-5 h-5 text-purple-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Spectator"})]})}),e.jsxs("div",{ref:b,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a spectator to this request. They will receive notifications but cannot approve or reject."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ci,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Oe,{type:"text",placeholder:"@username or user@example.com",value:n,onChange:N=>D(N.target.value),className:"pl-10 h-11 border-gray-300",disabled:l,autoFocus:!0}),(m||c.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:m?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):c.length>0?e.jsx("ul",{className:"divide-y",children:c.map(N=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>A(N),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zt,{className:"h-8 w-8",children:e.jsx(Jt,{className:"bg-purple-100 text-purple-800 text-xs font-semibold",children:(N.displayName||N.email).split(" ").map(P=>P[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:N.displayName||[N.firstName,N.lastName].filter(Boolean).join(" ")||N.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:N.email}),N.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:N.designation})]})]})},N.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:_,className:"flex-1 h-11 border-gray-300",disabled:l,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:S,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:l||!n.trim(),children:[e.jsx(ht,{className:"w-4 h-4 mr-2"}),l?"Adding...":"Add Spectator"]})]})]}),e.jsx(pt,{open:f.open,onOpenChange:N=>y(P=>({...P,open:N})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:f.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[f.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:f.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Ni,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),f.type==="error"&&e.jsxs(e.Fragment,{children:[f.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:f.email}),"."]}),f.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:f.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:()=>y(N=>({...N,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})}),e.jsx(Fn,{open:v.open,onClose:()=>w({open:!1,violations:[]}),violations:v.violations,policyDetails:{maxApprovalLevels:C.maxApprovalLevels,maxParticipants:C.maxParticipants,allowSpectators:C.allowSpectators,maxSpectators:C.maxSpectators}})]})}function $p({open:t,onClose:s,onConfirm:a,existingParticipants:r=[],currentLevels:n=[],maxApprovalLevels:i,onPolicyViolation:l}){const[o,c]=p.useState(""),[d,m]=p.useState(24),[h,x]=p.useState(null),[u,g]=p.useState(!1),[b,f]=p.useState([]),[y,v]=p.useState(!1),[w,C]=p.useState(null),k=p.useRef(null),S=p.useRef(null),[_,D]=p.useState({open:!1,type:"error",email:"",message:""}),A=n.filter(j=>j&&(j.status==="approved"||j.status==="rejected"||j.status==="skipped")),N=Math.max(1,A.length+1),P=Math.max(1,n.length+1),R=P>=N?Array.from({length:P-N+1},(j,U)=>N+U):[N];p.useEffect(()=>{R.length>0&&h===null&&x(R[0]||null)},[R.length,h]);const O=async()=>{var G,ce;const j=o.trim().toLowerCase();if(!j){D({open:!0,type:"error",email:"",message:"Please enter an email address"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(j)){D({open:!0,type:"error",email:j,message:"Please enter a valid email address"});return}if(!d||d<=0){D({open:!0,type:"error",email:"",message:"Please enter valid TAT hours (minimum 1 hour)"});return}if(d>720){D({open:!0,type:"error",email:"",message:"TAT hours cannot exceed 720 hours (30 days)"});return}if(!h){D({open:!0,type:"error",email:"",message:"Please select an approval level"});return}if(h0?Math.max(...n.map(te=>te.levelNumber),0):0,M=h>I?h:I+1;if(i&&M>i){l?l([{type:"Maximum Approval Levels Exceeded",message:`Adding an approver at level ${h} would result in ${M} approval levels, which exceeds the maximum allowed (${i}). Please remove an approver or contact your administrator.`,currentValue:M,maxValue:i}]):D({open:!0,type:"error",email:"",message:`Cannot add approver. This would exceed the maximum allowed approval levels (${i}). Current request has ${I} level(s).`});return}const W=r.find(te=>(te.email||"").toLowerCase()===j);if(W){const te=((G=W.participantType)==null?void 0:G.toUpperCase())||"PARTICIPANT",L=W.name||j;if(te==="INITIATOR"){D({open:!0,type:"error",email:j,message:`${L} is the request initiator and cannot be added as an approver.`});return}else if(te==="APPROVER"){D({open:!0,type:"error",email:j,message:`${L} is already an approver on this request.`});return}else if(te==="SPECTATOR"){D({open:!0,type:"error",email:j,message:`${L} is currently a spectator on this request and cannot be added as an approver. Please remove them as spectator first.`});return}else{D({open:!0,type:"error",email:j,message:`${L} is already a participant on this request.`});return}}if(!w||w.email.toLowerCase()!==j)try{const L=((ce=(await ia(j,1)).data)==null?void 0:ce.data)||[];if(L.length===0){D({open:!0,type:"not-found",email:j,message:""});return}const z=L[0];await ra({userId:z.userId,email:z.email,displayName:z.displayName,firstName:z.firstName,lastName:z.lastName,department:z.department,phone:z.phone,mobilePhone:z.mobilePhone,designation:z.designation,jobTitle:z.jobTitle,manager:z.manager,employeeId:z.employeeId,employeeNumber:z.employeeNumber,secondEmail:z.secondEmail,location:z.location})}catch(te){console.error("Failed to validate approver:",te),D({open:!0,type:"error",email:j,message:"Failed to validate user. Please try again."});return}try{g(!0),await a(j,d,h),c(""),m(24),x(null),C(null),s()}catch(te){console.error("Failed to add approver:",te)}finally{g(!1)}},F=()=>{u||(c(""),m(24),x(null),C(null),f([]),v(!1),s())},$=j=>{const U=j.toLowerCase();return U==="approved"?e.jsx(De,{className:"w-4 h-4 text-green-600"}):U==="rejected"?e.jsx(wt,{className:"w-4 h-4 text-red-600"}):U==="skipped"?e.jsx(ze,{className:"w-4 h-4 text-orange-600"}):U==="in-review"||U==="pending"?e.jsx(st,{className:"w-4 h-4 text-blue-600"}):e.jsx(st,{className:"w-4 h-4 text-gray-400"})};p.useEffect(()=>{b.length>0&&S.current&&S.current.scrollTo({top:S.current.scrollHeight,behavior:"smooth"})},[b.length]),p.useEffect(()=>()=>{k.current&&clearTimeout(k.current)},[]);const V=j=>{if(c(j),w&&w.email.toLowerCase()!==j.toLowerCase()&&C(null),k.current&&clearTimeout(k.current),!j||!j.startsWith("@")||j.length<2){f([]),v(!1);return}v(!0),k.current=setTimeout(async()=>{var U;try{const I=j.slice(1),W=((U=(await ia(I,10)).data)==null?void 0:U.data)||[];f(W)}catch(I){console.error("Search failed:",I),f([])}finally{v(!1)}},300)},T=async j=>{try{await ra({userId:j.userId,email:j.email,displayName:j.displayName,firstName:j.firstName,lastName:j.lastName,department:j.department,phone:j.phone,mobilePhone:j.mobilePhone,designation:j.designation,jobTitle:j.jobTitle,manager:j.manager,employeeId:j.employeeId,employeeNumber:j.employeeNumber,secondEmail:j.secondEmail,location:j.location}),c(j.email),C(j),f([]),v(!1)}catch(U){console.error("Failed to ensure user exists:",U),D({open:!0,type:"error",email:j.email,message:"Failed to verify user in database. Please try again."})}};return e.jsxs(pt,{open:t,onOpenChange:F,children:[e.jsxs(dt,{className:"sm:max-w-md min-h-[60vh] max-h-[90vh] flex flex-col p-0",children:[e.jsxs("button",{onClick:F,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none z-50",disabled:u,children:[e.jsx(ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),e.jsx(gt,{className:"px-6 pt-6 pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center",children:e.jsx(cs,{className:"w-5 h-5 text-blue-600"})}),e.jsx(mt,{className:"text-xl font-bold text-gray-900",children:"Add Approver"})]})}),e.jsxs("div",{ref:S,className:"space-y-4 px-6 py-4 pb-8 overflow-y-auto flex-1",children:[e.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:"Add a new approver at a specific level. Existing approvers at and after the selected level will be shifted down."}),i&&e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-2",children:e.jsxs("p",{className:"text-xs text-blue-800",children:["โ„น๏ธ Max: ",i," level",i!==1?"s":"",n.length>0&&e.jsxs("span",{className:"ml-2",children:["(",Math.max(...n.map(j=>j.levelNumber),0),"/",i,")"]})]})}),n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-semibold text-gray-700",children:"Current Approval Levels"}),e.jsx("div",{className:"max-h-40 overflow-y-auto space-y-2 border rounded-lg p-3 bg-gray-50",children:n.map(j=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-md ${j.status==="approved"?"bg-green-100 border border-green-200":j.status==="rejected"?"bg-red-100 border border-red-200":j.status==="skipped"?"bg-orange-100 border border-orange-200":"bg-white border border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-blue-600 text-white text-xs font-semibold flex items-center justify-center",children:j.levelNumber}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:j.approverName}),e.jsxs("p",{className:"text-xs text-gray-500",children:[j.tatHours,"h TAT"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[$(j.status),e.jsx(ne,{variant:"outline",className:`text-xs ${j.status==="approved"?"bg-green-50 text-green-700 border-green-300":j.status==="rejected"?"bg-red-50 text-red-700 border-red-300":j.status==="skipped"?"bg-orange-50 text-orange-700 border-orange-300":"bg-blue-50 text-blue-700 border-blue-300"}`,children:j.status})]})]},j.levelNumber))}),e.jsxs("p",{className:"text-xs text-gray-500",children:["โ„น๏ธ New approver can only be added at level ",N," or higher (after completed levels)"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"Approval Level *"}),e.jsxs(We,{value:(h==null?void 0:h.toString())||"",onValueChange:j=>x(Number(j)),disabled:u,children:[e.jsx(Ye,{className:"h-11 border-gray-300",children:e.jsx(Ge,{placeholder:"Select level"})}),e.jsx(Ke,{children:R.map(j=>e.jsx(Y,{value:j.toString(),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-blue-600"}),e.jsxs("span",{children:["Level ",j]}),j<=n.length&&e.jsxs("span",{className:"text-xs text-gray-500",children:["(will shift existing Level ",j,")"]})]})},j))})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Choose where to insert the new approver. Existing levels will be automatically shifted."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium text-gray-700",children:"TAT (Turn Around Time) *"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{type:"number",min:"1",max:"720",value:d,onChange:j=>m(Number(j.target.value)),className:"h-11 border-gray-300 flex-1",disabled:u,placeholder:"24"}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-600 bg-gray-100 px-3 h-11 rounded-md border border-gray-300",children:[e.jsx(st,{className:"w-4 h-4"}),"hours"]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"Maximum time for this approver to respond (1-720 hours)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email Address *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ci,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 z-10"}),e.jsx(Oe,{type:"text",placeholder:"@username or user@example.com",value:o,onChange:j=>V(j.target.value),className:"pl-10 h-11 border-gray-300",disabled:u,autoFocus:!0}),(y||b.length>0)&&e.jsx("div",{className:"absolute left-0 right-0 top-full mt-1 z-50 border rounded-md bg-white shadow-lg max-h-60 overflow-auto",children:y?e.jsx("div",{className:"p-3 text-sm text-gray-500",children:"Searching users..."}):b.length>0?e.jsx("ul",{className:"divide-y",children:b.map(j=>e.jsx("li",{className:"p-3 cursor-pointer hover:bg-gray-50 transition-colors",onClick:()=>T(j),children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zt,{className:"h-8 w-8",children:e.jsx(Jt,{className:"bg-blue-100 text-blue-800 text-xs font-semibold",children:(j.displayName||j.email).split(" ").map(U=>U[0]).join("").slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:j.displayName||[j.firstName,j.lastName].filter(Boolean).join(" ")||j.email}),e.jsx("p",{className:"text-xs text-gray-600 truncate",children:j.email}),j.designation&&e.jsx("p",{className:"text-xs text-gray-500",children:j.designation})]})]})},j.userId))}):null})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Type ",e.jsx("span",{className:"font-semibold",children:"@username"})," to search for users, or enter email directly."]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t flex-shrink-0 bg-white",children:[e.jsx(E,{type:"button",variant:"outline",onClick:F,className:"flex-1 h-11 border-gray-300",disabled:u,children:"Cancel"}),e.jsxs(E,{type:"button",onClick:O,className:"flex-1 h-11 bg-[#1a472a] hover:bg-[#152e1f] text-white",disabled:u||!o.trim()||!h||!d,children:[e.jsx(cs,{className:"w-4 h-4 mr-2"}),u?"Adding...":`Add at Level ${h||"?"}`]})]})]}),e.jsx(pt,{open:_.open,onOpenChange:j=>D(U=>({...U,open:j})),children:e.jsxs(dt,{className:"sm:max-w-md",children:[e.jsxs(gt,{children:[e.jsx(mt,{className:"flex items-center gap-2",children:_.type==="not-found"?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"User Not Found"]}):e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-5 h-5 text-red-600"}),"Validation Error"]})}),e.jsx(Dt,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[_.type==="not-found"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-gray-700",children:["User ",e.jsx("strong",{children:_.email})," was not found in the organization directory."]}),e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-sm text-red-800 font-semibold",children:"Please verify:"}),e.jsxs("ul",{className:"text-sm text-red-700 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Email address is spelled correctly"}),e.jsx("li",{children:"User exists in Okta/SSO system"}),e.jsx("li",{children:"User has an active account"})]})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-blue-800 flex items-center gap-1",children:[e.jsx(Ni,{className:"w-4 h-4"}),e.jsx("strong",{children:"Tip:"})," Use ",e.jsx("span",{className:"font-mono bg-blue-100 px-1 rounded",children:"@"})," sign to search users from the directory."]})})]}),_.type==="error"&&e.jsxs(e.Fragment,{children:[_.email&&e.jsxs("p",{className:"text-gray-700",children:["Failed to validate ",e.jsx("strong",{children:_.email}),"."]}),_.message&&e.jsx("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-3",children:e.jsx("p",{className:"text-sm text-gray-700",children:_.message})})]})]})})]}),e.jsx(Tt,{children:e.jsx(E,{onClick:()=>D(j=>({...j,open:!1})),className:"w-full sm:w-auto",children:"OK"})})]})})]})}const KS=t=>{switch(t){case"online":return"bg-green-500";case"away":return"bg-yellow-500";case"offline":return"bg-gray-400";default:return"bg-gray-400"}},XS=t=>{switch(t){case"online":return"Online";case"away":return"Away";case"offline":return"Offline";default:return"Unknown"}},ZS=t=>{const s=t.replace(/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,(a,r,n,i)=>{const l=n+a.length,o=i[l];return!o||/\s|[.,!?;:]|@/.test(o)?'@'+r+"":a}).replace(/\n/g,"
");return ba(s)},JS=t=>t<1024?t+" B":t<1024*1024?(t/1024).toFixed(1)+" KB":(t/(1024*1024)).toFixed(1)+" MB",wu=({type:t})=>{const s="w-4 h-4",a=t.toLowerCase();return a.includes("pdf")?e.jsx(Re,{className:`${s} text-red-600`}):a.includes("excel")||a.includes("spreadsheet")||a.includes("xlsx")?e.jsx(d0,{className:`${s} text-green-600`}):a.includes("powerpoint")||a.includes("presentation")||a.includes("pptx")?e.jsx(Re,{className:`${s} text-orange-600`}):a.includes("word")||a.includes("document")||a.includes("docx")?e.jsx(Re,{className:`${s} text-blue-600`}):a.includes("image")||a.includes("png")||a.includes("jpg")||a.includes("jpeg")||a.includes("gif")||a.includes("webp")?e.jsx(Wn,{className:`${s} text-purple-600`}):e.jsx(vi,{className:`${s} text-gray-600`})};function Op({requestId:t,messages:s,onSend:a,skipSocketJoin:r=!1,requestTitle:n,onAttachmentsExtracted:i,isInitiator:l=!1,isSpectator:o=!1,currentLevels:c=[],onAddApprover:d,maxApprovalLevels:m,onPolicyViolation:h}){const x=Ea(),u=t||x.requestId||"",[g,b]=p.useState(""),[f,y]=p.useState(""),[v,w]=p.useState(!1),[C,k]=p.useState([]),[S,_]=p.useState(!1),[D,A]=p.useState([]),[N,P]=p.useState(null),[R,O]=p.useState(null),[F,$]=p.useState(!1),[V,T]=p.useState(!1),[j,U]=p.useState(!1),[I,M]=p.useState({success:!0,title:"",message:""}),W=p.useRef(null),G=p.useRef(null),ce=p.useRef(null),te=p.useRef(!1),[L,z]=p.useState({maxFileSizeMB:10,allowedFileTypes:["pdf","doc","docx","xls","xlsx","ppt","pptx","jpg","jpeg","png","gif"]}),[H,ye]=p.useState({open:!1,errors:[]}),ae=p.useMemo(()=>({id:u,title:n||"Request Details"}),[u,n]),[me,Q]=p.useState([]),oe=me.filter(X=>X.status==="online"),Ce=C.filter(X=>X.content.toLowerCase().includes(f.toLowerCase())||X.user.name.toLowerCase().includes(f.toLowerCase())),Ee=p.useMemo(()=>o!==void 0?o:!N||me.length===0?!1:me.some(X=>{const we=X.userId||X.user_id,J=(X.role||"").toString().toUpperCase(),Le=(X.participantType||X.participant_type||"").toString().toUpperCase();return we===N&&(J==="SPECTATOR"||Le==="SPECTATOR")}),[o,N,me]);p.useEffect(()=>{},[me]),p.useEffect(()=>{!u||!N||s||(async()=>{try{const X=await Fr(u),we=Array.isArray(X)?X.map(J=>{const Le=J.userId||J.user_id;return{id:J.noteId||J.id||String(Math.random()),user:{name:J.userName||"User",avatar:(J.userName||"U").slice(0,2).toUpperCase(),role:J.userRole||"Participant"},content:J.message||"",timestamp:J.createdAt||new Date().toISOString(),isCurrentUser:Le===N,attachments:Array.isArray(J.attachments)?J.attachments.map(Fe=>({attachmentId:Fe.attachmentId||Fe.attachment_id,name:Fe.fileName||Fe.file_name||Fe.name,fileName:Fe.fileName||Fe.file_name||Fe.name,url:Fe.storageUrl||Fe.storage_url||Fe.url||"#",type:Fe.fileType||Fe.file_type||Fe.type||"file",fileType:Fe.fileType||Fe.file_type||Fe.type||"file",fileSize:Fe.fileSize||Fe.file_size})):void 0}}):[];k(we)}catch(X){console.error("[WorkNoteChat] Failed to load messages:",X)}})()},[u,N,s]);const be=p.useMemo(()=>{const X=[];return C.forEach(we=>{we.attachments&&we.attachments.length>0&&we.attachments.forEach(J=>{X.push({attachmentId:J.attachmentId||J.attachment_id,name:J.fileName||J.file_name||J.name||"Untitled",fileName:J.fileName||J.file_name||J.name||"Untitled",size:J.fileSize||J.file_size,type:J.fileType||J.file_type||J.type||"file",uploadedBy:we.user.name,uploadedAt:we.timestamp,url:J.storageUrl||J.storage_url||J.url||"#"})})}),X},[C]);p.useEffect(()=>{i&&be.length>=0&&i(be)},[be,i]);const q=p.useMemo(()=>me.map(X=>({email:(X.email||"").toLowerCase(),participantType:X.role==="Initiator"?"INITIATOR":X.role==="Approver"?"APPROVER":X.role==="Spectator"?"SPECTATOR":"PARTICIPANT",name:X.name})),[me]),ue=X=>{if(!X)return"Participant";switch(X.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()}},Ae=()=>{var X;(X=W.current)==null||X.scrollIntoView({behavior:"smooth"})};p.useEffect(()=>{Ae()},[C]);const Ue=X=>{switch(X.toUpperCase()){case"INITIATOR":return"Initiator";case"APPROVER":return"Approver";case"SPECTATOR":return"Spectator";default:return X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()}};p.useEffect(()=>{te.current||u&&(async()=>{try{const X=await vs(u),we=Array.isArray(X==null?void 0:X.participants)?X.participants:[];if(we.length===0)return;const J=we.map(Me=>{const Ze=Me.participantType||Me.participant_type||"participant",Be=Me.userId||Me.user_id||"";return{name:Me.userName||Me.user_name||Me.user_email||Me.userEmail||"User",avatar:(Me.userName||Me.user_name||Me.user_email||"U").toString().split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ue(Ze.toString()),status:"offline",email:Me.userEmail||Me.user_email||"",permissions:["read","write","mention"],userId:Be}});te.current=!0,Q(J);let Le=0;const Fe=3,Ve=()=>{ce.current&&ce.current.connected?(ce.current.emit("request:online-users",{requestId:u}),Le++,Le()=>{u&&(te.current=!1)},[u]),p.useEffect(()=>{const X=localStorage.getItem("userData");if(X)try{const we=JSON.parse(X),J=(we==null?void 0:we.id)||(we==null?void 0:we.userId)||(we==null?void 0:we.user_id)||null;P(J)}catch(we){console.error("[WorkNoteChat] Failed to parse userData:",we)}},[]),p.useEffect(()=>{(async()=>{try{const we=await Ys("DOCUMENT_POLICY"),J={};we.forEach(Me=>{J[Me.configKey]=Me.configValue});const Le=parseInt(J.MAX_FILE_SIZE_MB||"10"),Ve=(J.ALLOWED_FILE_TYPES||"pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif").split(",").map(Me=>Me.trim().toLowerCase());z({maxFileSizeMB:Le,allowedFileTypes:Ve})}catch(we){console.error("Failed to load document policy:",we)}})()},[]),p.useEffect(()=>{if(!N)return;let X=u;return(async()=>{var we;try{const J=await vs(u);(we=J==null?void 0:J.workflow)!=null&&we.requestId&&(X=J.workflow.requestId)}catch{}try{const J=Lr();r?Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)):(Ml(J,X,N),Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)));const Le=at=>{const et=(at==null?void 0:at.note)||at;if(!et)return;const yt=et.noteId||et.id;k(rs=>{if(rs.some(St=>St.id===yt))return rs;const Pt=et.userName||et.user_name||"User",la=et.userRole||et.user_role,pa=ue(la),Fa=et.userId||et.user_id,wa={id:yt||String(Date.now()),user:{name:Pt,avatar:Pt.split(" ").map(St=>St[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:pa},content:et.message||"",timestamp:et.createdAt||new Date().toISOString(),isCurrentUser:Fa===N,attachments:Array.isArray(et.attachments)?et.attachments.map(St=>({attachmentId:St.attachmentId||St.attachment_id,name:St.fileName||St.file_name||St.name,fileName:St.fileName||St.file_name||St.name,url:St.storageUrl||St.storage_url||St.url||"#",type:St.fileType||St.file_type||St.type||"file",fileType:St.fileType||St.file_type||St.type||"file",fileSize:St.fileSize||St.file_size})):void 0};return[...rs,wa]})},Fe=at=>{Q(et=>et.length===0||!et.find(Pt=>Pt.userId===at.userId)?et:et.map(Pt=>Pt.userId===at.userId?{...Pt,status:"online"}:Pt))},Ve=at=>{at.userId!==N&&Q(et=>et.length===0||!et.find(Pt=>Pt.userId===at.userId)?et:et.map(Pt=>Pt.userId===at.userId?{...Pt,status:"offline"}:Pt))},Me=at=>{Q(et=>et.length===0?et:et.map(rs=>{const Pt=rs.userId||"";if(Pt===N)return{...rs,status:"online"};const pa=at.userIds.includes(Pt);return{...rs,status:pa?"online":"offline"}}))},Ze=()=>{Q(at=>at.map(yt=>yt.userId===N?{...yt,status:"online"}:yt)),r||Ml(J,X,N),te.current&&(J.emit("request:online-users",{requestId:X}),setTimeout(()=>J.emit("request:online-users",{requestId:X}),300),setTimeout(()=>J.emit("request:online-users",{requestId:X}),800))},Be=at=>{console.error("[WorkNoteChat] โŒ Socket error:",at)},qe=at=>{console.warn("[WorkNoteChat] โš ๏ธ Socket disconnected:",at),Q(et=>et.map(yt=>yt.userId===N?yt:{...yt,status:"offline"}))},fs=at=>{at.includes("presence")||at.includes("worknote")||at.includes("request")};J.on("connect",Ze),J.on("disconnect",qe),J.on("error",Be),J.on("worknote:new",Le),J.on("presence:join",Fe),J.on("presence:leave",Ve),J.on("presence:online",Me),J.onAny(fs),ce.current=J,J.connected&&te.current&&(J.emit("request:online-users",{requestId:X}),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},300),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},800),setTimeout(()=>{J.emit("request:online-users",{requestId:X})},1500));const Ht=()=>{J.off("connect",Ze),J.off("disconnect",qe),J.off("error",Be),J.off("worknote:new",Le),J.off("presence:join",Fe),J.off("presence:leave",Ve),J.off("presence:online",Me),J.offAny(fs),r||Ax(J,X),ce.current=null};window.__wn_cleanup=Ht}catch{}})(),()=>{var we;try{(we=window.__wn_cleanup)==null||we.call(window)}catch{}}},[u,N,r]);const Z=async()=>{if(g.trim()||D.length>0){const X=Xs(g),we=X.map(Fe=>{const Ve=me.find(Me=>Me.name.toLowerCase().includes(Fe.toLowerCase()));return Ve==null?void 0:Ve.userId}).filter(Boolean),J=D.map(Fe=>({name:Fe.name,url:URL.createObjectURL(Fe),type:Fe.type.split("/")[1]||"file"})),Le={id:Date.now().toString(),user:{name:"You",avatar:"YO",role:"Current User"},content:g,timestamp:new Date().toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",hour12:!0}),mentions:X,isHighPriority:g.includes("!important")||g.includes("urgent"),attachments:J.length>0?J:void 0,isCurrentUser:!0};if(a)try{await a(g,D)}catch{}else try{await Bx(u,{message:g,mentions:we},D);const Fe=await Fr(u),Ve=Array.isArray(Fe)?Fe.map(Me=>{const Ze=Me.userId||Me.user_id;return{id:Me.noteId||Me.id||String(Math.random()),user:{name:Me.userName||"User",avatar:(Me.userName||"U").slice(0,2).toUpperCase(),role:Me.userRole||"Participant"},content:Me.message||"",timestamp:Me.createdAt||new Date().toISOString(),isCurrentUser:Ze===N,attachments:Array.isArray(Me.attachments)?Me.attachments.map(Be=>({attachmentId:Be.attachmentId||Be.attachment_id,name:Be.fileName||Be.file_name||Be.name,fileName:Be.fileName||Be.file_name||Be.name,url:Be.storageUrl||Be.storage_url||Be.url||"#",type:Be.fileType||Be.file_type||Be.type||"file",fileType:Be.fileType||Be.file_type||Be.type||"file",fileSize:Be.fileSize||Be.file_size})):void 0}}):[];k(Ve)}catch{k(Fe=>[...Fe,Le])}b(""),A([])}};p.useEffect(()=>{if(s&&Array.isArray(s))try{const we=s.filter(J=>(J.type||"").toLowerCase()!=="sla_warning").map(J=>{var Fe;if(J.type||J.activityType||J.isSystem)return{id:J.id||`activity-${J.timestamp||Date.now()}-${Math.random()}`,user:{name:"System",avatar:"SY",role:"System"},content:J.details||J.action||J.content||"",timestamp:J.timestamp||J.createdAt||J.created_at||new Date().toISOString(),isSystem:!0,isCurrentUser:!1};{const Ve=J.userName||J.user_name||((Fe=J.user)==null?void 0:Fe.name)||"User",Me=J.userRole||J.user_role,Ze=ue(Me),Be=J.userId||J.user_id;return{id:J.noteId||J.note_id||J.id||String(Math.random()),user:{name:Ve,avatar:Ve.split(" ").map(qe=>qe[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ze},content:J.message||J.content||"",timestamp:J.createdAt||J.created_at||J.timestamp||new Date().toISOString(),isSystem:!1,attachments:Array.isArray(J.attachments)?J.attachments.map(qe=>({attachmentId:qe.attachmentId||qe.attachment_id,name:qe.fileName||qe.file_name||qe.name,fileName:qe.fileName||qe.file_name||qe.name,url:qe.storageUrl||qe.storage_url||qe.url||"#",type:qe.fileType||qe.file_type||qe.type||"file",fileType:qe.fileType||qe.file_type||qe.type||"file",fileSize:qe.fileSize||qe.file_size})):void 0,isCurrentUser:Be===N}}}).sort((J,Le)=>new Date(J.timestamp).getTime()-new Date(Le.timestamp).getTime());k(we)}catch(X){console.error("[WorkNoteChat] Error mapping messages:",X)}else(async()=>{try{const X=await Fr(u),we=Array.isArray(X)?X.map(J=>{const Le=J.userName||J.user_name||"User",Fe=J.userRole||J.user_role,Ve=ue(Fe),Me=J.userId||J.user_id;return{id:J.noteId||J.note_id||J.id||String(Math.random()),user:{name:Le,avatar:Le.split(" ").map(Ze=>Ze[0]).filter(Boolean).join("").slice(0,2).toUpperCase(),role:Ve},content:J.message||"",timestamp:J.createdAt||J.created_at||new Date().toISOString(),attachments:Array.isArray(J.attachments)?J.attachments.map(Ze=>({attachmentId:Ze.attachmentId||Ze.attachment_id,name:Ze.fileName||Ze.file_name||Ze.name,fileName:Ze.fileName||Ze.file_name||Ze.name,url:Ze.storageUrl||Ze.storage_url||Ze.url||"#",type:Ze.fileType||Ze.file_type||Ze.type||"file",fileType:Ze.fileType||Ze.file_type||Ze.type||"file",fileSize:Ze.fileSize||Ze.file_size})):void 0,isCurrentUser:Me===N}}):[];k(we)}catch(X){console.error("[WorkNoteChat] Error loading work notes:",X)}})()},[s,u,me]);const Te=X=>{const we=L.maxFileSizeMB*1024*1024;if(X.size>we)return{valid:!1,reason:`File size exceeds the maximum allowed size of ${L.maxFileSizeMB}MB. Current size: ${(X.size/(1024*1024)).toFixed(2)}MB`};const J=X.name.toLowerCase(),Le=J.substring(J.lastIndexOf(".")+1);return L.allowedFileTypes.includes(Le)?{valid:!0}:{valid:!1,reason:`File type "${Le}" is not allowed. Allowed types: ${L.allowedFileTypes.join(", ")}`}},Xe=X=>{if(!X.target.files||X.target.files.length===0)return;const we=Array.from(X.target.files),J=[],Le=[];we.forEach(Fe=>{const Ve=Te(Fe);Ve.valid?Le.push(Fe):J.push({fileName:Fe.name,reason:Ve.reason||"Unknown validation error"})}),J.length>0&&ye({open:!0,errors:J}),Le.length>0&&(A(Fe=>[...Fe,...Le]),Le.length{A(we=>we.filter((J,Le)=>Le!==X)),G.current&&(G.current.value="")},_e=X=>{b(we=>we+X),w(!1)},rt=()=>{var X;(X=G.current)==null||X.click()},ut=async X=>{var we,J;try{await zx(u,X);const Le=await vs(u),Fe=Array.isArray(Le==null?void 0:Le.participants)?Le.participants:[];if(Fe.length){const Ve=Fe.map(Me=>{const Ze=Me.participantType||Me.participant_type||"participant",Be=Me.userId||Me.user_id||"",qe=Me.userName||Me.user_name||Me.userEmail||Me.user_email||"User",fs=Me.userEmail||Me.user_email||"",Ht=qe.split(" ").map(at=>at[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:qe,avatar:Ht,role:Ue(Ze),status:"offline",email:fs,lastSeen:void 0,permissions:["read"],userId:Be}});Q(Ve),ce.current&&ce.current.connected&&ce.current.emit("request:online-users",{requestId:u})}$(!1),M({success:!0,title:"Spectator Added",message:"Spectator added successfully. They can now view this request."}),U(!0)}catch(Le){throw console.error("Failed to add spectator:",Le),M({success:!1,title:"Failed to Add Spectator",message:((J=(we=Le==null?void 0:Le.response)==null?void 0:we.data)==null?void 0:J.error)||"Failed to add spectator. Please try again."}),U(!0),Le}},nt=async(X,we,J)=>{var Le,Fe;if(d)await d(X,we,J),T(!1);else try{await Vx(u,X,we,J);const Ve=await vs(u),Me=Array.isArray(Ve==null?void 0:Ve.participants)?Ve.participants:[];if(Me.length){const Ze=Me.map(Be=>{const qe=Be.participantType||Be.participant_type||"participant",fs=Be.userId||Be.user_id||"",Ht=Be.userName||Be.user_name||Be.userEmail||Be.user_email||"User",at=Be.userEmail||Be.user_email||"",et=Ht.split(" ").map(yt=>yt[0]).filter(Boolean).join("").slice(0,2).toUpperCase();return{name:Ht,avatar:et,role:Ue(qe),status:"offline",email:at,lastSeen:void 0,permissions:["read"],userId:fs}});Q(Ze),ce.current&&ce.current.connected&&ce.current.emit("request:online-users",{requestId:u})}T(!1),M({success:!0,title:"Approver Added",message:`Approver added successfully at Level ${J} with ${we}h TAT`}),U(!0)}catch(Ve){throw console.error("Failed to add approver:",Ve),M({success:!1,title:"Failed to Add Approver",message:((Fe=(Le=Ve==null?void 0:Ve.response)==null?void 0:Le.data)==null?void 0:Fe.error)||"Failed to add approver. Please try again."}),U(!0),Ve}},Ps=["๐Ÿ˜Š","๐Ÿ˜‚","๐Ÿคฃ","๐Ÿ˜","๐Ÿ˜ƒ","๐Ÿ˜„","๐Ÿ˜…","๐Ÿ˜†","๐Ÿ˜‰","๐Ÿ˜Œ","๐Ÿ˜","๐Ÿฅฐ","๐Ÿ˜˜","๐Ÿ˜—","๐Ÿ˜™","๐Ÿ˜š","๐Ÿ™‚","๐Ÿค—","๐Ÿคฉ","๐Ÿค”","๐Ÿคจ","๐Ÿ˜","๐Ÿ˜‘","๐Ÿ˜ถ","๐Ÿ™„","๐Ÿ˜","๐Ÿ˜’","๐Ÿ™ƒ","๐Ÿ˜ฌ","๐Ÿค","๐Ÿ˜ด","๐Ÿ˜ช","๐Ÿ˜ต","๐Ÿคฏ","๐Ÿคช","๐Ÿ˜œ","๐Ÿ˜","๐Ÿ˜›","๐Ÿคค","๐Ÿ˜‹","๐Ÿ˜Ž","๐Ÿค“","๐Ÿง","๐Ÿ˜•","๐Ÿ˜Ÿ","๐Ÿ™","โ˜น๏ธ","๐Ÿ˜ฎ","๐Ÿ˜ฏ","๐Ÿ˜ฒ","๐Ÿ˜ณ","๐Ÿฅบ","๐Ÿ˜ฆ","๐Ÿ˜ง","๐Ÿ˜จ","๐Ÿ˜ฐ","๐Ÿ˜ฅ","๐Ÿ˜ข","๐Ÿ˜ญ","๐Ÿ˜ฑ","๐Ÿ˜–","๐Ÿ˜ฃ","๐Ÿ˜ž","๐Ÿ˜“","๐Ÿ˜ฉ","๐Ÿ˜ซ","๐Ÿฅฑ","๐Ÿ˜ค","๐Ÿ˜ก","๐Ÿ˜ ","๐Ÿคฌ","๐Ÿ˜ˆ","๐Ÿ‘ฟ","๐Ÿ’€","โ˜ ๏ธ","๐Ÿ’ฉ","๐Ÿคก","๐Ÿ‘น","๐Ÿ‘บ","๐Ÿ‘ป","๐Ÿ‘‹","๐Ÿคš","๐Ÿ–๏ธ","โœ‹","๐Ÿ––","๐Ÿ‘Œ","๐ŸคŒ","๐Ÿค","โœŒ๏ธ","๐Ÿคž","๐ŸคŸ","๐Ÿค˜","๐Ÿค™","๐Ÿ‘ˆ","๐Ÿ‘‰","๐Ÿ‘†","๐Ÿ–•","๐Ÿ‘‡","โ˜๏ธ","๐Ÿ‘","๐Ÿ‘Ž","โœŠ","๐Ÿ‘Š","๐Ÿค›","๐Ÿคœ","๐Ÿ‘","๐Ÿ™Œ","๐Ÿ‘","๐Ÿคฒ","๐Ÿค","๐Ÿ™","๐Ÿ’ช","๐Ÿฆพ","๐Ÿฆฟ","๐Ÿฆต","๐Ÿฆถ","๐Ÿ‘‚","๐Ÿฆป","๐Ÿ‘ƒ","๐Ÿง ","โค๏ธ","๐Ÿงก","๐Ÿ’›","๐Ÿ’š","๐Ÿ’™","๐Ÿ’œ","๐Ÿ–ค","๐Ÿค","๐ŸคŽ","๐Ÿ’”","โฃ๏ธ","๐Ÿ’•","๐Ÿ’ž","๐Ÿ’“","๐Ÿ’—","๐Ÿ’–","๐Ÿ’˜","๐Ÿ’","๐Ÿ’Ÿ","โค๏ธโ€๐Ÿ”ฅ","๐Ÿ’ผ","๐Ÿ“Š","๐Ÿ“ˆ","๐Ÿ“‰","๐Ÿ’ป","โŒจ๏ธ","๐Ÿ–ฅ๏ธ","๐Ÿ–จ๏ธ","๐Ÿ–ฑ๏ธ","๐Ÿ’พ","๐Ÿ’ฟ","๐Ÿ“ฑ","โ˜Ž๏ธ","๐Ÿ“ž","๐Ÿ“Ÿ","๐Ÿ“ ","๐Ÿ“ง","โœ‰๏ธ","๐Ÿ“จ","๐Ÿ“ฉ","๐Ÿ“ฎ","๐Ÿ“ช","๐Ÿ“ซ","๐Ÿ“ฌ","๐Ÿ“ญ","๐Ÿ“„","๐Ÿ“ƒ","๐Ÿ“‘","๐Ÿ“","โœ๏ธ","โœ’๏ธ","๐Ÿ–Š๏ธ","๐Ÿ–‹๏ธ","๐Ÿ“","๐Ÿ“","๐Ÿ“Œ","๐Ÿ“","๐Ÿ—‚๏ธ","๐Ÿ“","๐Ÿ“‚","โœ…","โœ”๏ธ","โ˜‘๏ธ","๐ŸŽฏ","๐ŸŽ–๏ธ","๐Ÿ†","๐Ÿฅ‡","๐Ÿฅˆ","๐Ÿฅ‰","โญ","๐ŸŒŸ","โœจ","๐Ÿ’ซ","๐Ÿ”ฅ","๐Ÿ’ฅ","โšก","๐Ÿ’ฏ","๐ŸŽ‰","๐ŸŽŠ","๐ŸŽˆ","โš ๏ธ","๐Ÿšซ","โŒ","โ›”","๐Ÿšท","๐Ÿšฏ","๐Ÿšฑ","๐Ÿšณ","๐Ÿ”ž","๐Ÿ“ต","โ—","โ“","โ•","โ”","โ€ผ๏ธ","โ‰๏ธ","๐Ÿ’ข","๐Ÿ’ฌ","๐Ÿ’ญ","๐Ÿ—ฏ๏ธ","โฐ","โฑ๏ธ","โฒ๏ธ","โณ","โŒ›","๐Ÿ“…","๐Ÿ“†","๐Ÿ—“๏ธ","๐Ÿ“‡","๐Ÿ•","๐Ÿ•‘","๐Ÿ•’","๐Ÿ•“","๐Ÿ•”","๐Ÿ••","๐Ÿ•–","๐Ÿ•—","๐Ÿ•˜","๐Ÿ•™","๐Ÿ•š","๐Ÿš€","๐ŸŽฏ","๐ŸŽฒ","๐ŸŽฐ","๐Ÿงฉ","๐Ÿ”","๐Ÿ”Ž","๐Ÿ”‘","๐Ÿ—๏ธ","๐Ÿ”’","๐Ÿ”“","๐Ÿ”","๐Ÿ”","๐Ÿ””","๐Ÿ”•","๐Ÿ“ฃ","๐Ÿ“ข","๐Ÿ’ก","๐Ÿ”ฆ","๐Ÿฎ","โž•","โž–","โœ–๏ธ","โž—","โ™พ๏ธ","โ€ผ๏ธ","โ‰๏ธ","โ“","โ”","โ•","๐Ÿ”„","๐Ÿ”ƒ","๐Ÿ”‚","โ–ถ๏ธ","โธ๏ธ","โฏ๏ธ","โน๏ธ","โบ๏ธ","โญ๏ธ","โฎ๏ธ","โฉ","โช","โซ","โฌ","โ—€๏ธ","๐Ÿ”ผ","๐Ÿ”ฝ","โžก๏ธ","โฌ…๏ธ","โฌ†๏ธ","โฌ‡๏ธ","โ†—๏ธ","โ†˜๏ธ","โ†™๏ธ","โ†–๏ธ","โ†•๏ธ","โ†”๏ธ","โ†ช๏ธ","โ†ฉ๏ธ","โคด๏ธ"],Xs=X=>{const we=/@(\w+(?:\s+\w+)?)(?=\s|$|[.,!?;:]|@)/g,J=[];let Le;for(;(Le=we.exec(X))!==null;)if(Le[1]){const Fe=Le.index+Le[0].length,Ve=X.slice(Fe),Me=X[Fe];(Ve.startsWith("@")||!Me||/\s|[.,!?;:]|@/.test(Me))&&J.push(Le[1].trim())}return J},Na=X=>{X.key==="Enter"&&!X.shiftKey&&(X.preventDefault(),Z())},Xa=(X,we)=>{k(J=>J.map(Le=>{if(Le.id===X){const Fe=Le.reactions||[],Ve=Fe.find(Me=>Me.emoji===we);if(Ve)if(Ve.users.includes("You")){if(Ve.users=Ve.users.filter(Me=>Me!=="You"),Ve.users.length===0)return{...Le,reactions:Fe.filter(Me=>Me.emoji!==we)}}else Ve.users.push("You");else Fe.push({emoji:we,users:["You"]});return{...Le,reactions:Fe}}return Le}))};return e.jsxs("div",{className:"h-full flex flex-col bg-gray-50 overflow-hidden",children:[e.jsx("div",{className:"bg-white border-b border-gray-200 px-3 sm:px-6 py-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 min-w-0 flex-1",children:[e.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg shrink-0",children:e.jsx(As,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"text-lg sm:text-2xl font-bold text-gray-900",children:"Work Notes"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("p",{className:"text-gray-600 text-sm sm:text-base truncate",children:ae.title}),e.jsx(ne,{variant:"outline",className:"text-xs shrink-0",children:t})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:e.jsxs("div",{className:"flex -space-x-2",children:[oe.slice(0,3).map((X,we)=>e.jsx(Zt,{className:"h-8 w-8 ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:"bg-blue-500 text-white text-xs font-semibold",children:X.avatar})},we)),oe.length>3&&e.jsxs("div",{className:"h-8 w-8 rounded-full bg-gray-100 ring-2 ring-white flex items-center justify-center text-xs font-medium text-gray-600",children:["+",oe.length-3]})]})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>_(!S),className:"lg:hidden",children:e.jsx(cs,{className:"h-4 w-4"})})]})]})}),e.jsxs("div",{className:"flex-1 flex overflow-hidden relative",children:[e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx("div",{className:"bg-white border-b border-gray-200 px-2 sm:px-3 lg:px-6 py-2 sm:py-3 flex-shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx(Oe,{placeholder:"Search messages...",value:f,onChange:X=>y(X.target.value),className:"pl-10 bg-gray-50 border-gray-200 h-9 sm:h-10"})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden px-2 sm:px-3 lg:px-6 py-2 sm:py-4 min-h-0",children:e.jsxs("div",{className:"space-y-3 sm:space-y-6 max-w-full",children:[Ce.map(X=>{const we=X.isCurrentUser||!1;return e.jsxs("div",{className:`flex gap-2 sm:gap-3 lg:gap-4 ${X.isSystem?"justify-center":we?"justify-end":""}`,children:[!X.isSystem&&!we&&e.jsx(Zt,{className:"h-8 w-8 sm:h-10 sm:w-10 lg:h-12 lg:w-12 flex-shrink-0 ring-1 sm:ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:`text-white font-semibold text-xs sm:text-sm ${X.user.role==="Initiator"?"bg-green-600":X.user.role==="Current User"?"bg-blue-500":X.user.role==="System"?"bg-gray-500":"bg-slate-600"}`,children:X.user.avatar})}),e.jsx("div",{className:`${we?"max-w-[70%]":"flex-1"} min-w-0 ${X.isSystem?"text-center max-w-xs sm:max-w-md mx-auto":""}`,children:X.isSystem?e.jsxs("div",{className:"inline-flex items-center gap-2 sm:gap-3 px-3 sm:px-4 py-1.5 sm:py-2 bg-gray-100 rounded-full",children:[e.jsx(kt,{className:"w-3 h-3 sm:w-4 sm:h-4 text-gray-500 flex-shrink-0"}),e.jsx("span",{className:"text-xs sm:text-sm text-gray-700",children:X.content}),e.jsx("span",{className:"text-xs text-gray-500 hidden sm:inline",children:Qt(X.timestamp)})]}):e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2 flex-wrap ${we?"justify-end":""}`,children:[e.jsxs("span",{className:"font-semibold text-gray-900 text-sm sm:text-base truncate",children:[X.user.name," ",we&&e.jsx("span",{className:"text-xs text-gray-500 font-normal",children:"(you)"})]}),e.jsx(ne,{variant:"outline",className:"text-xs flex-shrink-0",children:X.user.role}),e.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1 flex-shrink-0",children:[e.jsx(st,{className:"w-3 h-3"}),Qt(X.timestamp)]}),X.isHighPriority&&e.jsxs(ne,{variant:"destructive",className:"text-xs flex-shrink-0",children:[e.jsx(o0,{className:"w-3 h-3 mr-1"}),"Priority"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 sm:p-4 shadow-sm ${we?"bg-blue-50 border-blue-200":"bg-white border-gray-200"}`,children:[e.jsx("div",{className:"text-gray-800 leading-relaxed text-sm sm:text-base",dangerouslySetInnerHTML:{__html:ZS(X.content)}}),X.attachments&&X.attachments.length>0&&e.jsx("div",{className:"mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-100",children:e.jsx("div",{className:"space-y-2",children:X.attachments.map((J,Le)=>{const Fe=J.fileSize||J.file_size,Ve=J.fileName||J.file_name||J.name,Me=J.fileType||J.file_type||J.type||"",Ze=J.attachmentId||J.attachment_id;return e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 p-2 sm:p-3 bg-gray-50 rounded-lg border border-gray-200 hover:bg-gray-100 transition-colors",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx(wu,{type:Me})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs sm:text-sm font-medium text-gray-700 truncate",children:Ve}),Fe&&e.jsx("p",{className:"text-xs text-gray-500",children:JS(Fe)})]}),Ze&&(()=>{const Be=(Me||"").toLowerCase();return Be.includes("image")||Be.includes("pdf")||Be.includes("jpg")||Be.includes("jpeg")||Be.includes("png")||Be.includes("gif")})()&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-purple-100 hover:text-purple-600",onClick:Be=>{Be.preventDefault(),Be.stopPropagation();const qe=eN(Ze);O({fileName:Ve,fileType:Me,fileUrl:qe,fileSize:Fe,attachmentId:Ze})},title:"Preview file",children:e.jsx(ht,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-8 sm:w-8 p-0 flex-shrink-0 hover:bg-blue-100 hover:text-blue-600",onClick:async Be=>{if(Be.preventDefault(),Be.stopPropagation(),!Ze){K.error("Cannot download: Attachment ID missing");return}try{await Jd(Ze)}catch{K.error("Failed to download file")}},title:"Download file",children:e.jsx(Ct,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]},Le)})})}),X.reactions&&X.reactions.length>0&&e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-100 flex-wrap",children:[X.reactions.map((J,Le)=>e.jsxs("button",{onClick:()=>Xa(X.id,J.emoji),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs sm:text-sm transition-colors flex-shrink-0 ${J.users.includes("You")?"bg-blue-100 text-blue-800 border border-blue-200":"bg-gray-100 text-gray-700 hover:bg-gray-200"}`,children:[e.jsx("span",{children:J.emoji}),e.jsx("span",{className:"text-xs font-medium",children:J.users.length})]},Le)),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 w-6 sm:h-7 sm:w-7 p-0 flex-shrink-0",onClick:()=>w(!v),children:e.jsx(gs,{className:"w-2 h-2 sm:w-3 sm:h-3"})})]})]})]})}),!X.isSystem&&we&&e.jsx(Zt,{className:"h-8 w-8 sm:h-10 sm:w-10 lg:h-12 lg:w-12 flex-shrink-0 ring-1 sm:ring-2 ring-white shadow-sm",children:e.jsx(Jt,{className:"bg-blue-500 text-white font-semibold text-xs sm:text-sm",children:X.user.avatar})})]},X.id)}),e.jsx("div",{ref:W})]})}),e.jsx("div",{className:"bg-white border-t border-gray-200 p-2 sm:p-3 lg:p-6 flex-shrink-0",children:e.jsxs("div",{className:"max-w-full",children:[e.jsx("input",{type:"file",ref:G,onChange:Xe,className:"hidden",multiple:!0,accept:L.allowedFileTypes.map(X=>`.${X}`).join(",")}),D.length>0&&e.jsx("div",{className:"mb-3 space-y-2 max-h-32 overflow-y-auto pr-2",children:D.map((X,we)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-blue-50 rounded-lg border border-blue-200",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx(wu,{type:X.type.split("/")[1]||"file"})}),e.jsx("span",{className:"text-sm text-gray-700 flex-1 truncate min-w-0",children:X.name}),e.jsxs("span",{className:"text-xs text-gray-500 flex-shrink-0",children:[(X.size/1024).toFixed(1)," KB"]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>pe(we),className:"h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0",children:e.jsx(ft,{className:"h-3 w-3 text-red-600"})})]},we))}),e.jsxs("div",{className:"relative mb-2",children:[(()=>{const X=g.lastIndexOf("@"),we=X>=0;if(!we)return null;const J=g.slice(X+1),Le=J.trim(),Fe=J.endsWith(" "),Ve=Le.length>0,Me=Le.includes(" ")&&!Fe,Ze=Fe&&Ve;if(!(we&&J.length<=20&&!Me&&!Ze))return null;const qe=Le.toLowerCase(),fs=me.filter(Ht=>Ht.userId===N?!1:qe?Ht.name.toLowerCase().includes(qe):!0);return e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border-2 border-blue-300 rounded-lg shadow-2xl p-3 z-[100] w-full sm:max-w-md",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900 mb-2",children:"๐Ÿ’ฌ Mention someone"}),e.jsx("div",{className:"max-h-60 overflow-y-auto space-y-1",children:fs.length>0?fs.map((Ht,at)=>e.jsxs("button",{type:"button",onClick:et=>{et.preventDefault(),et.stopPropagation();const yt=g.lastIndexOf("@"),rs=g.slice(0,yt);b(rs+"@"+Ht.name+" ")},className:"w-full flex items-center gap-3 p-3 hover:bg-blue-50 rounded-lg text-left transition-colors border border-transparent hover:border-blue-200",children:[e.jsx(Zt,{className:"h-10 w-10",children:e.jsx(Jt,{className:`text-white text-sm font-semibold ${Ht.role==="Initiator"?"bg-green-600":Ht.role==="Approver"?"bg-purple-600":"bg-blue-500"}`,children:Ht.avatar})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-gray-900",children:Ht.name}),e.jsx("p",{className:"text-xs text-gray-600",children:Ht.role})]})]},at)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:qe?`No participants found matching "${qe}"`:"No other participants available"})})]})})(),e.jsx(Ds,{placeholder:"Type your message... Use @username to mention someone",value:g,onChange:X=>b(X.target.value),onKeyPress:Na,className:"min-h-[50px] sm:min-h-[60px] resize-none border-gray-200 focus:ring-blue-500 focus:border-blue-500 w-full text-sm",rows:2}),v&&e.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-white border border-gray-200 rounded-lg shadow-xl p-3 z-50 w-full sm:w-96 max-h-80 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 sticky top-0 bg-white pb-2 border-b",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-700",children:"Pick an emoji"}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>w(!1),className:"h-6 w-6 p-0",children:e.jsx(ft,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid grid-cols-8 sm:grid-cols-10 gap-1",children:Ps.map((X,we)=>e.jsx("button",{onClick:()=>_e(X),className:"text-xl sm:text-2xl hover:bg-gray-100 rounded p-1 transition-colors flex items-center justify-center",title:X,children:X},we))})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1 sm:gap-2 flex-shrink-0",children:[e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:rt,title:"Attach file",children:e.jsx(vi,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>w(!v),title:"Add emoji",children:e.jsx(c0,{className:"h-4 w-4"})}),e.jsx(E,{variant:"ghost",size:"sm",className:"text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600 flex-shrink-0",onClick:()=>b(X=>X+"@"),title:"Mention someone",children:e.jsx(Ci,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto flex-shrink-0",children:[e.jsxs("span",{className:"text-xs text-gray-500 hidden md:inline whitespace-nowrap",children:[g.length,"/2000"]}),e.jsxs(E,{onClick:Z,disabled:!g.trim()&&D.length===0,className:"bg-blue-600 hover:bg-blue-700 h-8 sm:h-9 px-3 sm:px-4 disabled:opacity-50 disabled:cursor-not-allowed flex-shrink-0",size:"sm",children:[e.jsx(ax,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Send"})]})]})]})]})})]}),S&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:()=>_(!1)}),e.jsxs("div",{className:` w-72 sm:w-80 bg-white border-l border-gray-200 flex flex-col lg:relative lg:translate-x-0 lg:shadow-none ${S?"fixed right-0 top-0 bottom-0 z-50 shadow-xl":"hidden lg:flex"} diff --git a/build/index.html b/build/index.html index d6cebea..0b74d7c 100644 --- a/build/index.html +++ b/build/index.html @@ -13,7 +13,7 @@ - +